USING IRONPDF

C# Create PDF (Code Example Tutorial)

Updated September 4, 2024
Share:

This article will teach you how to produce PDF documents from a web page in the C# .NET programming language using IronPDF.

IronPDF is a fully-featured PDF library for .NET and Java. It is one of several third-party libraries available that work efficiently in creating, editing, and processing PDF documents, as well as in outputting editable PDF files from the content of other file types (HTML, PNG, RTF, etc.). Find out more about IronPDF and similar PDF libraries from the growing catalog of comparison articles.

As HTML is a markup language, it can be difficult to convert the contents of HTML to a PDF without the HTML tags. IronPDF offers features such as creating PDF in C# from HTML, because of its ease of use and additional features like using JavaScript, CSS, and images.

This article will cover the HTML to PDF conversion in C#, provided by IronPDF, in detail.


1. Create a New Project in Visual Studio

Open the Visual Studio software and go to the File menu. Select New Project and then select Console Application. This article will use a Console Application to generate PDF documents.

C# Create PDF (Code Example Tutorial), Figure 01: Create a new project in Visual Studio Create a new project in Visual Studio

Enter the project name and select the path in the appropriate TextBox. Then, click the Next button.

C# Create PDF (Code Example Tutorial), Figure 02: Configure this project Configure this project

Select the required .NET Framework then, click the Create button, as shown below:

C# Create PDF (Code Example Tutorial), Figure 03: .NET Framework selection .NET Framework selection

The Visual Studio project will now generate the structure for the selected application, and if you have selected the Console, Windows, and Web Application, it will open the program.cs file where you can enter the code and build/run the application.

The next step is to add the library and test the program.

Using the Visual Studio NuGet Package Manager

The Visual Studio software provides the NuGet Package Manager option to install the package directly to the solution. The below screenshot shows how to open the NuGet Package Manager.

Don't worry about the license key, IronPDF is free for development.

C# Create PDF (Code Example Tutorial), Figure 04: Navigate to NuGet Package Manager Navigate to NuGet Package Manager

It provides the search box to show the list of available package libraries from the NuGet website. In the package manager, search for the keyword "IronPDF", as shown in the below screenshot:

C# Create PDF (Code Example Tutorial), Figure 05: Install the IronPdf package from the NuGet Package Manager Install the IronPdf package from the NuGet Package Manager

From the image above, select the IronPDF option from the list of related NuGet packages and install the package for the solution.

Using the Visual Studio Command-Line

In the Visual Studio menu, Go to Tools > NuGet Package Manager > Package Manager Console

C# Create PDF (Code Example Tutorial), Figure 06: Navigate to Package Manager Console Navigate to Package Manager Console

Enter the following line in the Package Manager Console tab:

Install-Package IronPdf

C# Create PDF (Code Example Tutorial), Figure 07: Installation step Installation step

Now the package will download/install to the current project and be ready to use.

C# Create PDF (Code Example Tutorial), Figure 08: Installation process in Package Manager Console Installation process in Package Manager Console

2. Create a PDF from HTML using RenderHtmlAsPdf()

After the IronPDF library is installed, the first objective is to create a PDFDocument object in C#. Copy the code below and paste it into your Visual Studio, then run the program.

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

var pdf = new ChromePdfRenderer();
PdfDocument doc = pdf.RenderHtmlAsPdf("<h1>This is a heading</h1>");
mypdf.SaveAs("FirstPDFDocument.pdf");
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

var pdf = new ChromePdfRenderer();
PdfDocument doc = pdf.RenderHtmlAsPdf("<h1>This is a heading</h1>");
mypdf.SaveAs("FirstPDFDocument.pdf");
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

Dim pdf = New ChromePdfRenderer()
Dim doc As PdfDocument = pdf.RenderHtmlAsPdf("<h1>This is a heading</h1>")
mypdf.SaveAs("FirstPDFDocument.pdf")
VB   C#

After execution of your C# project there will be a file mane "FirstPDFDocument.pdf" in the bin folder of your project, double click on the said file, and the PDF file will open in the browser tab.

C# Create PDF (Code Example Tutorial), Figure 09:


Creating PDF files in C# or creating PDF files converting HTML to PDF is just a few lines of code using IronPDF.

3. Create a PDF Document from a URL

Creating a PDF file in C# using a URL is just as easy as the above example with just these three lines of code, the following code will demonstrate how to create PDF files from a URL.

using IronPdf;

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

var renderer = new IronPdf.ChromePdfRenderer();
// Create a PDF from a URL or local file path
using var pdf = renderer.RenderUrlAsPdf("https://www.amazon.com/?tag=hp2-brobookmark-us-20");
// Export to a file or Stream
pdf.SaveAs("url.pdf");
using IronPdf;

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

var renderer = new IronPdf.ChromePdfRenderer();
// Create a PDF from a URL or local file path
using var pdf = renderer.RenderUrlAsPdf("https://www.amazon.com/?tag=hp2-brobookmark-us-20");
// Export to a file or Stream
pdf.SaveAs("url.pdf");
Imports IronPdf

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

Dim renderer = New IronPdf.ChromePdfRenderer()
' Create a PDF from a URL or local file path
Dim pdf = renderer.RenderUrlAsPdf("https://www.amazon.com/?tag=hp2-brobookmark-us-20")
' Export to a file or Stream
pdf.SaveAs("url.pdf")
VB   C#

Here is the output of the above code.

C# Create PDF (Code Example Tutorial), Figure 10: PDF file output, rendered from a URL PDF file output, rendered from a URL

Other examples of converting popular complex sites to PDF.

C# Create PDF (Code Example Tutorial), Figure 11: Another example of rendering a complex website Another example of rendering a complex website

4. Render ASP.NET MVC to PDF

You can serve an existing HTML file or string, an existing PDF document, or a PDF in ASP.NET MVC. To easily serve these files or strings, use IronPDF and access it via a DLL ZIP file or through the NuGet page.

To serve a PDF document in ASP.NET MVC requires generating a FileResult method. With IronPDF you can use MVC to return a PDF file.

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

var renderer = new IronPdf.ChromePdfRenderer();
using var pdf = renderer.RenderHtmlFileAsPdf("Project/MyHtmlDocument.html");
// or to convert an HTML string
//var pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment;filename=\"FileName.pdf\"");
// edit this line to display ion browser and change the file name
Response.BinaryWrite(pdf.BinaryData);
Response.Flush();
Response.End();
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

var renderer = new IronPdf.ChromePdfRenderer();
using var pdf = renderer.RenderHtmlFileAsPdf("Project/MyHtmlDocument.html");
// or to convert an HTML string
//var pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition","attachment;filename=\"FileName.pdf\"");
// edit this line to display ion browser and change the file name
Response.BinaryWrite(pdf.BinaryData);
Response.Flush();
Response.End();
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

Dim renderer = New IronPdf.ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlFileAsPdf("Project/MyHtmlDocument.html")
' or to convert an HTML string
'var pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("Content-Disposition","attachment;filename=""FileName.pdf""")
' edit this line to display ion browser and change the file name
Response.BinaryWrite(pdf.BinaryData)
Response.Flush()
Response.End()
VB   C#

5. Render Razor Views To PDF

The following method makes it easy to render a Razor view to a string. IronPDF's HTML to PDF functionality can be used to render that Razor view as a string. Don't forget to set the optional BaseURI parameter of the IronPdf.ChromePdfRenderer.RenderHtmlAsPdf Method to load relative assets, CSS, JavaScript and images. Here is an example:

public string RenderRazorViewToString(string viewName, object model)
{ 
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

    ViewData.Model = model;
    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
        viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View,
        ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}
public string RenderRazorViewToString(string viewName, object model)
{ 
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

    ViewData.Model = model;
    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
        viewName);
        var viewContext = new ViewContext(ControllerContext, viewResult.View,
        ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}
Public Function RenderRazorViewToString(ByVal viewName As String, ByVal model As Object) As String
	IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

	ViewData.Model = model
	Using sw = New StringWriter()
		Dim viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName)
		Dim viewContext As New ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw)
		viewResult.View.Render(viewContext, sw)
		viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View)
		Return sw.GetStringBuilder().ToString()
	End Using
End Function
VB   C#

Please read the .NET MVC PDF documentation page to learn how to render an MVC view as a binary PDF file.

6. Convert XML to PDF

C# XML to PDF directly can be a complex challenge, and it is best to start with XSLT. XML and may be rendered to PDF via HTML(5) using XLST transformations.

These documents define how XML from a given schema may be converted to an accurate HTML representation and are a well-established standard.

The resultant HTML string or file may then be rendered as a PDF using the .NET PDF Generator:

Here is an example:

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

XslCompiledTransform transform = new XslCompiledTransform();
using(XmlReader reader = XmlReader.Create(new StringReader(XSLT))) {
    transform.Load(reader);
}
StringWriter results = new StringWriter();
using(XmlReader reader = XmlReader.Create(new StringReader(XML))) {
    transform.Transform(reader, null, results);
}
IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();
// options, headers and footers may be set there
// Render the XML as a PDF via XSLT
Renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf");
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

XslCompiledTransform transform = new XslCompiledTransform();
using(XmlReader reader = XmlReader.Create(new StringReader(XSLT))) {
    transform.Load(reader);
}
StringWriter results = new StringWriter();
using(XmlReader reader = XmlReader.Create(new StringReader(XML))) {
    transform.Transform(reader, null, results);
}
IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();
// options, headers and footers may be set there
// Render the XML as a PDF via XSLT
Renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf");
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

Dim transform As New XslCompiledTransform()
Using reader As XmlReader = XmlReader.Create(New StringReader(XSLT))
	transform.Load(reader)
End Using
Dim results As New StringWriter()
Using reader As XmlReader = XmlReader.Create(New StringReader(XML))
	transform.Transform(reader, Nothing, results)
End Using
Dim Renderer As New IronPdf.ChromePdfRenderer()
' options, headers and footers may be set there
' Render the XML as a PDF via XSLT
Renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf")
VB   C#

7. Generate PDF Reports

IronPDF can be used as a PDF reader C# and help visualize and export SSRS reports to PDF in ASP.NET C#. IronPDF can be used to render snapshots of data as "reports" in the PDF File Format. It also works as a PDF C# parser. The basic methodology is to first generate the report as an HTML document - and then render the HTML as a PDF using IronPDF.

To style an XML report, the XML may be parsed and then the HTML is generated with the data. These reports may be generated as HTML which may then be customized and converted to PDF format using IronPDF. The easiest way to serve HTML content in ASP.NET is to use the IronPdf.AspxToPdf class on the Form_Load event of an ASP.NET WebForms.

Here is an example:

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();
// add a header to very page easily
Renderer.RenderingOptions.FirstPageNumber = 1;
Renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
Renderer.RenderingOptions.TextHeader.CenterText = "{url}";
Renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Helvetica;
Renderer.RenderingOptions.TextHeader.FontSize = 12;
// add a footer too
Renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
Renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial;
Renderer.RenderingOptions.TextFooter.FontSize = 10;
Renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
Renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";
Renderer.RenderHtmlFileAsPdf("Report.html").SaveAs("Report.pdf");
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();
// add a header to very page easily
Renderer.RenderingOptions.FirstPageNumber = 1;
Renderer.RenderingOptions.TextHeader.DrawDividerLine = true;
Renderer.RenderingOptions.TextHeader.CenterText = "{url}";
Renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Helvetica;
Renderer.RenderingOptions.TextHeader.FontSize = 12;
// add a footer too
Renderer.RenderingOptions.TextFooter.DrawDividerLine = true;
Renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial;
Renderer.RenderingOptions.TextFooter.FontSize = 10;
Renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}";
Renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}";
Renderer.RenderHtmlFileAsPdf("Report.html").SaveAs("Report.pdf");
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

Dim Renderer As New IronPdf.ChromePdfRenderer()
' add a header to very page easily
Renderer.RenderingOptions.FirstPageNumber = 1
Renderer.RenderingOptions.TextHeader.DrawDividerLine = True
Renderer.RenderingOptions.TextHeader.CenterText = "{url}"
Renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Helvetica
Renderer.RenderingOptions.TextHeader.FontSize = 12
' add a footer too
Renderer.RenderingOptions.TextFooter.DrawDividerLine = True
Renderer.RenderingOptions.TextFooter.Font = IronSoftware.Drawing.FontTypes.Arial
Renderer.RenderingOptions.TextFooter.FontSize = 10
Renderer.RenderingOptions.TextFooter.LeftText = "{date} {time}"
Renderer.RenderingOptions.TextFooter.RightText = "{page} of {total-pages}"
Renderer.RenderHtmlFileAsPdf("Report.html").SaveAs("Report.pdf")
VB   C#

C# Create PDF (Code Example Tutorial), Figure 12: CSharp Create PDF CSharp Create PDF

8. Work with PDF images and CSS

To use IronPDF to convert HTML String to PDF, provide a BaseUri when working with assets. All assets such as CSS, JavaScript files, and images will be loaded relative to that base URL.

The BaseURL may be a web URL starting with "http" to load remote assets, or a local file path to access assets on your disk.

Another trick is to use the IronPdf.Imaging.ImageUtilities.ImageToDataUri method to convert any System.Drawing.Image or Bitmap object into an HTML string which can be embedded in HTML without saving to disk. Here is an example:

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

using var pdf = Renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>",@"C:\site\assets\");
pdf.SaveAs("html-with-assets.pdf");
var renderer = new IronPdf.ChromePdfRenderer();
using var advancedPDF = renderer.RenderHtmlFileAsPdf("C:\\Assets\\TestInvoice1.html");
advancedPDF.SaveAs("Invoice.pdf");
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

using var pdf = Renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>",@"C:\site\assets\");
pdf.SaveAs("html-with-assets.pdf");
var renderer = new IronPdf.ChromePdfRenderer();
using var advancedPDF = renderer.RenderHtmlFileAsPdf("C:\\Assets\\TestInvoice1.html");
advancedPDF.SaveAs("Invoice.pdf");
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

Dim pdf = Renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>","C:\site\assets\")
pdf.SaveAs("html-with-assets.pdf")
Dim renderer = New IronPdf.ChromePdfRenderer()
Dim advancedPDF = renderer.RenderHtmlFileAsPdf("C:\Assets\TestInvoice1.html")
advancedPDF.SaveAs("Invoice.pdf")
VB   C#

9. Convert ASPX Files to PDF

First, let's access the 'free for development' C# Library for converting ASPX files to PDF. You can download it directly or access it via NuGet. Install as usual into your Visual Studio project. Additionally, it 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. Now that you have IronPDF and its extensions, you'll see that it has the functionality for HTML conversion as well as ASPX to PDF generation as in the code below.

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

namespace aspxtopdf
{
    public partial class SiteMaster : MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
            AspxToPdf.RenderThisPageAsPdf();
        }
    }
}
using System;
using System.Web.UI;
using IronPdf;

namespace aspxtopdf
{
    public partial class SiteMaster : MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
            AspxToPdf.RenderThisPageAsPdf();
        }
    }
}
Imports System
Imports System.Web.UI
Imports IronPdf

Namespace aspxtopdf
	Partial Public Class SiteMaster
		Inherits MasterPage

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
			IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
			AspxToPdf.RenderThisPageAsPdf()
		End Sub
	End Class
End Namespace
VB   C#

C# Create PDF (Code Example Tutorial), Figure 13: CSharp Create PDF CSharp Create PDF

10. View HTML to PDF Example File

The code below demonstrates how IronPDF can be used to convert HTML to PDF documents programmatically.

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

var uri = new Uri("https://www.c-sharpcorner.com/article/how-to-create-pdf-file-in-c-sharp-using-ironpdf/");
// turn page into pdf
var pdf = ChromePdfRenderer.StaticRenderUrlAsPdf(uri);
// save resulting pdf into file
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdf.Pdf"));
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

var uri = new Uri("https://www.c-sharpcorner.com/article/how-to-create-pdf-file-in-c-sharp-using-ironpdf/");
// turn page into pdf
var pdf = ChromePdfRenderer.StaticRenderUrlAsPdf(uri);
// save resulting pdf into file
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdf.Pdf"));
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

Dim uri As New Uri("https://www.c-sharpcorner.com/article/how-to-create-pdf-file-in-c-sharp-using-ironpdf/")
' turn page into pdf
Dim pdf = ChromePdfRenderer.StaticRenderUrlAsPdf(uri)
' save resulting pdf into file
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdf.Pdf"))
VB   C#

The PDF file is created inside the Debug folder. Here is the output:

C# Create PDF (Code Example Tutorial), Figure 14: CSharp Create PDF CSharp Create PDF

The Getting Started Guide explains how to install IronPDF via NuGet (for those who are unfamiliar with the NuGet Package Manager).

11. Generate PDF File in C# .NET

With an extensive C# library using IronPDF, any ASP.NET page can easily be converted from HTML to PDF. This allows full control over reading, editing, and manipulating documents with just a single line of code.

Here is an example:

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

namespace aspxtopdf
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
            AspxToPdf.RenderThisPageAsPdf();
        }
    }
}
using System;
using System.Web.UI;
using IronPdf;

namespace aspxtopdf
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
            AspxToPdf.RenderThisPageAsPdf();
        }
    }
}
Imports System
Imports System.Web.UI
Imports IronPdf

Namespace aspxtopdf
	Partial Public Class _Default
		Inherits Page

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

		End Sub

		Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
			IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
			AspxToPdf.RenderThisPageAsPdf()
		End Sub
	End Class
End Namespace
VB   C#

C# Create PDF (Code Example Tutorial), Figure 15: CSharp Create PDF CSharp Create PDF

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

12. Generate PDF Document

Install the IronPDF C# HTML to PDF library. Access the software by direct file download.

Here is a very quick example of how to generate a PDF from an HTML input string:

/**
PDF from HTML String
anchor-generate-pdf-from-html-string
**/
private void HTMLString()
{
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

    // Render any HTML fragment or document to HTML
    var renderer = new IronPdf.ChromePdfRenderer();
    using var pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");
    var outputPath = "ChromePdfRenderer.pdf";
    pdf.SaveAs(outputPath);
}
/**
PDF from HTML String
anchor-generate-pdf-from-html-string
**/
private void HTMLString()
{
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

    // Render any HTML fragment or document to HTML
    var renderer = new IronPdf.ChromePdfRenderer();
    using var pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");
    var outputPath = "ChromePdfRenderer.pdf";
    pdf.SaveAs(outputPath);
}
'''
'''PDF from HTML String
'''anchor-generate-pdf-from-html-string
'''*
Private Sub HTMLString()
	IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

	' Render any HTML fragment or document to HTML
	Dim renderer = New IronPdf.ChromePdfRenderer()
	Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF</h1>")
	Dim outputPath = "ChromePdfRenderer.pdf"
	pdf.SaveAs(outputPath)
End Sub
VB   C#

The following code makes use of IronPDF to generate a PDF directly from an ASPX file:

/**
PDF from ASPX
anchor-generate-pdf-from-aspx
**/
protected void Page_Load(object sender, EventArgs e)
{
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
    IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
/**
PDF from ASPX
anchor-generate-pdf-from-aspx
**/
protected void Page_Load(object sender, EventArgs e)
{
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
    IronPdf.AspxToPdf.RenderThisPageAsPdf();
}
'''
'''PDF from ASPX
'''anchor-generate-pdf-from-aspx
'''*
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
	IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"
	IronPdf.AspxToPdf.RenderThisPageAsPdf()
End Sub
VB   C#

IronPDF supports JavaScript quite nicely via the Chromium rendering engine. One stipulation though, you may have to add a delay to a page render to allow JavaScript time to execute whilst generating PDFs.

13. PDF Library For .NET

Using IronPDF, we're able to create and edit PDF features simply according to application requirements. IronPDF provides a suite of functionality with its C# .NET PDF Library. The two main ways of accessing the library are to either:

  1. Download and unpack the DLL file
  2. Navigate NuGet and install the package via Visual Studio.

In the code below, C# Forms with button1_Click demonstrate how simple it is to create a PDF with C#.

using IronPdf;
using System.Windows.Forms;

namespace ReadPdf
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

            //Used ChromePdfRenderer Convert Class
            var renderer = new ChromePdfRenderer();
            //Getting Text from TextBox
            string text = textBox1.Text;
            //rendering or converting htmlaspdf.
            renderer.RenderHtmlAsPdf("<h1>"+text+"</h1>").SaveAs("custom.pdf");
            //Confirmation
            MessageBox.Show("Done !");
        }
    }
}
using IronPdf;
using System.Windows.Forms;

namespace ReadPdf
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

            //Used ChromePdfRenderer Convert Class
            var renderer = new ChromePdfRenderer();
            //Getting Text from TextBox
            string text = textBox1.Text;
            //rendering or converting htmlaspdf.
            renderer.RenderHtmlAsPdf("<h1>"+text+"</h1>").SaveAs("custom.pdf");
            //Confirmation
            MessageBox.Show("Done !");
        }
    }
}
Imports IronPdf
Imports System.Windows.Forms

Namespace ReadPdf
	Partial Public Class Form1
		Inherits Form

		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

			'Used ChromePdfRenderer Convert Class
			Dim renderer = New ChromePdfRenderer()
			'Getting Text from TextBox
'INSTANT VB NOTE: The variable text was renamed since Visual Basic does not handle local variables named the same as class members well:
			Dim text_Conflict As String = textBox1.Text
			'rendering or converting htmlaspdf.
			renderer.RenderHtmlAsPdf("<h1>" & text_Conflict &"</h1>").SaveAs("custom.pdf")
			'Confirmation
			MessageBox.Show("Done !")
		End Sub
	End Class
End Namespace
VB   C#

C# Form:

C# Create PDF (Code Example Tutorial), Figure 16: CSharp Create PDF CSharp Create PDF

14. Chrome PDF Rendering Engine

The Iron Software engineering team is proud to release a game-changing upgrade to IronPDF in 2021, now featuring "Chrome Identical" PDF rendering.

First, you must install IronPDF into your project from the NuGet Package Manager named IronPdf. Changing to the new renderer at a global level is simple. This approach updates all usages of your existing ChromePdfRenderer and AspxToPdf code.

Some of the Features of Chrome PDF Rendering Feature are:

  1. High-Quality Rendering
    1. The latest "Blink!" HTML rendering. Choose from Chrome Identical rendering or Enhanced Rendering
  2. 20% Faster Renders
    1. Provides effortless multithreading and Async, using as many CPU cores as you wish. For SAAS and high-load applications, this may be 5-20 times faster, outperforming direct browser usage and web-drivers.
  3. Full Support
    1. Full support for JavaScript, responsive layout and CSS3.
    2. Azure as a first-class citizen. It just works.
    3. Continued maintenance and improved full support for .NET 6, 5, Core, and Framework 4.0+.
  4. Rigorously Tested
    1. The release passed with 1156 green units & integration tests (and no red ones), ensuring stability similar to the main release, and continuously and actively improving it every day.
  5. Section 508 Accessibility Compliance

Produces accessible PDFs using the PDF(UA) tagged PDF standard.

Multithreading and Async support for the Chrome rendering engine is in a different league from the previous build.

  1. For enterprise-grade multithreading, use the ChromePdfRenderer in your existing threads and it will work. For web applications, this also takes zero setups.
  2. For batch processing of HTML to PDF, it is recommended to use the built-in .NET Parallel.ForEach pattern.
  3. Async variants are provided for all of the rendering methods such as ChromePdfRenderer.RenderHtmlAsPdfAsync

Here is an example:

IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

IChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

using var doc = renderer.RenderHtmlAsPdf("<h1>Hello world! This is sample for IronPdf</h1>");
doc.SaveAs("google_chrome.pdf");
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

IChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
renderer.RenderingOptions.PrintHtmlBackgrounds = true;
renderer.RenderingOptions.CreatePdfFormsFromHtml = true;

using var doc = renderer.RenderHtmlAsPdf("<h1>Hello world! This is sample for IronPdf</h1>");
doc.SaveAs("google_chrome.pdf");
IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

Dim renderer As IChromePdfRenderer = New ChromePdfRenderer()
renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen
renderer.RenderingOptions.PrintHtmlBackgrounds = True
renderer.RenderingOptions.CreatePdfFormsFromHtml = True

Dim doc = renderer.RenderHtmlAsPdf("<h1>Hello world! This is sample for IronPdf</h1>")
doc.SaveAs("google_chrome.pdf")
VB   C#

C# Create PDF (Code Example Tutorial), Figure 17: CSharp Create PDF CSharp Create PDF

15. Summary

Thanks for reading! This article demonstrated how to create a PDF document in C# using IronPDF. IronPDF is ideal for users needing to convert the contents of HTML to PDF without using HTML tags because of its ease of use and additional features like JavaScript, CSS, and images.

So, try out these methods and leave your feedback in the comments section of this article post! If you are not yet an IronPDF customer, you can try the 30-day free trial to check out their available features.

If you buy the complete Iron Suite, you will get All 7 Products for the Price of 2. For further details about the licensing, Visit the pricing page to purchase the complete package.


Library Quick Access

Read API Reference

IronPDF documentation available in the interactive API Reference.

Read API Reference
< PREVIOUS
.NET Core PDF Library
NEXT >
x509certificate2 Add Digital Signature to PDF Programmatically

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >