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 file to users directly within the browser. ASP.NET Core application provides 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. In this article, we are going to explore how to use IronPDF to display PDF files in an ASP.NET Core PDF viewer control application. We 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 website or via NuGet package manager.

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

  3. .NET Core Application: Make sure you have a basic understanding of ASP.NET Core 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 MVC project.

    How to Display a PDF File in ASP.NET Core: Figure 2 - 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

  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."

    How to Display a PDF File in ASP.NET Core: Figure 4 - 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

Create PDF using an ASP.NET Core Web Page

To create a PDF from an ASP.NET Core web page, using the web API, follow these steps:

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

Step 1 Add the IronPDF Namespace

Open the source file path of the ASPX web page that you want to convert into a PDF. In the code-behind file (Default.aspx.cs), add the IronPDF namespace at the top:

using IronPdf;
using IronPdf;
Imports IronPdf
VB   C#

Step 2 Convert ASPX Page to PDF

Inside the Page_Load function, add the following code:

AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser)
VB   C#

With just one line of code, the ASPX page will be converted into a PDF document using the RenderThisPageAsPdf method from the AspxToPdf class.

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:

AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.Attachment);
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.Attachment);
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

This code will download the PDF file of the ASPX web page into the .NET Core project directory.

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

Load and Display a PDF file in ASP.NET Core

Displaying PDF files in an ASP.NET Core application is a common requirement. IronPDF is a powerful library that provides various methods to generate and display PDF documents. In this article, we will explore different approaches to generate PDF files using IronPDF and display them in an ASP.NET Core application. We will utilize keywords related to ASP.NET Core, PDF files, IronPDF, and display functionalities to cover the topic comprehensively.

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:

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); //public string
return Content(base64);
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); //public string
return Content(base64);
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

In the above code, IronPDF's ChromePdfRenderer 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 allows us to transform HTML strings into PDF documents. The code snippet below demonstrates how to generate a PDF file from a string:

using var PDF = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>");
using var PDF = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>");
Dim PDF = (New IronPdf.ChromePdfRenderer()).RenderHtmlAsPdf("<h1>Hello world!!</h1>")
VB   C#

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

Generate PDF from HTML Files

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

using var PDF = new IronPdf.ChromePdfRenderer().RenderHtmlFileAsPdf("demo.html"); //using the string filename
byte[] bytes = PDF.BinaryData; //var file
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
using var PDF = new IronPdf.ChromePdfRenderer().RenderHtmlFileAsPdf("demo.html"); //using the string filename
byte[] bytes = PDF.BinaryData; //var file
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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
VB   C#

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 //public string
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser); //input element
        }
    }
}
namespace WebApplication7
{
    public partial class _Default : Page //public string
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser); //input element
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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:

string HtmlTemplate = "<p>[[NAME]]</p>";
string[] Names = { "John", "James", "Jenny" };
foreach (var name in Names)
{
    string HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);
    using (var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance))
    {
        Pdf.SaveAs(name + ".pdf");
    }
}
string HtmlTemplate = "<p>[[NAME]]</p>";
string[] Names = { "John", "James", "Jenny" };
foreach (var name in Names)
{
    string HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);
    using (var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance))
    {
        Pdf.SaveAs(name + ".pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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()
        {
            using (var PDF = HtmlToPdf.StaticRenderUrlAsPdf(new Uri("https://en.wikipedia.org")))
            {
                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()
        {
            using (var PDF = HtmlToPdf.StaticRenderUrlAsPdf(new Uri("https://en.wikipedia.org")))
            {
                return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf");
            }
        }
        // Other action methods...
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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/"))
{
    using (var Merged = PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF))
    {
        Merged.SaveAs("Combined.Pdf");
    }
}
using (var PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/"))
{
    using (var Merged = PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF))
    {
        Merged.SaveAs("Combined.Pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Add a Watermark to Your Document

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

using IronPdf;
HtmlToPdf Renderer = new HtmlToPdf();
using (var pdf = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf"))
{
    pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf");
    pdf.SaveAs(@"C:\PathToWatermarked.pdf"); //string filepath
}
using IronPdf;
HtmlToPdf Renderer = new HtmlToPdf();
using (var pdf = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf"))
{
    pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf");
    pdf.SaveAs(@"C:\PathToWatermarked.pdf"); //string filepath
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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;
var htmlToPdf = new HtmlToPdf();
using (var pdfDocument = htmlToPdf.RenderHtmlAsPdf("<h1>Hello World<h1>"))
{
    pdfDocument.Password = "strong!@#pass&^%word";
    pdfDocument.SaveAs("secured.pdf");
}
using IronPdf;
var htmlToPdf = new HtmlToPdf();
using (var pdfDocument = htmlToPdf.RenderHtmlAsPdf("<h1>Hello World<h1>"))
{
    pdfDocument.Password = "strong!@#pass&^%word";
    pdfDocument.SaveAs("secured.pdf");
}
Imports IronPdf
Private htmlToPdf = New HtmlToPdf()
Using pdfDocument = htmlToPdf.RenderHtmlAsPdf("<h1>Hello World<h1>")
	pdfDocument.Password = "strong!@#pass&^%word"
	pdfDocument.SaveAs("secured.pdf")
End Using
VB   C#

In addition to the above functionalities, IronPDF offers other features such as extracting images and text from PDFs using OCR, editing HTML content, enhancing images, 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.