Create PDF in C# from HTML File

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.

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 though the process of using IronPDF as a PDF Generator C#. It covers the basics as well as many advanced C# PDF topics.

HTML to PDF Walkthrough

This demo walks you through examples on how to use IronPdf. Please feel free to request any additional use case demos.

Demo consists of Hello World, RenderHtmlAsPdf and RenderUrlAsPdf examples. All the examples could be found under corresponding projects under IronPDFDemo solution.

Step 1: Installation

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

Or you can use direct link to download the library.

Step 2: Hello World

Once you have IronPDF installed and referenced in you 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 web page into 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

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!

Corresponding results are:

1

2

Please find the code sample under IronPDFDemo.HelloWorld project.

Step 3: RenderHtmlAsPdf

Example 1

Let us now get into more real life examples. Let us imagine that we have an Invoice in the form of html that we need to turn into pdf. Here is how we do that.

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

The source invoice looks like this in browser:

4

To turn this into a pdf , we are using almost the same code as our HelloWorld example above, the difference being that we are reading html from 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:

5

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

Now let us imagine that we need to bring some customization into the resulting pdf from Example 1. For example: add custom margins, add a header with a document title, footer with a creation date & pages, and add some custom css for "print" media type that our invoice has. To do this we specify an instance of ChromePdfRenderer that we pass 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 for 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 mail 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:

6

Custom margins, headers, footers, custom css for "print" media type are now in place. Please find the code sample under IronPDFDemo.RenderHtmlAdPdfDemo project. More settings can be found here 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. In our case url this is http://localhost:51169/Static/TestInvoice1.html (will be the same for you if you do not change corresponding project settings).

Example 1

Now let us imagine that we need to turn our hosted DemoWebSite invoice into a pdf. To do that we are using almost the same code as for HelloWorld example, the difference is that we are using a different 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:

7

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

Example 2

Now let us imagine that we have our invoice hidden behind some basic user authentication. We need to turn it into pdf with some customization: custom margins, header with document title, footer with creation date and pages, and custom css for "print" media type. The url for the invoice is at http://localhost:51169/Invoice.

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

8

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

So how can we bypass authentication? By setting our 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: We are using the same customization as for the ChromePdfRenderer Example2.

Result is:

9

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:

10

Also see Jean's .NET HTML to PDF Tutorial