Skip to footer content
USING IRONPDF

How to Display a PDF File in ASP.NET Core

PDF files are widely used for document sharing and data display purposes. In web applications, it is often required to display PDF files to users directly within the browser. ASP.NET Core applications provide various options to achieve this functionality, and one popular library for working with PDF files is IronPDF.

IronPDF is a powerful .NET library that allows developers to create, edit, and manipulate PDFs with ease. This article is going to explore how to use IronPDF to display PDF files in an ASP.NET Core PDF viewer application. It will cover the steps to set up the necessary components and provide sample logic to demonstrate the ASP.NET Core PDF viewer integration.

Setting up the Environment

To get started, make sure you have the following prerequisites:

  1. Visual Studio: Install the latest version of Visual Studio or any other compatible Integrated Development Environment (IDE) of your choice.
  2. IronPDF Library: Obtain the IronPDF library from the Official IronPDF Website or via NuGet Package Manager.

    How to Display a PDF File in ASP.NET Core, Figure 1: NuGet Package Manager NuGet Package Manager

  3. .NET Core Application: Make sure you have a basic understanding of ASP.NET Core Setup Instructions and have it installed on your development machine.

Once you have set up the environment, let's dive into the steps to display PDF files using IronPDF in an ASP.NET Core application.

Creating a New Project

  1. Open Visual Studio and create a new ASP.NET Core Web App project.

    How to Display a PDF File in ASP.NET Core, Figure 2: Web Application Web Application

  2. Select the "ASP.NET Core Web App" template.

    How to Display a PDF File in ASP.NET Core, Figure 3: .NET Framework .NET Framework

  3. Choose the desired project settings and click "Create" to generate the new project.

Adding IronPDF Library

To use IronPDF in your project, you need to add the IronPDF library reference.

  1. Right-click on the project in the Solution Explorer and select "Manage NuGet Packages for Solution..."

    How to Display a PDF File in ASP.NET Core, Figure 4: NuGet Package Manager NuGet Package Manager

  2. Search for "IronPDF" in the NuGet Package Manager and install the latest version of the package.

    How to Display a PDF File in ASP.NET Core, Figure 5: NuGet Package Manager - Solution Explorer NuGet Package Manager - Solution Explorer

Create PDF using an ASP.NET Core Web Page

To create a PDF from an ASP.NET Core Web Page from the server side, follow these steps:

How to Display a PDF File in ASP.NET Core, Figure 6: NuGet Package Manager - Solution Explorer Solution Explorer

Step 1 Add the IronPDF Namespace

Open the source file path of the ASP.NET Core web page that you want to convert into a PDF. In the code-behind file (Index.cshtml.cs), add the IronPdf namespace at the top:

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

Step 2 Convert Razor Page to PDF

Inside the OnGet function, add the following code:

public FileContentResult OnGet()
{
    // Create a new instance of ChromePdfRenderer
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the current Razor page to a PDF document
    PdfDocument pdf = renderer.RenderRazorToPdf(this);

    // Add HTTP header to display PDF in the browser
    Response.Headers.Add("Content-Disposition", "inline");

    // Return the PDF file to the client
    return File(pdf.BinaryData, "application/pdf");
}
public FileContentResult OnGet()
{
    // Create a new instance of ChromePdfRenderer
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the current Razor page to a PDF document
    PdfDocument pdf = renderer.RenderRazorToPdf(this);

    // Add HTTP header to display PDF in the browser
    Response.Headers.Add("Content-Disposition", "inline");

    // Return the PDF file to the client
    return File(pdf.BinaryData, "application/pdf");
}
Public Function OnGet() As FileContentResult
	' Create a new instance of ChromePdfRenderer
	Dim renderer As New ChromePdfRenderer()

	' Render the current Razor page to a PDF document
	Dim pdf As PdfDocument = renderer.RenderRazorToPdf(Me)

	' Add HTTP header to display PDF in the browser
	Response.Headers.Add("Content-Disposition", "inline")

	' Return the PDF file to the client
	Return File(pdf.BinaryData, "application/pdf")
End Function
$vbLabelText   $csharpLabel

With just one line of code, the Razor Page will be converted into a PDF document using the RenderRazorToPdf method.

To achieve this, the IronPdf.Extensions.Razor NuGet Package needs to be installed.

Step 3 Display or Download PDF

By default, the code will display the PDF document in the browser. If you want to download the PDF instead, modify the code as follows:

return File(pdf.BinaryData, "application/pdf", "razorPageToPDF.pdf");
return File(pdf.BinaryData, "application/pdf", "razorPageToPDF.pdf");
Return File(pdf.BinaryData, "application/pdf", "razorPageToPDF.pdf")
$vbLabelText   $csharpLabel

This code will download the PDF file of the ASP.NET Web Page into your local "Downloads" folder.

How to Display a PDF File in ASP.NET Core, Figure 7: ASPX Page to PDF Razor Page to PDF

Load and Display a PDF file in ASP.NET Core

Next, this section will explore different approaches to generate PDF files using IronPDF and display them in an ASP.NET Core application.

Generate PDF from URL

IronPDF simplifies the process of creating a PDF document by generating an HTML file from a URL (HTTP services) and converting it to a PDF. The following code demonstrates how to generate a PDF file from a URL:

// Render a PDF from a URL
using var pdf = new IronPdf.ChromePdfRenderer().RenderUrlAsPdf("https://www.google.co.in/");

// Read the File as Byte Array
byte[] bytes = pdf.BinaryData;

// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
// Render a PDF from a URL
using var pdf = new IronPdf.ChromePdfRenderer().RenderUrlAsPdf("https://www.google.co.in/");

// Read the File as Byte Array
byte[] bytes = pdf.BinaryData;

// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
' Render a PDF from a URL
Dim pdf = (New IronPdf.ChromePdfRenderer()).RenderUrlAsPdf("https://www.google.co.in/")

' Read the File as Byte Array
Dim bytes() As Byte = pdf.BinaryData

' Convert File to Base64 string and send to Client
Dim base64 As String = Convert.ToBase64String(bytes, 0, bytes.Length)
Return Content(base64)
$vbLabelText   $csharpLabel

In the above code, IronPDF's ChromePdfRenderer class is used to render the HTML content from the specified URL and convert it into a PDF document. The PDF document is then converted to a byte array and sent to the client as a base64 string.

Generate PDF from HTML String

IronPDF offers an efficient approach to transforming HTML strings into PDF documents. The code snippet below demonstrates how to generate a PDF file from a string:

// Render a PDF from an HTML string
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>");
// Render a PDF from an HTML string
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>");
' Render a PDF from an HTML string
Dim pdf = (New IronPdf.ChromePdfRenderer()).RenderHtmlAsPdf("<h1>Hello world!!</h1>")
$vbLabelText   $csharpLabel

In the above example, the RenderHtmlAsPdf method is used to render the HTML string and convert it into a PDF document. The resulting PDF can be further processed or saved as per the application's requirements.

How to Display a PDF File in ASP.NET Core, Figure 8: Web Application Output Web Application Output

Generate PDF from HTML Files

IronPDF also supports transforming HTML files or CSS files into PDF document examples. The following code showcases how to generate a PDF file from an HTML file:

// Render a PDF from an HTML file
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlFileAsPdf("demo.html");

// Read the file as Byte Array
byte[] bytes = pdf.BinaryData;

// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
// Render a PDF from an HTML file
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlFileAsPdf("demo.html");

// Read the file as Byte Array
byte[] bytes = pdf.BinaryData;

// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
' Render a PDF from an HTML file
Dim pdf = (New IronPdf.ChromePdfRenderer()).RenderHtmlFileAsPdf("demo.html")

' Read the file as Byte Array
Dim bytes() As Byte = pdf.BinaryData

' Convert File to Base64 string and send to Client
Dim base64 As String = Convert.ToBase64String(bytes, 0, bytes.Length)
Return Content(base64)
$vbLabelText   $csharpLabel

In the code snippet above, the RenderHtmlFileAsPdf method is used to render the HTML content from the specified filename and convert it into a PDF document. The resulting PDF is converted to a byte array and sent to the client as a base64 string.

How to Display a PDF File in ASP.NET Core: Figure 9 - Add a New Web Page

Converting ASP.NET Web Forms to a PDF File with IronPDF from the ASP.NET Web API

You can easily convert ASP.NET web forms to PDF format using just a single line of code instead of HTML. Place this code in the Page_Load method of the page's code-behind file to display it on the page.

Import the IronPdf Namespace

Use the using keyword to import the IronPdf namespace in your code-behind file.

using IronPdf;
using System;
using System.Web.UI;
using IronPdf;
using System;
using System.Web.UI;
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Convert ASP.NET Web Form to PDF

In the code-behind file of the page you want to convert to PDF (e.g., Default.aspx.cs), add the following code:

namespace WebApplication7
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Convert the ASPX page to a PDF displayed in the browser
            AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
        }
    }
}
namespace WebApplication7
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Convert the ASPX page to a PDF displayed in the browser
            AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
        }
    }
}
Namespace WebApplication7
	Partial Public Class _Default
		Inherits Page

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
			' Convert the ASPX page to a PDF displayed in the browser
			AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

The RenderThisPageAsPdf method of the AspxToPdf class will convert the web form into a PDF document from the web API.

Apply HTML Templates

For intranet and website developers, generating PDFs with templates is often a common requirement. IronPDF simplifies this process by allowing you to generate an HTML template and populate it with data.

Here's an example of how to generate multiple customized PDFs using HTML templates and IronPDF:

// Define an HTML template with placeholders
string HtmlTemplate = "<p>[[NAME]]</p>";
string[] Names = { "John", "James", "Jenny" };
foreach (var name in Names)
{
    // Replace placeholder in template with actual data
    string HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);

    // Render HTML to PDF
    using (var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance))
    {
        // Save the PDF with the name as filename
        Pdf.SaveAs(name + ".pdf");
    }
}
// Define an HTML template with placeholders
string HtmlTemplate = "<p>[[NAME]]</p>";
string[] Names = { "John", "James", "Jenny" };
foreach (var name in Names)
{
    // Replace placeholder in template with actual data
    string HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);

    // Render HTML to PDF
    using (var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance))
    {
        // Save the PDF with the name as filename
        Pdf.SaveAs(name + ".pdf");
    }
}
' Define an HTML template with placeholders
Dim HtmlTemplate As String = "<p>[[NAME]]</p>"
Dim Names() As String = { "John", "James", "Jenny" }
For Each name In Names
	' Replace placeholder in template with actual data
	Dim HtmlInstance As String = HtmlTemplate.Replace("[[NAME]]", name)

	' Render HTML to PDF
	Using Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance)
		' Save the PDF with the name as filename
		Pdf.SaveAs(name & ".pdf")
	End Using
Next name
$vbLabelText   $csharpLabel

ASP MVC Routing Download the PDF Version Of This Page

If you're using ASP.NET MVC, you can easily direct users to a PDF file. Here's an example of how the source code should be written:

using IronPdf;
using System;
using System.Web.Mvc;

namespace WebApplication8.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            // Create a new instance of ChromePdfRenderer
            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Render the URL as a PDF
            using (var PDF = renderer.RenderUrlAsPdf(new Uri("https://en.wikipedia.org")))
            {
                // Return the PDF file with a specified filename
                return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf");
            }
        }
        // Other action methods...
    }
}
using IronPdf;
using System;
using System.Web.Mvc;

namespace WebApplication8.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            // Create a new instance of ChromePdfRenderer
            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Render the URL as a PDF
            using (var PDF = renderer.RenderUrlAsPdf(new Uri("https://en.wikipedia.org")))
            {
                // Return the PDF file with a specified filename
                return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf");
            }
        }
        // Other action methods...
    }
}
Imports IronPdf
Imports System
Imports System.Web.Mvc

Namespace WebApplication8.Controllers
	Public Class HomeController
		Inherits Controller

		Public Function Index() As IActionResult
			' Create a new instance of ChromePdfRenderer
			Dim renderer As New ChromePdfRenderer()

			' Render the URL as a PDF
			Using PDF = renderer.RenderUrlAsPdf(New Uri("https://en.wikipedia.org"))
				' Return the PDF file with a specified filename
				Return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf")
			End Using
		End Function
		' Other action methods...
	End Class
End Namespace
$vbLabelText   $csharpLabel

Add a Cover Page to a PDF Document

To add a cover page or back page to an existing PDF document, you can use IronPDF's merge functionality. Here's an example:

using (var PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/"))
{
    // Merge the cover page with the main PDF
    using (var Merged = PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF))
    {
        // Save the combined PDF
        Merged.SaveAs("Combined.Pdf");
    }
}
using (var PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/"))
{
    // Merge the cover page with the main PDF
    using (var Merged = PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF))
    {
        // Save the combined PDF
        Merged.SaveAs("Combined.Pdf");
    }
}
Using PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/")
	' Merge the cover page with the main PDF
	Using Merged = PdfDocument.Merge(New PdfDocument("CoverPage.pdf"), PDF)
		' Save the combined PDF
		Merged.SaveAs("Combined.Pdf")
	End Using
End Using
$vbLabelText   $csharpLabel

Add a Watermark to Your Document

You can also add a watermark to PDF documents using C# code. Here's an example:

using IronPdf;

// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render the URL as a PDF
using (var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf"))
{
    // Add watermark text to all pages
    pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45);

    // Save the watermarked PDF
    pdf.SaveAs(@"C:\PathToWatermarked.pdf");
}
using IronPdf;

// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render the URL as a PDF
using (var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf"))
{
    // Add watermark text to all pages
    pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45);

    // Save the watermarked PDF
    pdf.SaveAs(@"C:\PathToWatermarked.pdf");
}
Imports IronPdf

' Create a new instance of ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

' Render the URL as a PDF
Using pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
	' Add watermark text to all pages
	pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45)

	' Save the watermarked PDF
	pdf.SaveAs("C:\PathToWatermarked.pdf")
End Using
$vbLabelText   $csharpLabel

Protect Your PDF with a Password

You can encrypt and protect a PDF document with a password using IronPDF. Here's an example:

using IronPdf;

// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render HTML to PDF
using (var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World<h1>"))
{
    // Set a password to protect the PDF
    pdfDocument.Password = "strong!@#pass&^%word";

    // Save the secured PDF
    pdfDocument.SaveAs("secured.pdf");
}
using IronPdf;

// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render HTML to PDF
using (var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World<h1>"))
{
    // Set a password to protect the PDF
    pdfDocument.Password = "strong!@#pass&^%word";

    // Save the secured PDF
    pdfDocument.SaveAs("secured.pdf");
}
Imports IronPdf

' Create a new instance of ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

' Render HTML to PDF
Using pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World<h1>")
	' Set a password to protect the PDF
	pdfDocument.Password = "strong!@#pass&^%word"

	' Save the secured PDF
	pdfDocument.SaveAs("secured.pdf")
End Using
$vbLabelText   $csharpLabel

In addition to the above functionalities, IronPDF offers other features such as extracting images and text with OCR from PDFs, rendering charts to PDF, adding barcodes to PDFs, enhancing document security with passwords and watermarking techniques for PDFs, even handling and customizing PDF forms, and more. By using IronPDF, you can simplify the process of creating PDFs and improve the overall presentation of your documents.

Conclusion

IronPDF is an exceptional tool designed specifically for .NET developers, offering a wide range of functionalities to effortlessly handle PDF manipulation within their .NET projects. With IronPDF, developers can enhance their workflow and streamline their work processes. This powerful tool provides numerous features that enable seamless PDF file formatting, page deletion, page addition, and much more. It empowers developers to efficiently manage and customize PDF documents according to their specific requirements.

IronPDF not only excels in functionality but also offers the added benefit of being free for development purposes. This means that developers can leverage its capabilities without incurring any costs during the development phase of their projects. By utilizing IronPDF, developers can enhance their productivity and achieve remarkable results in their PDF-related tasks, ultimately delivering high-quality and efficient solutions within their .NET projects.

There are many other useful libraries such as IronPDF for working with PDF documents, IronXL for working with Excel documents, and IronOCR for working with OCR. Currently, you can get all five libraries for the price of just two by purchasing the complete Iron Suite. Visit our Iron Software Licensing Information for more details.

Frequently Asked Questions

What is a powerful .NET library for working with PDFs?

IronPDF is a powerful .NET library that allows developers to create, edit, and manipulate PDFs with ease. It is commonly used in ASP.NET Core applications to display PDF files in a web app.

How can I set up the environment to work with PDFs in an ASP.NET Core application?

To set up the environment, you need to install the latest version of Visual Studio or another compatible IDE, obtain the IronPDF library via the Official IronPDF Website or NuGet Package Manager, and ensure you have a basic understanding of ASP.NET Core setup instructions.

How do I create a new ASP.NET Core project to display PDFs?

Open Visual Studio, create a new ASP.NET Core Web App project, select the 'ASP.NET Core Web App' template, choose your desired project settings, and click 'Create' to generate the project.

How do I add a PDF library to my ASP.NET Core project?

Right-click on the project in the Solution Explorer, select 'Manage NuGet Packages for Solution...', search for 'IronPDF', and install the latest version of the package.

How can I convert a Razor Page to a PDF in ASP.NET Core?

In the code-behind file (e.g., 'Index.cshtml.cs'), add the IronPdf namespace. Inside the 'OnGet' function, create a ChromePdfRenderer instance, render the Razor page to a PDF document, and return the PDF file to the client.

How can I generate a PDF from a URL?

Use the ChromePdfRenderer class to render the HTML content from the specified URL and convert it into a PDF document. Convert the PDF to a byte array and send it to the client as a base64 string.

Can I add a watermark to a PDF document?

Yes, you can add a watermark to PDF documents using the ChromePdfRenderer class to render the URL as a PDF and then use the 'WatermarkAllPages' method to add watermark text to all pages.

How do I protect a PDF with a password?

Use the ChromePdfRenderer class to render HTML to PDF and set a password on the PdfDocument object before saving it to secure the PDF.

Is there a free option for development purposes for working with PDFs?

Yes, IronPDF is free for development purposes, allowing developers to leverage its capabilities without any costs during the development phase of their projects.

What are some other useful libraries for document processing?

Other useful libraries by Iron Software include IronXL for Excel documents and IronOCR for OCR. You can get all five libraries for the price of two with the complete Iron Suite.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.
Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?

Nuget Passed