How to Load and Display a PDF in ASP.NET Core
| Quick Start Guide | |
|---|---|
| Tutorial Concept | Learn how to integrate a .NET PDF API library on the server side with a JavaScript PDF viewer to load, generate, and display PDF files in the browser inside an ASP.NET Core (.NET 8) application. |
| What You Will Need |
|
| Controls Referenced |
|
PDF continues to be one of the most essential and dependable document formats in modern web applications. From financial reports and legal agreements to healthcare forms and engineering drawings, the ability to dynamically generate and display PDF files has become a core requirement for enterprise-grade systems. While traditional approaches often rely on server-heavy workflows or require third-party plugins on the client, modern development patterns favor lightweight, cross-platform, browser-native solutions.
Why Use Document Solutions for PDF
Document Solutions for PDF (DsPdf), offered by MESCIUS, provides a powerful, fully managed .NET API for programmatically generating and manipulating PDF files programmatically. Its companion component, DsPdfViewer, is a modern JavaScript PDF viewer that runs directly in the browser without plugins, enabling rich PDF interactions such as navigation, zooming, annotation, form editing, and more.
In this article, we walk step-by-step through building a complete ASP.NET Core (.NET 8) application that:
- Generates a branded PDF on the server using DsPdf
- Saves it into wwwroot so that it becomes accessible to the browser
- Loads and displays it with DsPdfViewer using only JavaScript
- Optionally enables advanced client-side editing via Support API
By the end, you will have a working project that demonstrates a full PDF workflow for generation, serving, and viewing, fully powered by Document Solutions.
Now let’s walk through each of these task's step-by-step.
Download a Trial of Document Solutions for PDF & the JS PDF Viewer Today!
Steps to Load & Display a PDF in ASP.NET Core
- Creating the .NET Core Application
- Installing the DsPdf NuGet Package
- Generating or Loading a PDF in C#
- Installing DsPdfViewer (JavaScript PDF Viewer)
- Displaying the PDF in the Browser
- Editing PDF on the Client-Side
Download a Finished Sample Application to Follow Along with the Tutorial
Creating the ASP.NET Core Application
Document Solutions for PDF (DsPdf) offers a powerful .NET API for creating and editing PDF files, including support for annotations, forms, digital signatures, layers, and more. You can refer to the official documentation and demos for a full overview of its capabilities.
To get started, open Visual Studio 2022 and create a new ASP.NET Core Web Application. Select the appropriate project template such as ASP.NET Core Web App (Razor Pages) and choose a project name.

In this tutorial, we will use CreatePdf_DocSol.

Choose .NET Core 8.0 as the project's target framework.

Installing the DsPdf NuGet Package
As discussed above, we will be using Document Solutions for PDF (DsPdf) to generate a PDF file on the server side. To work with the DsPdf API in our ASP.NET Core application, we first need to install the corresponding NuGet package. This ensures that all the classes required for creating, modifying, and saving PDF documents are available within the project.
To install the package, open Visual Studio and navigate to the NuGet Package Manager. You may access it in either of the following ways:
- Right-click the project in Solution Explorer → Manage NuGet Packages, or
- Go to Tools → NuGet Package Manager → Manage NuGet Packages for Solution
In the NuGet window, ensure the Package source (top right) is set to NuGet Gallery, then click the Browse tab and search for “Ds.Documents.Pdf”. Select the package and click Install to add the Document Solutions for PDF library to your project.

Generating or Loading a PDF in C#
Once the package has been successfully installed, we can move on to writing the server-side logic responsible for generating the PDF file. This functionality will live inside the Index.cshtml.cs file, which is located under the Pages folder of the project. Since this Razor Page is executed when the application loads its home screen, it provides a convenient place to trigger PDF creation.
Before generating the PDF, we need access to the application’s web root directory, where static files such as images, fonts, and the generated PDF will be stored. To achieve this, we inject an instance of IWebHostEnvironment into the page’s constructor. This gives us the physical path to the wwwroot folder, allowing the server-side code to save the PDF in a location where the client-side viewer can easily load it later.
Add the following code inside Index.cshtml.cs to initialize the environment variable and call the PDF creation method:
private readonly ILogger<IndexModel> _logger;
private readonly IWebHostEnvironment _environment;
public IndexModel(ILogger<IndexModel> logger, IWebHostEnvironment environment)
{
_logger = logger;
_environment = environment;
// Create PDF when the page model is constructed
CreatePdf();
}
Next, we define a method to create the PDF file on the server. The code snippet below implements the CreatePdf method, which generates a single-page PDF by drawing an optional header image at the top of the page, loading a custom TrueType font from the Resources folder, and rendering a marketing-style heading and feature list beneath the image. Finally, the method saves the generated document as sample.pdf in the web root folder so it can be loaded easily by the client-side viewer in the next section.
private void CreatePdf()
{
try
{
// 1. Create DsPdf document
var doc = new GcPdfDocument();
// 2. Add page and get graphics
var page = doc.Pages.Add();
var g = page.Graphics;
// 3. Optional header image from Resources/Images
var imagePath = Path.Combine("Resources", "Images", "myheader.jpg");
var rc = page.Bounds;
float textTop;
if (System.IO.File.Exists(imagePath))
{
// Load header image
GcImage img = GcImage.FromFile(imagePath);
rc.Height *= 0.35f;
g.DrawImage(img, rc, null, ImageAlign.StretchImage);
// Set text start slightly below image
textTop = rc.Bottom + 12;
}
else
{
// Fallback text position if image is missing
textTop = 72;
}
// 4. Load custom font from Resources/Fonts (or fallback)
var fontPath = Path.Combine("Resources", "Fonts", "OpenSans-Regular.ttf");
GcFont bodyFont;
if (System.IO.File.Exists(fontPath))
{
bodyFont = GcFont.FromFile(fontPath);
}
else
{
bodyFont = StandardFonts.Helvetica;
}
var headingFormat = new TextFormat
{
Font = bodyFont,
FontSize = 20,
ForeColor = Color.Black
};
var textFormat = new TextFormat
{
Font = bodyFont,
FontSize = 12,
ForeColor = Color.Black
};
// 5. Build the text layout
var tl = g.CreateTextLayout();
tl.MaxWidth = page.Size.Width - 72 * 2; // 1-inch margins
tl.AppendLine("Document Solutions for PDF (DsPdf)", headingFormat);
tl.AppendLine("");
tl.AppendLine(
"This PDF includes a header image and a custom font loaded from Resources. " +
"It follows the same layout style as the original marketing blog sample.",
textFormat);
tl.AppendLine("");
tl.AppendLine("Features:", textFormat);
tl.AppendLine("• Load header branding images", textFormat);
tl.AppendLine("• Use custom TTF fonts", textFormat);
tl.AppendLine("• Create rich PDF layouts in ASP.NET Core", textFormat);
tl.PerformLayout(true);
// 6. Draw the text beneath the header area
g.DrawTextLayout(tl, new PointF(72, textTop));
// 7. Save the document into wwwroot/sample.pdf
Directory.CreateDirectory(_environment.WebRootPath);
var outputPath = Path.Combine(_environment.WebRootPath, "sample.pdf");
using var fs = new FileStream(outputPath, FileMode.Create, FileAccess.Write);
doc.Save(fs);
_logger.LogInformation("PDF created at {Path}", outputPath);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating PDF.");
}
}
The screenshot below depicts the PDF file generated by executing the above code:

Installing DsPdfViewer (JavaScript PDF Viewer)
Next, we move on to loading and displaying the PDF file that was generated on the server. To accomplish this, we use the Document Solutions PDF Viewer, referred to as DsPdfViewer. This is a JavaScript-based viewer that runs entirely in the browser and allows users to open, view, navigate, zoom, search, and even edit PDF files. The viewer exposes a powerful API that supports annotations, form filling, signatures, and many other client-side editing capabilities.
Installing DsPdfViewer via NPM
To use DsPdfViewer inside an ASP.NET Core application, we must first install the viewer’s JavaScript library. The viewer is distributed as an NPM package, so we install it directly into the project’s wwwroot/lib folder. This ensures that all required JavaScript and CSS files are available to the Razor Pages.
To install the viewer, open Package Manager Console in Visual Studio (Tools → NuGet Package Manager → Package Manager Console) and run the following command:
npm install @mescius/dspdfviewer
After installation, the viewer library will appear inside your project under:
<project-name>\wwwroot\lib\node_modules\@mescius\dspdfviewer
From here, we copy the entire dspdfviewer folder into:
wwwroot/lib/dspdfviewer

Displaying the PDF with DsPdfViewer
In this step, we add the client-side viewer to the Index.cshtml file so that the PDF generated on the server can be loaded and displayed directly in the browser. The viewer requires its JavaScript and worker files to be included on the page, which enables all client-side operations such as rendering, zooming, searching, and panel interactions.
To begin, we replace the default Razor markup with the code necessary to initialize the DsPdfViewer class. The viewer is rendered inside a <div> element using its CSS selector (#root). Once initialized, we add the default UI panels such as the thumbnails panel, search panel, outlines panel and more using the addDefaultPanels() method. Finally, we call viewer.open("sample.pdf") to load the PDF file that was previously created and saved to the wwwroot folder during the server-side generation step.
@page
@model CreatePdf_DocSol.Pages.IndexModel
@{
ViewData["Title"] = "Home page";
}
<h2>PDF Viewer</h2>
<div id="root" style="height:600px; width:100%;"></div>
@section Scripts {
<script>
var viewer = new DsPdfViewer("#root", {
workerSrc: "/lib/dspdfviewer/dspdfviewer.worker.js"
});
viewer.addDefaultPanels();
viewer.open("sample.pdf");
</script>
The screenshot below depicts the PDF file loaded into JavaScript-based DsPdfViewer after executing the above code snippet:

Editing PDF on the Client Side (Optional)
Now that the PDF document is successfully loaded into the JavaScript-based DsPdfViewer, we can explore the editing capabilities provided by the viewer. By default, DsPdfViewer allows users to view PDF files in a rich, interactive interface. To unlock full client-side editing features such as annotations, form editing, signatures, redaction, and more the viewer must be paired with an additional component called SupportAPI.
SupportAPI is a server-side processing library that communicates with the viewer in the browser. When connected, it enables real-time editing operations, letting users modify PDFs directly on the client side while the server handles saving, updating, and validating the changes. You can refer to the Document Solutions documentation for instructions on how to configure SupportAPI in an ASP.NET Core application.
Using the Annotation Editor
Annotations are one of the most common ways to enhance or review PDF documents. Whether you are highlighting key text passages, marking corrections, adding comments, or visually emphasizing areas of interest, annotations play a crucial role in document collaboration. DsPdfViewer includes a built-in annotation editor that enables users to insert, edit, and remove a wide variety of annotation types directly in the browser.
You can refer here 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:

Organizing PDF Pages with the Page Management Tools
Besides annotation, another common requirement when editing PDFs is restructuring the document itself. Users may need to insert new pages, delete unwanted pages, reorder page sequences, or merge multiple PDFs into a single file. DsPdfViewer includes a dedicated Page Organizer interface that enables these operations directly within the browser when SupportAPI is enabled.
You can refer here 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:

Download a Trial of Document Solutions for PDF & the JavaScript PDF Viewer Today!
Conclusion
By combining Document Solutions for PDF (DsPdf) with the JavaScript-based DsPdfViewer, developers can implement a complete end-to-end PDF workflow inside any ASP.NET Core application. From generating branded PDF documents on the server to viewing and optionally editing them in the browser, this approach eliminates the need for plugins and enables a fully cross-platform experience.
For more examples and advanced scenarios, refer to the Document Solutions documentation and online demos.