USING IRONPDF

How to view PDF files in ASP.NET using C# and IronPDF

Updated November 4, 2021
Share:

Most people open PDFs on a computer using a dedicated desktop application, but software engineers can also use IronPDF to create, view, open, read and edit PDF content with C# programmatically.

IronPDF turned out to be a very useful plugin when reading PDF files in ASP.NET and C#.

You can download the project file from this link.

It is possible to create PDF documents quickly and easily using C# with IronPDF.

Much of the design and layout of PDF documents can be accomplished by using existing HTML assets or by delegating the task to web design employees; it takes care of the time-consuming task of integrating PDF generation into your application, and it automates converting prepared documents into PDFs. With .NET, you can:

  • Convert web forms, local HTML pages, and other websites to PDF format.
  • Allow users to download documents, share them with others via email, or save them in the cloud.
  • Invoice customers and provide quotations; prepare reports; negotiate contracts and other paperwork.
  • Work with ASP.NET, ASP.NET Core, Web Forms, MVC, Web APIs on .NET Framework and .NET Core, and other programming languages.

Setting up IronPDF Library

There are two ways to install the library;

Installing with the NuGet Package Manager

IronPDF can be installed via the Visual Studio Add-in or the NuGet Package Manager from the command line. Navigate to the Console, type in the following code in Visual Studio:

Install-Package IronPdf

Download the DLL File Directly From the Website

Alternatively, you can get the DLL straight from the website.

Remember to include the following remark at the top of any cs class file that makes use of IronPDF:

Check out IronPDF Features.

IronPDF is a must-have plugin. Get yours now and try it with NuGet.

Create a PDF File From an HTML String in .NET C#

Creating a PDF file from an HTML string in C# is an efficient and rewarding method of creating a new PDF file in C#.

The RenderHtmlAsPdf function from a ChromePdfRenderer provides an easy way to convert any HTML (HTML5) string into a PDF document, thanks to the embedded version of the Google Chromium engine in the IronPDF DLL.

//Render HTML to pdf
var renderer = new ChromePdfRenderer();
using var rendered_pdf = renderer.RenderHtmAsPdf("<h1>My First HTML to Pdf</h1>");

var Output_Path = "My_First_Html.pdf";
PDF.SaveAs(Output_Path);
System.Diagnostics.Process.Start(Output_Path);
//Render HTML to pdf
var renderer = new ChromePdfRenderer();
using var rendered_pdf = renderer.RenderHtmAsPdf("<h1>My First HTML to Pdf</h1>");

var Output_Path = "My_First_Html.pdf";
PDF.SaveAs(Output_Path);
System.Diagnostics.Process.Start(Output_Path);
'Render HTML to pdf
Dim renderer = New ChromePdfRenderer()
Dim rendered_pdf = renderer.RenderHtmAsPdf("<h1>My First HTML to Pdf</h1>")

Dim Output_Path = "My_First_Html.pdf"
PDF.SaveAs(Output_Path)
System.Diagnostics.Process.Start(Output_Path)
VB   C#

RenderHtmlAsPdf is a powerful tool that supports CSS, JavaScript, and images in total. It may be necessary to set the second argument of RenderHtmlAsPdf if these materials are stored on a hard disc.

The following code will generate a PDF file:

var Render_pdf = renderer.RenderHtmlAsPdf("<img src='image_1.png'/>", @"C:\Newproject");
var Render_pdf = renderer.RenderHtmlAsPdf("<img src='image_1.png'/>", @"C:\Newproject");
Dim Render_pdf = renderer.RenderHtmlAsPdf("<img src='image_1.png'/>", "C:\Newproject")
VB   C#

All CSS stylesheets, pictures, and JavaScript files referenced will be relative to the BaseUrlPath, allowing for a more organized and logical structure to be maintained. You can, of course, make use of pictures, stylesheets, and assets available on the internet, such as Web Fonts, Google Fonts, and even jQuery, if you choose.

Create a PDF document. Making Use of an Existing HTML URL

Existing URLs can be rendered into PDFs with C# in a very efficient and straightforward manner; this also enables teams to divide PDF design and back-end PDF rendering work across various sections, which is beneficial.

The code below demonstrates how to render the endeavorcreative.com page from its URL:

//Render url to pdf
var renderer = new ChromePdfRenderer();
using var Rendered_pdf = renderer.RenderUrlAsPdf("https://endeavorcreative.com/setting-up-wordpress-website-from-scratch/");

var Output_Path = "Url_pdf.pdf";
Rendered_pdf.SaveAs(Output_Path);
System.Diagnostics.Process.Start(Output_Path);
//Render url to pdf
var renderer = new ChromePdfRenderer();
using var Rendered_pdf = renderer.RenderUrlAsPdf("https://endeavorcreative.com/setting-up-wordpress-website-from-scratch/");

var Output_Path = "Url_pdf.pdf";
Rendered_pdf.SaveAs(Output_Path);
System.Diagnostics.Process.Start(Output_Path);
'Render url to pdf
Dim renderer = New ChromePdfRenderer()
Dim Rendered_pdf = renderer.RenderUrlAsPdf("https://endeavorcreative.com/setting-up-wordpress-website-from-scratch/")

Dim Output_Path = "Url_pdf.pdf"
Rendered_pdf.SaveAs(Output_Path)
System.Diagnostics.Process.Start(Output_Path)
VB   C#

As a result, all the hyperlinks (HTML links) and even HTML forms are retained in the generated PDF.

Create a PDF Document From an Existing HTML Document

This section shows how to render any local HTML file. It will appear that the file has been opened using the file:/ protocol for all relative assets such as CSS, pictures, and JavaScript, among others.

//Render existing html to pdf
var renderer = new ChromePdfRenderer();
using var Rendered_pdf = renderer.RenderHtmlFileAsPdf("Assets/test1.html");

var Output_Path = "test1_pdf.pdf";
Rendered_pdf.SaveAs(Output_Path);
System.Diagnostics.Process.Start(Output_Path);
//Render existing html to pdf
var renderer = new ChromePdfRenderer();
using var Rendered_pdf = renderer.RenderHtmlFileAsPdf("Assets/test1.html");

var Output_Path = "test1_pdf.pdf";
Rendered_pdf.SaveAs(Output_Path);
System.Diagnostics.Process.Start(Output_Path);
'Render existing html to pdf
Dim renderer = New ChromePdfRenderer()
Dim Rendered_pdf = renderer.RenderHtmlFileAsPdf("Assets/test1.html")

Dim Output_Path = "test1_pdf.pdf"
Rendered_pdf.SaveAs(Output_Path)
System.Diagnostics.Process.Start(Output_Path)
VB   C#

The advantage of this strategy is that it allows developers to test HTML content in a browser while creating it. IronPDF's rendering engine is built on the Chrome web browser. Therefore, it is recommended to convert XML to PDF; printing XML content to PDF can be done using XSLT templates.

Converting ASP.NET Web Forms to a PDF File

With a single line of code, you can convert ASP.NET online forms to PDF format instead of HTML. Place the line of code in the Page_Load method of the page's code-behind file to make it appear on the page.

ASP.NET Web Forms Applications can either be created from scratch or opened from a previous version.

Install the NuGet package if it is not already installed.

The using keyword should be used to import the IronPdf namespace.

Make your way to the code behind the page that you'd like to convert to PDF. For instance, the file Default.aspx.cs using ASP.NET

RenderThisPageAsPdf is a method on the AspxToPdf class.

using IronPdf;
using System;
using System.Web.UI;

namespace WebApplication7
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {            
            AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
        }
    }
}
using IronPdf;
using System;
using System.Web.UI;

namespace WebApplication7
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {            
            AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
        }
    }
}
Imports IronPdf
Imports System
Imports System.Web.UI

Namespace WebApplication7
	Partial Public Class _Default
		Inherits Page

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
			AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser)
		End Sub
	End Class
End Namespace
VB   C#

This requires IronPdf.Extensions.ASPX from NuGet official page to be installed. It is not available in .NET Core because ASPX is superseded by the MVC model.

Apply HTML Templating

For Intranet and website developers, the ability to template or "batch produce" PDFs is a standard necessity.

Rather than creating a template for a PDF document, the IronPDF Library offers a way to generate a template for HTML by leveraging existing, well-tested technology.

A dynamically generated PDF file is created when the HTML template is supplemented with data from a query string or a database, as shown below.

As an example, consider the C# String class and its properties. The format method works well for basic "mail-merge" operations.

String.Format("<h1>Hello {}!<h1/>","World");
String.Format("<h1>Hello {}!<h1/>","World");
String.Format("<h1>Hello {}!<h1/>","World")
VB   C#

Because HTML files can be pretty extensive, it is common to utilize arbitrary placeholders such as [[NAME]] and then replace them with accurate data.

The following example will generate three PDF documents, each of which will be customized for a different user.

var HtmlTemplate = "<p>[[NAME]]</p>";
var Names = new [] { "John", "James", "Jenny" };
foreach (var name in Names) {
var HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);

var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(HtmlInstance);
pdf.SaveAs(name + ".pdf");
}
var HtmlTemplate = "<p>[[NAME]]</p>";
var Names = new [] { "John", "James", "Jenny" };
foreach (var name in Names) {
var HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);

var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(HtmlInstance);
pdf.SaveAs(name + ".pdf");
}
Dim HtmlTemplate = "<p>[[NAME]]</p>"
Dim Names = { "John", "James", "Jenny" }
For Each name In Names
Dim HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name)

Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(HtmlInstance)
pdf.SaveAs(name & ".pdf")
Next name
VB   C#

ASP.NET MVC Routing Download the PDF Version Of This Page

With the ASP.NET MVC Framework, you may direct the user to a PDF file.

When building a new ASP.NET MVC Application or adding an existing MVC Controller to an existing application, select this option. Start the Visual Studio new project wizard by selecting ASP.NET Web Application (.NET Framework) > MVC from the drop-down menu. Alternatively, you can open an existing MVC project. Replace the Index method in the HomeController file in the Controllers folder, or create a new controller in the Controllers folder.

The following is an example of how the code should be written:

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

namespace WebApplication8.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            using var PDF = HtmlToPdf.StaticRenderUrlAsPdf(new Uri("https://en.wikipedia.org"));
            return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf");
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}
using IronPdf;
using System;
using System.Web.Mvc;

namespace WebApplication8.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            using var PDF = HtmlToPdf.StaticRenderUrlAsPdf(new Uri("https://en.wikipedia.org"));
            return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf");
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}
Imports IronPdf
Imports System
Imports System.Web.Mvc

Namespace WebApplication8.Controllers
	Public Class HomeController
		Inherits Controller

		Public Function Index() As ActionResult
			Dim PDF = HtmlToPdf.StaticRenderUrlAsPdf(New Uri("https://en.wikipedia.org"))
			Return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf")
		End Function

		Public Function About() As ActionResult
			ViewBag.Message = "Your application description page."

			Return View()
		End Function

		Public Function Contact() As ActionResult
			ViewBag.Message = "Your contact page."

			Return View()
		End Function
	End Class
End Namespace
VB   C#

Add a Cover Page to a PDF document

How to view PDF files in ASP.NET using C# and IronPDF, Figure 1: Add a Cover Page to a PDF document Add a Cover Page to a PDF document

IronPDF simplifies the process of merging PDF documents. The most common application of this technique is to add a cover page or back page to an already-rendered PDF document that has been rendered.

To accomplish this, prepare a cover page and then use the PdfDocument capabilities.

To combine the two documents, use the Merge static method.

var renderer = new ChromePdfRenderer();
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");
var renderer = new ChromePdfRenderer();
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");
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/")
Dim merged = PdfDocument.Merge(New PdfDocument("CoverPage.pdf"), pdf)
merged.SaveAs("Combined.Pdf")
VB   C#

Add a Watermark to Your Document

Last but not least, adding a watermark to PDF documents can be accomplished using C# code; this can be used to add a disclaimer to each page of a document stating that it is "confidential" or "a sample."

// prepare a stamp
HtmlStamper stamper = new HtmlStamper("<h2 style='color:red'>SAMPLE</h2>")
{
    HorizontalOffset = new Length(-3, MeasurementUnit.Inch),
    VerticalAlignment = VerticalAlignment.Bottom
};

// Stamps a watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyStamp(stamper);
pdf.SaveAs(@"C:\PathToWatermarked.pdf");
// prepare a stamp
HtmlStamper stamper = new HtmlStamper("<h2 style='color:red'>SAMPLE</h2>")
{
    HorizontalOffset = new Length(-3, MeasurementUnit.Inch),
    VerticalAlignment = VerticalAlignment.Bottom
};

// Stamps a watermark onto a new or existing PDF
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.ApplyStamp(stamper);
pdf.SaveAs(@"C:\PathToWatermarked.pdf");
' prepare a stamp
Dim stamper As New HtmlStamper("<h2 style='color:red'>SAMPLE</h2>") With {
	.HorizontalOffset = New Length(-3, MeasurementUnit.Inch),
	.VerticalAlignment = VerticalAlignment.Bottom
}

' Stamps a watermark onto a new or existing PDF
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.ApplyStamp(stamper)
pdf.SaveAs("C:\PathToWatermarked.pdf")
VB   C#

Your PDF File Can Be Protected Using a Password

When you set the password property of a PDF document, it will be encrypted, and the user will be required to provide the correct password to read the document. This sample can be used in a.NET Core Console Application.

using IronPdf;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string [] args)
        {
            var renderer = new ChromePdfRenderer();
            using var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World<h1>");
            pdfDocument.Password = "strong!@#pass&^%word";
            pdfDocument.SaveAs("secured.pdf");
        }
    }
}
using IronPdf;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string [] args)
        {
            var renderer = new ChromePdfRenderer();
            using var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World<h1>");
            pdfDocument.Password = "strong!@#pass&^%word";
            pdfDocument.SaveAs("secured.pdf");
        }
    }
}
Imports IronPdf

Namespace ConsoleApp
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			Dim renderer = New ChromePdfRenderer()
			Dim pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World<h1>")
			pdfDocument.Password = "strong!@#pass&^%word"
			pdfDocument.SaveAs("secured.pdf")
		End Sub
	End Class
End Namespace
VB   C#

Without the advantages mentioned above, with the IronPDF, you can also:

Creating PDFs is such a challenging undertaking; some people may have never come across the fundamental notions they should employ to produce the most outstanding documents. As a result, IronPDF is extremely helpful, as it simplifies creating PDFs and, as a result, improves the original presentation of documents created from PDFs and HTML.

Based on the information provided in the documentation and competitor analysis: IronPDF is the most effective tool to use when creating PDFs, making it simple for anybody, including those who work in offices or schools, to complete their tasks efficiently.

How to view PDF files in ASP.NET using C# and IronPDF, Figure 2: How to view PDF files in ASP.NET using C# and IronPDF How to view PDF files in ASP.NET using C# and IronPDF

IronPDF is a must-have .NET library. Get yours now and try it with NuGet.

< PREVIOUS
Create PDF in C# from HTML File
NEXT >
5 steps to Generate a PDF File in C# using IRON PDF

Ready to get started? Version: 2024.6 just released

Start Free Trial Total downloads: 9,661,997
View Licenses >