How to view PDF files in ASP.NET using C# and IronPDF
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 ASP.NET PDF demonstration project.
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 command 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 directive at the top of any cs
class file that makes use of IronPDF:
using IronPdf;
using IronPdf;
Imports IronPdf
Check out IronPDF Detailed Features Overview.
IronPDF is a must-have plugin. Get yours now and try it with IronPDF NuGet Package.
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.
// Create a renderer to convert HTML to PDF
var renderer = new ChromePdfRenderer();
// Convert an HTML string to a PDF
using var renderedPdf = renderer.RenderHtmlAsPdf("<h1>My First HTML to Pdf</h1>");
// Define the output path for the PDF
var outputPath = "My_First_Html.pdf";
// Save the rendered PDF to the specified path
renderedPdf.SaveAs(outputPath);
// Automatically open the newly created PDF
System.Diagnostics.Process.Start(outputPath);
// Create a renderer to convert HTML to PDF
var renderer = new ChromePdfRenderer();
// Convert an HTML string to a PDF
using var renderedPdf = renderer.RenderHtmlAsPdf("<h1>My First HTML to Pdf</h1>");
// Define the output path for the PDF
var outputPath = "My_First_Html.pdf";
// Save the rendered PDF to the specified path
renderedPdf.SaveAs(outputPath);
// Automatically open the newly created PDF
System.Diagnostics.Process.Start(outputPath);
' Create a renderer to convert HTML to PDF
Dim renderer = New ChromePdfRenderer()
' Convert an HTML string to a PDF
Dim renderedPdf = renderer.RenderHtmlAsPdf("<h1>My First HTML to Pdf</h1>")
' Define the output path for the PDF
Dim outputPath = "My_First_Html.pdf"
' Save the rendered PDF to the specified path
renderedPdf.SaveAs(outputPath)
' Automatically open the newly created PDF
System.Diagnostics.Process.Start(outputPath)
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:
// Render HTML to PDF with a base path for local assets
var renderPdf = renderer.RenderHtmlAsPdf("<img src='image_1.png'/>", @"C:\Newproject");
// Render HTML to PDF with a base path for local assets
var renderPdf = renderer.RenderHtmlAsPdf("<img src='image_1.png'/>", @"C:\Newproject");
' Render HTML to PDF with a base path for local assets
Dim renderPdf = renderer.RenderHtmlAsPdf("<img src='image_1.png'/>", "C:\Newproject")
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 Using an Existing HTML URL
Existing URLs can be rendered into PDFs with C# efficiently; 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:
// Create a renderer for converting URLs to PDF
var renderer = new ChromePdfRenderer();
// Convert the specified URL to a PDF
using var renderedPdf = renderer.RenderUrlAsPdf("https://endeavorcreative.com/setting-up-wordpress-website-from-scratch/");
// Specify the output path for the PDF
var outputPath = "Url_pdf.pdf";
// Save the PDF to the specified path
renderedPdf.SaveAs(outputPath);
// Open the newly created PDF
System.Diagnostics.Process.Start(outputPath);
// Create a renderer for converting URLs to PDF
var renderer = new ChromePdfRenderer();
// Convert the specified URL to a PDF
using var renderedPdf = renderer.RenderUrlAsPdf("https://endeavorcreative.com/setting-up-wordpress-website-from-scratch/");
// Specify the output path for the PDF
var outputPath = "Url_pdf.pdf";
// Save the PDF to the specified path
renderedPdf.SaveAs(outputPath);
// Open the newly created PDF
System.Diagnostics.Process.Start(outputPath);
' Create a renderer for converting URLs to PDF
Dim renderer = New ChromePdfRenderer()
' Convert the specified URL to a PDF
Dim renderedPdf = renderer.RenderUrlAsPdf("https://endeavorcreative.com/setting-up-wordpress-website-from-scratch/")
' Specify the output path for the PDF
Dim outputPath = "Url_pdf.pdf"
' Save the PDF to the specified path
renderedPdf.SaveAs(outputPath)
' Open the newly created PDF
System.Diagnostics.Process.Start(outputPath)
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.
// Create a renderer for existing HTML files
var renderer = new ChromePdfRenderer();
// Render an HTML file to PDF
using var renderedPdf = renderer.RenderHtmlFileAsPdf("Assets/test1.html");
// Specify the output path for the PDF
var outputPath = "test1_pdf.pdf";
// Save the PDF to the specified path
renderedPdf.SaveAs(outputPath);
// Open the newly created PDF
System.Diagnostics.Process.Start(outputPath);
// Create a renderer for existing HTML files
var renderer = new ChromePdfRenderer();
// Render an HTML file to PDF
using var renderedPdf = renderer.RenderHtmlFileAsPdf("Assets/test1.html");
// Specify the output path for the PDF
var outputPath = "test1_pdf.pdf";
// Save the PDF to the specified path
renderedPdf.SaveAs(outputPath);
// Open the newly created PDF
System.Diagnostics.Process.Start(outputPath);
' Create a renderer for existing HTML files
Dim renderer = New ChromePdfRenderer()
' Render an HTML file to PDF
Dim renderedPdf = renderer.RenderHtmlFileAsPdf("Assets/test1.html")
' Specify the output path for the PDF
Dim outputPath = "test1_pdf.pdf"
' Save the PDF to the specified path
renderedPdf.SaveAs(outputPath)
' Open the newly created PDF
System.Diagnostics.Process.Start(outputPath)
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 use XML to PDF Conversion as 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.
Navigate 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)
{
// Render the current page as a PDF in the browser
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)
{
// Render the current page as a PDF in the browser
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)
' Render the current page as a PDF in the browser
AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser)
End Sub
End Class
End Namespace
This requires the IronPdf.Extensions.ASPX NuGet Package 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.
// Basic HTML String Formatting
string formattedString = String.Format("<h1>Hello {0}!</h1>", "World");
// Basic HTML String Formatting
string formattedString = String.Format("<h1>Hello {0}!</h1>", "World");
' Basic HTML String Formatting
Dim formattedString As String = String.Format("<h1>Hello {0}!</h1>", "World")
Because HTML files can be pretty extensive, it is common to utilize arbitrary placeholders, such as [[NAME]], and then replace them with the actual data.
The following example will generate three PDF documents, each of which will be customized for a different user.
// Define an HTML template with a placeholder
var htmlTemplate = "<p>[[NAME]]</p>";
// Sample data to replace placeholders
var names = new[] { "John", "James", "Jenny" };
// Create a new PDF for each name
foreach (var name in names)
{
// Replace placeholder with actual name
var htmlInstance = htmlTemplate.Replace("[[NAME]]", name);
// Create a renderer and render the HTML as PDF
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(htmlInstance);
// Save the PDF with the name in the filename
pdf.SaveAs($"{name}.pdf");
}
// Define an HTML template with a placeholder
var htmlTemplate = "<p>[[NAME]]</p>";
// Sample data to replace placeholders
var names = new[] { "John", "James", "Jenny" };
// Create a new PDF for each name
foreach (var name in names)
{
// Replace placeholder with actual name
var htmlInstance = htmlTemplate.Replace("[[NAME]]", name);
// Create a renderer and render the HTML as PDF
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderHtmlAsPdf(htmlInstance);
// Save the PDF with the name in the filename
pdf.SaveAs($"{name}.pdf");
}
' Define an HTML template with a placeholder
Dim htmlTemplate = "<p>[[NAME]]</p>"
' Sample data to replace placeholders
Dim names = { "John", "James", "Jenny" }
' Create a new PDF for each name
For Each name In names
' Replace placeholder with actual name
Dim htmlInstance = htmlTemplate.Replace("[[NAME]]", name)
' Create a renderer and render the HTML as PDF
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlInstance)
' Save the PDF with the name in the filename
pdf.SaveAs($"{name}.pdf")
Next name
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()
{
// Render a URL as PDF and return it in the response
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()
{
// Render a URL as PDF and return it in the response
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
' Render a URL as PDF and return it in the response
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
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 PDF Documents Method
.
// Create a renderer and render a PDF from a URL
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/");
// Merge the cover page with the rendered PDF
using var merged = PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), pdf);
// Save the merged document
merged.SaveAs("Combined.Pdf");
// Create a renderer and render a PDF from a URL
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/");
// Merge the cover page with the rendered PDF
using var merged = PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), pdf);
// Save the merged document
merged.SaveAs("Combined.Pdf");
' Create a renderer and render a PDF from a URL
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/")
' Merge the cover page with the rendered PDF
Dim merged = PdfDocument.Merge(New PdfDocument("CoverPage.pdf"), pdf)
' Save the merged document
merged.SaveAs("Combined.Pdf")
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 stamper with HTML content for the watermark
HtmlStamper stamper = new HtmlStamper("<h2 style='color:red'>SAMPLE</h2>")
{
HorizontalOffset = new Length(-3, MeasurementUnit.Inch),
VerticalAlignment = VerticalAlignment.Bottom
};
// Create a renderer and render a PDF from a URL
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
// Apply the watermark to the PDF
pdf.ApplyStamp(stamper);
// Save the watermarked PDF
pdf.SaveAs(@"C:\PathToWatermarked.pdf");
// Prepare a stamper with HTML content for the watermark
HtmlStamper stamper = new HtmlStamper("<h2 style='color:red'>SAMPLE</h2>")
{
HorizontalOffset = new Length(-3, MeasurementUnit.Inch),
VerticalAlignment = VerticalAlignment.Bottom
};
// Create a renderer and render a PDF from a URL
var renderer = new ChromePdfRenderer();
using var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
// Apply the watermark to the PDF
pdf.ApplyStamp(stamper);
// Save the watermarked PDF
pdf.SaveAs(@"C:\PathToWatermarked.pdf");
' Prepare a stamper with HTML content for the watermark
Dim stamper As New HtmlStamper("<h2 style='color:red'>SAMPLE</h2>") With {
.HorizontalOffset = New Length(-3, MeasurementUnit.Inch),
.VerticalAlignment = VerticalAlignment.Bottom
}
' Create a renderer and render a PDF from a URL
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
' Apply the watermark to the PDF
pdf.ApplyStamp(stamper)
' Save the watermarked PDF
pdf.SaveAs("C:\PathToWatermarked.pdf")
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)
{
// Create a renderer and render a PDF from HTML
var renderer = new ChromePdfRenderer();
using var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
// Set password to protect the PDF
pdfDocument.Password = "strong!@#pass&^%word";
// Save the secured PDF
pdfDocument.SaveAs("secured.pdf");
}
}
}
using IronPdf;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
// Create a renderer and render a PDF from HTML
var renderer = new ChromePdfRenderer();
using var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");
// Set password to protect the PDF
pdfDocument.Password = "strong!@#pass&^%word";
// Save the secured PDF
pdfDocument.SaveAs("secured.pdf");
}
}
}
Imports IronPdf
Namespace ConsoleApp
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Create a renderer and render a PDF from HTML
Dim renderer = New ChromePdfRenderer()
Dim pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")
' Set password to protect the PDF
pdfDocument.Password = "strong!@#pass&^%word"
' Save the secured PDF
pdfDocument.SaveAs("secured.pdf")
End Sub
End Class
End Namespace
Without the advantages mentioned above, with IronPDF, you can also:
- Extract images and text from PDFs
- Edit the HTML content of PDFs
- Enhance foreground and background images
- Add digital signature to PDFs
- Auto-fill your PDF forms quickly and effortlessly
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
IronPDF is a must-have .NET library. Get yours now and try it with IronPDF NuGet Package.
Frequently Asked Questions
How can I view a PDF file in an ASP.NET application using C#?
You can use IronPDF to view PDF files in an ASP.NET application by rendering the PDF to an image or an HTML element that can be embedded within a web page.
What are the steps to convert an HTML page to a PDF in ASP.NET?
To convert an HTML page to a PDF in ASP.NET, you can use IronPDF's RenderHtmlAsPdf
method, which supports CSS and JavaScript for accurate rendering.
How can I merge multiple PDF documents in C#?
IronPDF allows you to merge multiple PDF documents using the PdfDocument.Merge
method which combines different PDF files into a single document.
Is it possible to add watermarks to PDF documents in ASP.NET?
Yes, you can add watermarks to PDF documents in ASP.NET using IronPDF by employing the HtmlStamper
class to overlay custom HTML content.
How do I implement password protection on a PDF file using C#?
You can implement password protection on a PDF file using IronPDF by setting the Password
property on a PdfDocument
to encrypt the file.
Can IronPDF be used to convert ASP.NET Web Forms to PDF?
Yes, IronPDF can convert ASP.NET Web Forms to PDF by using methods like RenderThisPageAsPdf
, capturing the whole web form as a PDF document.
What advantages does IronPDF provide for PDF generation in ASP.NET?
IronPDF provides advantages such as accurate rendering of HTML, CSS, and JavaScript using a built-in Google Chromium engine, making it a flexible tool for PDF generation in ASP.NET.
How can I install IronPDF in my ASP.NET project?
You can install IronPDF in your ASP.NET project via the NuGet Package Manager or by downloading the DLL file directly from the IronPDF website.
What makes IronPDF a valuable asset for software developers?
IronPDF is a valuable asset for software developers as it simplifies complex PDF generation tasks and integrates seamlessly into ASP.NET applications for efficient PDF manipulation.
How can I create a PDF from a URL in C# using IronPDF?
You can create a PDF from a URL in C# using IronPDF's RenderUrlAsPdf
method, which fetches the content from the URL and converts it into a PDF document.