USING IRONPDF

Create PDF in C# from HTML File

Updated January 20, 2024
Share:

IronPDF converts HTML to PDF documents programmatically.

How to Create a PDF in C# - HTML to PDF Example

A simple example of this technique can be downloaded and viewed as a PDF Example.

The source code for this entire article is available for C# as a C# HTML to PDF Project Source Code Download.

The following tutorial will walk you through the process of using IronPDF as a C# PDF Generator. It covers the basics as well as many advanced C# PDF topics.

HTML to PDF Walkthrough

This demo walks you through examples of how to use IronPdf. Request additional use case demos from Iron Software.

The demo consists of Hello World, RenderHtmlAsPdf and RenderUrlAsPdf examples. All the examples can be found under corresponding projects under IronPDF Demo solution.

Step 1: Installation

You can install IronPdf either via NuGet. The package name is IronPDF NuGet Package.

Or you can use the Direct Library Download.

Step 2: Hello World

Once you have IronPDF installed and referenced in your project, you can start using it right away by typing a couple of strings:

var ChromePdfRenderer = new ChromePdfRenderer();  // new instance of ChromePdfRenderer
var ChromePdfRenderer = new ChromePdfRenderer();  // new instance of ChromePdfRenderer
Dim ChromePdfRenderer As New ChromePdfRenderer() ' new instance of ChromePdfRenderer
VB   C#

then if you need to turn HTML into PDF

// html to turn into pdf
var html = @"<h1>Hello World!</h1><br><p>This is IronPdf.</p>";
// turn html to pdf
using var pdf = ChromePdfRenderer.RenderHtmlAsPdf(html);
// save resulting pdf into file
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "ChromePdfRenderer.Pdf"));
// html to turn into pdf
var html = @"<h1>Hello World!</h1><br><p>This is IronPdf.</p>";
// turn html to pdf
using var pdf = ChromePdfRenderer.RenderHtmlAsPdf(html);
// save resulting pdf into file
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "ChromePdfRenderer.Pdf"));
' html to turn into pdf
Dim html = "<h1>Hello World!</h1><br><p>This is IronPdf.</p>"
' turn html to pdf
Dim pdf = ChromePdfRenderer.RenderHtmlAsPdf(html)
' save resulting pdf into file
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "ChromePdfRenderer.Pdf"))
VB   C#

or if you want to turn a web page into a PDF file

// uri of the page to turn into pdf
var uri = new Uri("http://www.google.com/ncr");
// turn page into pdf
pdf = ChromePdfRenderer.RenderUrlAsPdf(uri);
// save resulting pdf into file
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdf.Pdf"));
// uri of the page to turn into pdf
var uri = new Uri("http://www.google.com/ncr");
// turn page into pdf
pdf = ChromePdfRenderer.RenderUrlAsPdf(uri);
// save resulting pdf into file
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdf.Pdf"));
' uri of the page to turn into pdf
Dim uri As New Uri("http://www.google.com/ncr")
' turn page into pdf
pdf = ChromePdfRenderer.RenderUrlAsPdf(uri)
' save resulting pdf into file
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdf.Pdf"))
VB   C#

And that is it! The corresponding results are:

Create PDF in C# from HTML File, Figure 1: The result of converting HTML into PDF The result of converting HTML into PDF**

Create PDF in C# from HTML File, Figure 2: The result of converting a web page into a PDF The result of converting a web page into a PDF

Please find the code sample under IronPDFDemo.HelloWorld project.

Step 3: RenderHtmlAsPdf

Example 1

To assess a more real-life example, imagine an HTML Invoice that needs to be turned into a PDF. Here is the code on how to do that.

Note: You can find invoice html under IronPDFDemo.DemoWebSite project (~/Static/TestInvoice1.html). Please note that the invoice has custom CSS for the "print" media type.

The source invoice looks like this in the browser:

Create PDF in C# from HTML File, Figure 4:


To turn this into a PDF file, the codes similar to the HelloWorld example above are used, the difference being the source HTML file.

// read html from file
var html = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "TestInvoice1.html"));
var ChromePdfRenderer = new ChromePdfRenderer();
using var pdf = ChromePdfRenderer.RenderHtmlAsPdf(html);
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "ChromePdfRendererExample1.Pdf"));
// read html from file
var html = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "TestInvoice1.html"));
var ChromePdfRenderer = new ChromePdfRenderer();
using var pdf = ChromePdfRenderer.RenderHtmlAsPdf(html);
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "ChromePdfRendererExample1.Pdf"));
' read html from file
Dim html = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "TestInvoice1.html"))
Dim ChromePdfRenderer As New ChromePdfRenderer()
Dim pdf = ChromePdfRenderer.RenderHtmlAsPdf(html)
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "ChromePdfRendererExample1.Pdf"))
VB   C#

Result is:

Create PDF in C# from HTML File, Figure 5: Generate a PDF file from HTML Generate a PDF file from HTML

Looks great! Please find the code sample under IronPDFDemo.RenderHtmlAdPdfDemo project.

Also view this question on How to use HTML documents or Strings with Byte Arrays in IronPDF

Example 2

This section will help customize the resulting PDF from Example 1. For example, it will add custom margins, a header with a document title, a footer with a creation date & page numbers, and some custom CSS for the "print" media type that a standard invoice has. To do this, an instance of ChromePdfRenderOptions is initialized and passed into the ChromePdfRenderer constructor.

var pdfRenderingOptions= new ChromePdfRenderOptions()
{
    MarginTop = 50,
    MarginBottom = 50,
    TextHeader = new TextHeaderFooter()
    {
        CenterText = "{pdf-title}",
        DrawDividerLine = true,
        FontSize = 16
    },
    TextFooter = new TextHeaderFooter()
    {
        LeftText = "{date} {time}",
        RightText = "Page {page} of {total-pages}",
        DrawDividerLine = true,
        FontSize = 14
    },
    CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
};
var chromePdfRenderer = new ChromePdfRenderer(pdfRenderingOptions);
var pdfRenderingOptions= new ChromePdfRenderOptions()
{
    MarginTop = 50,
    MarginBottom = 50,
    TextHeader = new TextHeaderFooter()
    {
        CenterText = "{pdf-title}",
        DrawDividerLine = true,
        FontSize = 16
    },
    TextFooter = new TextHeaderFooter()
    {
        LeftText = "{date} {time}",
        RightText = "Page {page} of {total-pages}",
        DrawDividerLine = true,
        FontSize = 14
    },
    CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
};
var chromePdfRenderer = new ChromePdfRenderer(pdfRenderingOptions);
Dim pdfRenderingOptions= New ChromePdfRenderOptions() With {
	.MarginTop = 50,
	.MarginBottom = 50,
	.TextHeader = New TextHeaderFooter() With {
		.CenterText = "{pdf-title}",
		.DrawDividerLine = True,
		.FontSize = 16
	},
	.TextFooter = New TextHeaderFooter() With {
		.LeftText = "{date} {time}",
		.RightText = "Page {page} of {total-pages}",
		.DrawDividerLine = True,
		.FontSize = 14
	},
	.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
}
Dim chromePdfRenderer As New ChromePdfRenderer(pdfRenderingOptions)
VB   C#

Tip: Instead of passing options as a parameter in the constructor, you can set the corresponding field for a ChromePdfRenderer instance:

var chromePdfRenderer = new ChromePdfRenderer();
chromePdfRenderer.RenderingOptions = pdfRenderingOptions;
var chromePdfRenderer = new ChromePdfRenderer();
chromePdfRenderer.RenderingOptions = pdfRenderingOptions;
Dim chromePdfRenderer As New ChromePdfRenderer()
chromePdfRenderer.RenderingOptions = pdfRenderingOptions
VB   C#

Note: Header and footer features merge functionality, meaning that all the merge fields ({page}, {total-pages}, {url}, {date}, {time}, {html-title}, {pdf-title}) can be populated with corresponding data.

The rest of the code is the same as Example 1. Result is:

Create PDF in C# from HTML File, Figure 6: Generate an invoice with header and footer Generate an invoice with header and footer

Custom margins, headers, footers, and CSS for "print" media type are now in place. Please find the code sample under IronPDFDemo.RenderHtmlAdPdfDemo project. More settings can be found in the IronPDF API reference.

Step 4: RenderUrlAsPdf

Set up

To run samples from this section you need to host the IronPDFDemo.DemoWebSite locally. To do that in IIS Express:

  1. Navigate to DemoWebSite
  2. Right-click > Set as StartUp Project
  3. Start without debugging (Ctrl+F5)
  4. Navigate to your {baseurl}/Static/TestInvoice1.html to make sure it is working. This is the URL http://localhost:51169/Static/TestInvoice1.html (will be the same for you if you do not change corresponding project settings).

Example 1

In this section, the hosted DemoWebSite invoice is converted into a PDF using the same code as the HelloWorld example. The difference lies in the hosted URL:

var uri = new Uri("http://localhost:51169/Static/TestInvoice1.html");
var urlToPdf = new ChromePdfRenderer();
using var pdf = urlToPdf.RenderUrlAsPdf(uri);
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdfExample1.Pdf"));
var uri = new Uri("http://localhost:51169/Static/TestInvoice1.html");
var urlToPdf = new ChromePdfRenderer();
using var pdf = urlToPdf.RenderUrlAsPdf(uri);
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdfExample1.Pdf"));
Dim uri As New Uri("http://localhost:51169/Static/TestInvoice1.html")
Dim urlToPdf = New ChromePdfRenderer()
Dim pdf = urlToPdf.RenderUrlAsPdf(uri)
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdfExample1.Pdf"))
VB   C#

Result is:

Create PDF in C# from HTML File, Figure 7: Generate a hosted website into PDF Generate a hosted website into a PDF

This is great and it looks as expected. Please find the code sample inside IronPDFDemo.RenderUrlAsPdfDemo project.

Example 2

Many websites are often protected by an authentication method. This section uses a provided username and password during the process of rendering a PDF file with some customization: custom margins, a header with the document title, a footer with the creation date and pages, and custom CSS for the "print" media type. The URL for the invoice is at http://localhost:51169/Invoice.

Accessing http://localhost:51169/Invoice results in the "Authentication required" form:

Create PDF in C# from HTML File, Figure 8: Authentication required form Authentication required form

Note: Credentials are "testUser"/"testPassword".

So how to bypass authentication? By setting HttpLoginCredentials:

var uri = new Uri("http://localhost:51169/Invoice");
var urlToPdf = new ChromePdfRenderer
{
    PrintOptions = new ChromePdfRenderer()
    {
        MarginTop = 50,
        MarginBottom = 50,
        TextHeader = new TextHeaderFooter()
        {
            CenterText = "{pdf-title}",
            DrawDividerLine = true,
            FontSize = 16
        },
        TextFooter = new TextHeaderFooter()
        {
            LeftText = "{date} {time}",
            RightText = "Page {page} of {total-pages}",
            DrawDividerLine = true,
            FontSize = 14
        },
        CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
    },
    // setting login credentials to bypass basic authentication
    LoginCredentials = new HttpLoginCredentials()
    {
        NetworkUsername = "testUser",
        NetworkPassword = "testPassword"
    }
};
using var pdf = urlToPdf.RenderUrlAsPdf(uri);
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdfExample2.Pdf"));
var uri = new Uri("http://localhost:51169/Invoice");
var urlToPdf = new ChromePdfRenderer
{
    PrintOptions = new ChromePdfRenderer()
    {
        MarginTop = 50,
        MarginBottom = 50,
        TextHeader = new TextHeaderFooter()
        {
            CenterText = "{pdf-title}",
            DrawDividerLine = true,
            FontSize = 16
        },
        TextFooter = new TextHeaderFooter()
        {
            LeftText = "{date} {time}",
            RightText = "Page {page} of {total-pages}",
            DrawDividerLine = true,
            FontSize = 14
        },
        CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
    },
    // setting login credentials to bypass basic authentication
    LoginCredentials = new HttpLoginCredentials()
    {
        NetworkUsername = "testUser",
        NetworkPassword = "testPassword"
    }
};
using var pdf = urlToPdf.RenderUrlAsPdf(uri);
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdfExample2.Pdf"));
Dim uri As New Uri("http://localhost:51169/Invoice")
Dim urlToPdf = New ChromePdfRenderer With {
	.PrintOptions = New ChromePdfRenderer() With {
		.MarginTop = 50,
		.MarginBottom = 50,
		.TextHeader = New TextHeaderFooter() With {
			.CenterText = "{pdf-title}",
			.DrawDividerLine = True,
			.FontSize = 16
		},
		.TextFooter = New TextHeaderFooter() With {
			.LeftText = "{date} {time}",
			.RightText = "Page {page} of {total-pages}",
			.DrawDividerLine = True,
			.FontSize = 14
		},
		.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
	},
	.LoginCredentials = New HttpLoginCredentials() With {
		.NetworkUsername = "testUser",
		.NetworkPassword = "testPassword"
	}
}
Dim pdf = urlToPdf.RenderUrlAsPdf(uri)
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdfExample2.Pdf"))
VB   C#

Note: The same customization is used as for the ChromePdfRenderer Example2.

Result is:

Create PDF in C# from HTML File, Figure 9: Generate an HTML site with credentials to a PDF file Generate an HTML site with credentials to a PDF file

Everything is in place. Please find a code sample under IronPDFDemo.RenderUrlAsPdfDemo project. If you are wondering how the result would look without HttpLoginCredentials, here you are:

Create PDF in C# from HTML File, Figure 10: Generate an empty PDF file without credentials Generate an empty PDF file without credentials

Also see Jean's .NET HTML to PDF Tutorial

Additionally, IronPDF can also interact with PDF in different ways:

< PREVIOUS
Generating PDF Files in C#
NEXT >
How to view PDF files in ASP.NET using C# and IronPDF

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >