How to Load and Display a PDF in ASP.NET Core
Tags: webdev, devops, dotnet, tutorial
Published: 2023-11-07 22:19:05

---
canonical_url: https://developer.mescius.com/blogs/how-to-load-and-display-pdf-in-asp-net-core
description: Learn how to load and display a PDF document in ASP.NET Core. See more and build your application today.
---
PDF is a very old file format that has been used for years to draft information in almost all sectors, whether healthcare, legal, education, or entertainment. This blog introduces how a developer can create a PDF file from scratch using C# and later display and edit the PDF file on the client side using a Javascript-based viewer.

[Grapecity Documents](https://developer.mescius.com/document-solutions "https://developer.mescius.com/document-solutions") provides document solutions for various formats such as PDF, Word, Excel, and Imaging, which lets you either create these files through code or edit the existing ones as per your requirements. Hence, these APIs can be used to automate the document workflow of creating, modifying, saving, and viewing documents of different types. In this blog, we will use [GrapeCity Documents for PDF](https://developer.mescius.com/document-solutions/dot-net-pdf-api "https://developer.mescius.com/document-solutions/dot-net-pdf-api") to create a PDF file and [GrapeCity Documents PDF Viewer](https://developer.mescius.com/document-solutions/javascript-pdf-viewer "https://developer.mescius.com/document-solutions/javascript-pdf-viewer") to load, view, and edit the PDF file on the client side.

So, let’s just take each of these tasks one by one.

## Create PDF on the Server Side<span class="confluence-ssr-app-1afrefi" aria-label="Copy"></span>

**GrapeCity Documents for PDF,** referred to as **GcPdf** hereafter, offers a powerful API that lets you create or edit a PDF file, offering many popular features such as Annotation, Forms, Digital Signatures, Layers, etc. You may refer to the [documentation](https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs "https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs") and [demos](https://developer.mescius.com/document-solutions/dot-net-pdf-api/demos/ "https://developer.mescius.com/document-solutions/dot-net-pdf-api/demos/") for detailed information about all the features offered by GcPdf API.

The steps below will help you understand the basics of creating and saving a PDF file using GcPdf API.

No. 1 - Open Visual Studio 2022 and create a new ASP. NET Core Web Application, choosing the appropriate project template and providing an appropriate project name, here it is **CreatePDF**.

<div class="rich-media-item mediaSingleView-content-wrap image-align-start confluence-ssr-app-1xjjxlc" data-layout="align-start" data-width="50" data-width-type="percentage" data-node-type="mediaSingle">

<div class="confluence-ssr-app-vsn2bx">

<div data-type="file" data-node-type="media" data-width="840" data-height="511" data-id="a10e6002-c1d5-4bee-8a0b-a63d54dd922b" data-collection="contentId-3394142212" data-file-name="I1.png" data-file-size="95370" data-file-mime-type="image/png" data-alt="" data-context-id="3394142212">

<div id="newFileExperienceWrapper" class="new-file-experience-wrapper confluence-ssr-app-9rnxrx" data-testid="media-card-view">

<div class="media-file-card-view confluence-ssr-app-1yn77bd" data-testid="media-file-card-view" data-test-media-name="I1.png" data-test-status="complete" data-test-progress="1">![ASP.NET Core pdf viewer](//cdn.mescius.io/umb/media/rxfdsrje/i1.png?rmode=max&width=758&height=461)</div>

</div>

</div>

</div>

</div>

<div class="rich-media-item mediaSingleView-content-wrap image-align-start confluence-ssr-app-1xjjxlc" data-layout="align-start" data-width="50" data-width-type="percentage" data-node-type="mediaSingle">

<div class="confluence-ssr-app-n3ends">

<div data-type="file" data-node-type="media" data-width="841" data-height="511" data-id="6d5a3a52-0ffb-4048-9ba8-6e7386a4418e" data-collection="contentId-3394142212" data-file-name="I2.png" data-file-size="31452" data-file-mime-type="image/png" data-alt="" data-context-id="3394142212">

<div id="newFileExperienceWrapper" class="new-file-experience-wrapper confluence-ssr-app-1ko0z9q" data-testid="media-card-view">

<div class="media-file-card-view confluence-ssr-app-1yn77bd" data-testid="media-file-card-view" data-test-media-name="I2.png" data-test-status="complete" data-test-progress="1">![ASP.NET Core pdf viewer](//cdn.mescius.io/umb/media/3bnh0to4/i2.png?rmode=max&width=771&height=468)</div>

</div>

</div>

</div>

</div>

No. 2 - Choose .NET Core 6.0 as the project's target framework.
    
![NET 6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m55t5dklg94l96gkz3ys.png)

No. 3 - As discussed above, we will be using **GrapeCity Documents for PDF** to create a PDF file on the server side. So, we must install the Grapecity.Documents. PDF package to work with the PDF API. To accomplish the same, right-click the project in Solution Explorer and choose **Manage NuGet Packages**. In the **Package source** on the top right, select <span aria-expanded="false" aria-haspopup="true" data-testid="hover-card-trigger-wrapper">[<span class="css-1cwva94 e1c6quvb2" data-testid="inline-card-icon-and-title"><span class="css-1lcr4h8 e1c6quvb5"><span class="css-klch0j e1c6quvb6"></span>NuGet Gallery | Home</span></span>](http://nuget.org/)</span>. Click the **Browse** tab on the top left and search for "GrapeCity.Documents", now select **GrapeCity.Documents.Pdf** from the left panel. Install it by clicking on the **Install** button in the right panel.

<div class="rich-media-item mediaSingleView-content-wrap image-align-start confluence-ssr-app-1xjjxlc" data-layout="align-start" data-width="50" data-width-type="percentage" data-node-type="mediaSingle">

<div class="confluence-ssr-app-8tst6l">

<div data-type="file" data-node-type="media" data-width="960" data-height="542" data-id="f570c8cc-6f48-4ea4-ac57-2ec86447933e" data-collection="contentId-3394142212" data-file-name="I4.png" data-file-size="164465" data-file-mime-type="image/png" data-alt="" data-context-id="3394142212">

<div id="newFileExperienceWrapper" class="new-file-experience-wrapper confluence-ssr-app-1bw04uk" data-testid="media-card-view">

<div class="media-file-card-view confluence-ssr-app-1yn77bd" data-testid="media-file-card-view" data-test-media-name="I4.png" data-test-status="complete" data-test-progress="1">![ASP.NET Core pdf viewer](//cdn.mescius.io/umb/media/ey1ndkwk/i4.png?rmode=max&width=768&height=434)</div>

</div>

</div>

</div>

</div>

Once the package gets installed, we will move on to defining the code used to generate the PDF file.

No. 4 - Open **Index.cshtml.cs** page found under the **Pages** folder in the project folder. We will be defining the server-side code in this file to generate the PDF file. Add the following code to initialize the **Environment** variable of type **IWebHostEnvironmet** to save the generated PDF file in the web root folder. This is done so as to make sure that the client-side viewer can easily access the PDF file, as explained in the next section of the blog.

```
    //Define Environment variable to access web root folder
    private IWebHostEnvironment Environment;

    public IndexModel(ILogger<IndexModel> logger, IWebHostEnvironment _environment)
    {
        _logger = logger;
        Environment = _environment;
        CreatePDF();
    }
```

No. 5 - Next, we define a method to create a PDF file. The code snippet below defines this method and creates a single-page PDF file by adding a background image and a bullet list over the image. You can find detailed information about all the API members used to accomplish the task via the code comments added to the code snippet below:

```
    public void CreatePDF()
    {
       const int FontSize = 12;

       //Define an instance of GcPdfDocument
       var doc = new GcPdfDocument();

       //Add a new page 
       var page = doc.Pages.Add();
       var g = page.Graphics;

       //Initialize TextLayout to render text
       var tl = g.CreateTextLayout();

       //Add an image to PDF document
       var img = Image.FromFile(Path.Combine("Resources", "ImagesBis", "2020-website-gcdocs-headers_tall.png"));
       var rc = page.Bounds;
       rc.Height *= 0.65f;
       g.DrawImage(img, rc, null, ImageAlign.StretchImage);

       //Define text format settings
       var ip = new PointF(48, 72);

       var font = Font.FromFile(Path.Combine("Resources", "Fonts", "OpenSans-Regular.ttf"));            
       var tfCap = new TextFormat() { Font = font, FontSize = FontSize * 1.6f, ForeColor = Color.White };
       var tf = new TextFormat() { Font = font, FontSize = FontSize, ForeColor = Color.White };
       tl.MaxWidth = 72 * 5;

       // Add Header:
       tl.AppendLine("Fast, Efficient Document APIs for .NET 5 and Java Applications", tfCap);
       tl.AppendLine(tfCap);
       tl.AppendLine("Take total control of your documents with ultra-fast, low-footprint APIs for enterprise apps.", tf);
       tl.AppendLine(tf);
       g.DrawTextLayout(tl, ip);

       // Add Bullet list:
       ip.Y += tl.ContentHeight;
       tl.Clear();
       const string bullet = "\x2022\x2003";
       tl.FirstLineIndent = -g.MeasureString(bullet, tf).Width;
       tl.ParagraphSpacing += 4;

       tl.Append(bullet, tf);
       tl.AppendLine("Generate, load, edit, save XLSX spreadsheets, PDF, Images, and DOCX files using C# .NET, VB.NET, or Java", tf);
       tl.Append(bullet, tf);
       tl.AppendLine("View, edit, print, fill and submit documents in JavaScript PDF Viewer and PDF Editor.", tf);
       tl.Append(bullet, tf);
       tl.AppendLine("Compatible on Windows, macOS, and Linux", tf);
       tl.Append(bullet, tf);
       tl.AppendLine("No dependencies on Excel, Word, or Acrobat", tf);
       tl.Append(bullet, tf);
       tl.AppendLine("Deploy to a variety of cloud-based services, including Azure, AWS, and AWS Lambda", tf);
       tl.Append(bullet, tf);
       tl.AppendLine("Product available individually or as a bundle", tf);

       //Render text
       g.DrawTextLayout(tl, ip);

       //Save the document to web root folder
       doc.Save(Path.Combine(Environment.WebRootPath, "sample.pdf"));
    }
```

The screenshot below depicts the PDF file generated by executing the above code, loaded in Adobe Acrobat Reader:

<div class="rich-media-item mediaSingleView-content-wrap image-align-start confluence-ssr-app-1xjjxlc" data-layout="align-start" data-width-type="percentage" data-node-type="mediaSingle" data-width="50">

<div class="confluence-ssr-app-13mf7z9">

<div data-type="file" data-node-type="media" data-width="692" data-height="569" data-id="b4eaee76-4480-47b9-817f-47f62cc64985" data-collection="contentId-3394142212" data-file-name="I5.png" data-file-size="91432" data-file-mime-type="image/png" data-alt="" data-context-id="3394142212">

<div id="newFileExperienceWrapper" class="new-file-experience-wrapper confluence-ssr-app-19mjd4x" data-testid="media-card-view">

<div class="media-file-card-view confluence-ssr-app-1yn77bd" data-testid="media-file-card-view" data-test-media-name="I5.png" data-test-status="complete" data-test-progress="1">![ASP.NET Core pdf viewer](//cdn.mescius.io/umb/media/2nqpe4lp/i5.png?rmode=max&width=737&height=606)</div>

</div>

</div>

</div>

</div>

## Load and View PDF in GcPdfViewer<span class="confluence-ssr-app-1afrefi" aria-label="Copy"></span>

Next, we move on to loading and viewing this PDF file generated on the server side into a Javascript-based viewer, i.e., [GrapeCity Documents PDF Viewer](https://developer.mescius.com/document-solutions/javascript-pdf-viewer "https://developer.mescius.com/document-solutions/javascript-pdf-viewer"), referred to as **GcPdfViewer**, hereafter. GcPdfViewer is a Javascript based viewer used to load, view, and edit PDF files on the client side. It offers a powerful API to support all the edit operations on the client side. Refer [here](https://developer.mescius.com/document-solutions/javascript-pdf-viewer/api/ "https://developer.mescius.com/document-solutions/javascript-pdf-viewer/api/") for more details on the API members.

The steps below will guide you on how to install and use GcPdfViewer.

No. 1 - We begin with installing GcPdfViewer in our project to start working with the respective JS files for GcPdfViewer. To accomplish the same, open Package Manager Console, choosing Tools → NuGet Package Manager → Package Manager Console. Run the following command to install GcDocs PDF Viewer. Ensure that the directory location in the command prompt is set to the lib folder in the project.

```
npm install @grapecity/gcpdfviewer
```

The GcDocs PDF Viewer will be installed in _<app_name>\<app_name>\wwwroot\lib\node_modules_ folder.

<div class="rich-media-item mediaSingleView-content-wrap image-align-start confluence-ssr-app-1xjjxlc" data-layout="align-start" data-width="50" data-width-type="percentage" data-node-type="mediaSingle">

<div class="confluence-ssr-app-4lg34m">

<div data-type="file" data-node-type="media" data-width="836" data-height="521" data-id="e03be434-d4d0-4628-adf3-b193a2a8a692" data-collection="contentId-3394142212" data-file-name="I6.png" data-file-size="97031" data-file-mime-type="image/png" data-alt="" data-context-id="3394142212">

<div id="newFileExperienceWrapper" class="new-file-experience-wrapper confluence-ssr-app-sko9ol" data-testid="media-card-view">

<div class="media-file-card-view confluence-ssr-app-1yn77bd" data-testid="media-file-card-view" data-test-media-name="I6.png" data-test-status="complete" data-test-progress="1">![ASP.NET Core pdf viewer](//cdn.mescius.io/umb/media/fk1gohmw/i6.png?rmode=max&width=745&height=464)</div>

</div>

</div>

</div>

</div>

No. 2 - In this step, we add the following code to the Index.cshtml file by replacing any existing code. The code below adds the GcPdfViewer JS file to access all the client-side APIs to initialize and work with the viewer. Next, we create an instance of GcPdfViewer by initializing the GcPdfViewer class and passing the DIV element id, which is to be used to render the viewer. Later, we add the default panels using the addDefaultPanels method and load the PDF file by invoking the open method of the GcPdfViewer class. Please note that the open method looks for the PDF file in the web root folder, i.e., why we saved the server-side generated PDF file in the wwwroot folder.

```
    <div id="root" style="height:600px;"></div>
    <script src="~/node_modules/@@grapecity/gcpdfviewer/gcpdfviewer.js"></script>
    <script>
        window.onload = function () {
            var viewer = new GcPdfViewer("#root", { /* Specify options here */ }
            );
            viewer.addDefaultPanels();
            viewer.open("sample.pdf");
        }
    </script>
```

The screenshot below depicts the PDF file loaded into Javascript-based GcPdfViewer after executing the above code snippet:

<div class="rich-media-item mediaSingleView-content-wrap image-align-start confluence-ssr-app-1xjjxlc" data-layout="align-start" data-width="50" data-width-type="percentage" data-node-type="mediaSingle">

<div class="confluence-ssr-app-wvojk3">

<div data-type="file" data-node-type="media" data-width="769" data-height="602" data-id="5818fb50-0a26-43c2-ac00-4c3eff858f66" data-collection="contentId-3394142212" data-file-name="I7.png" data-file-size="91616" data-file-mime-type="image/png" data-alt="" data-context-id="3394142212">

<div id="newFileExperienceWrapper" class="new-file-experience-wrapper confluence-ssr-app-1aiff6j" data-testid="media-card-view">

<div class="media-file-card-view confluence-ssr-app-1yn77bd" data-testid="media-file-card-view" data-test-media-name="I7.png" data-test-status="complete" data-test-progress="1">![ASP.NET Core pdf viewer](//cdn.mescius.io/umb/media/m4ddzhsh/i7.png?rmode=max&width=746&height=584)</div>

</div>

</div>

</div>

</div>

## Edit PDF on the Client Side<span class="confluence-ssr-app-1afrefi" aria-label="Copy"></span>

Now that we have loaded the PDF file into the Javascript-based GcPdfViewer let’s explore the editing possibilities offered by the viewer. GcPdfViewer, by default, only supports viewing the PDF file in the viewer. To enable the editing tools, we must configure the SupportAPI for the viewer. SupportAPI is a server-side library that, when connected to GcPdfViewer, lets you edit the PDF file on the client side using all the editing tools available in the viewer. Refer to the following documentation [topic](https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs/online/configure-pdf-editor.html "https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs/online/configure-pdf-editor.html"), which helps you understand how to configure the PDF Editor.

GcPdfViewer provides many editing tools such as annotation editor, collaboration, form editor, signature, etc. Refer to the [documentation](https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs/online/edit-pdf.html "https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs/online/edit-pdf.html") and [demos](https://developer.mescius.com/document-solutions/javascript-pdf-viewer/demos/editor-features/ "https://developer.mescius.com/document-solutions/javascript-pdf-viewer/demos/editor-features/") for exploring all the available editing tools. Here, we quickly have a look at two common ways to edit the PDF using GcPdfViewer editing tools.

### **Add Annotations using Annotation Editor:**<span class="confluence-ssr-app-1afrefi" aria-label="Copy"></span>

The use of annotations in PDF is a very popular way of editing the PDF file as it helps in many scenarios, such as reviewing a PDF file, sharing additional information through comments or sticky notes, and highlighting different parts of the text to emphasize specific content in the document. GcPdfViewer provides an annotation editor to add or remove different types of annotation to the document, such as text annotation, circle annotation, stamp annotation, redact annotation, etc. You can refer to the following [link](https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs/online/annotation-editor.html "https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs/online/annotation-editor.html") to find details about all the available annotations.

Here in the GIF below, we make use of the circle annotation to highlight an issue we observe with the document:

![ASP.NET Core pdf viewer](//cdn.mescius.io/umb/media/cy0phmhn/add-annotations-_-gif-update.gif?rmode=max&width=679&height=484)

### **Organize PDF Pages using the PDF Organizer Tool**<span class="confluence-ssr-app-1afrefi" aria-label="Copy"></span>

Another common editing requirement when working with PDF files is to add or delete pages or may be merge two PDF files, or delete specific page ranges. GcPdfViewer supports page organization using the Page tool available in the toolbar, which, when clicked, opens a secondary toolbar with different page editing features such as adding new documents/pages, deleting the current page, and a page organizer tool to organize pages like adding page ranges, merging external PDF’s or clearing page ranges. You can refer to the following [link](https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs/online/PDFOrganizer.html "https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs/online/PDFOrganizer.html") for more information about the Page tools.

The GIF below showcases the Page Tool and Page Organizer tool and uses them to duplicate and add all the PDF pages again to the PDF file:

![ASP.NET Core pdf viewer](//cdn.mescius.io/umb/media/uj4hs1dr/update2-2.gif?rmode=max&width=758&height=540)

So, with this, we conclude how you can create a PDF file on the server side and load and edit it on the client side. For more information about the product, you can refer to the [documentation](https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs/online/overview.html "https://developer.mescius.com/document-solutions/dot-net-pdf-api/docs/online/overview.html") and [demos](https://developer.mescius.com/document-solutions/javascript-pdf-viewer/demos/ "https://developer.mescius.com/document-solutions/javascript-pdf-viewer/demos/").