How to Create a PDF with C#?

IronPDF converts HTML to PDF documents programmatically.

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.

5

The following tutorial will walk you though the process of creating and generating a PDF using IronPDF. 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 htmlToPdf = new HtmlToPdf();  // new instance of HtmlToPdf
Dim htmlToPdf As var = New HtmlToPdf
' new instance of HtmlToPdf
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

var pdf = htmlToPdf.RenderHtmlAsPdf(html);

// save resulting pdf into file

pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "HtmlToPdf.Pdf"));  
Dim html As var = "<h1>Hello World!</h1><br><p>This is IronPdf.</p>"
Dim pdf As var = htmlToPdf.RenderHtmlAsPdf(html)
' save resulting pdf into file
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory, "HtmlToPdf.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 = htmlToPdf.RenderUrlAsPdf(uri);

// save resulting pdf into file

pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdf.Pdf"));
Dim uri As var = New Uri("http://www.google.com/ncr")
' turn page into pdf
pdf = htmlToPdf.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 htmlToPdf = new HtmlToPdf();

var pdf = htmlToPdf.RenderHtmlAsPdf(html);

pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "HtmlToPdfExample1.Pdf"));
Dim html As var = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory, "TestInvoice1.html"))
Dim htmlToPdf As var = New HtmlToPdf
Dim pdf As var = htmlToPdf.RenderHtmlAsPdf(html)
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory, "HtmlToPdfExample1.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 PdfPrintOptions that we pass into the HtmlToPdf constructor.


var pdfPrintOptions= new PdfPrintOptions()

{

    MarginTop = 50,

    MarginBottom = 50,

    Header = new SimpleHeaderFooter()

    {

        CenterText = "{pdf-title}",

        DrawDividerLine = true,

        FontSize = 16

    },

    Footer = new SimpleHeaderFooter()

    {

        LeftText = "{date} {time}",

        RightText = "Page {page} of {total-pages}",

        DrawDividerLine = true,

        FontSize = 14

    },

    CssMediaType = PdfPrintOptions.PdfCssMediaType.Print

};

var htmlToPdf = new HtmlToPdf(pdfPrintOptions);
Dim pdfPrintOptions As var = New PdfPrintOptions
Dim htmlToPdf As var = New HtmlToPdf(pdfPrintOptions)
VB   C#

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


var htmlToPdf = new HtmlToPdf();

htmlToPdf.PrintOptions = pdfPrintOptions;
Dim htmlToPdf As var = New HtmlToPdf
htmlToPdf.PrintOptions = pdfPrintOptions
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 object 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 HtmlToPdf();

var pdf = urlToPdf.RenderUrlAsPdf(uri);

pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdfExample1.Pdf"));
Dim uri As var = New Uri("http://localhost:51169/Static/TestInvoice1.html")
Dim urlToPdf As var = New HtmlToPdf
Dim pdf As var = 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 HtmlToPdf

{

    PrintOptions = new PdfPrintOptions()

    {

        MarginTop = 50,

        MarginBottom = 50,

        Header = new SimpleHeaderFooter()

        {

            CenterText = "{pdf-title}",

            DrawDividerLine = true,

            FontSize = 16

        },

        Footer = new SimpleHeaderFooter()

        {

            LeftText = "{date} {time}",

            RightText = "Page {page} of {total-pages}",

            DrawDividerLine = true,

            FontSize = 14

        },

        CssMediaType = PdfPrintOptions.PdfCssMediaType.Print

    },

    // setting login credentials to bypass basic authentication

    LoginCredentials = new HttpLoginCredentials()

    {

        NetworkUsername = "testUser",

        NetworkPassword = "testPassword"

    }

};

var pdf = urlToPdf.RenderUrlAsPdf(uri);

pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdfExample2.Pdf"));
Dim uri As var = New Uri("http://localhost:51169/Invoice")
Dim urlToPdf As var = New HtmlToPdf() {PrintOptions=newPdfPrintOptions(Unknown{MarginTop=50,MarginBottom=50,Header=newSimpleHeaderFooter(Unknown{CenterText={pdf-title},DrawDividerLine=true,FontSize=16Unknown,Footer=newSimpleHeaderFooter(Unknown{LeftText={date} {time},RightText=Page {page} of {total-pages},DrawDividerLine=true,FontSize=14Unknown,CssMediaType=PdfPrintOptions.PdfCssMediaType.PrintUnknown, LoginCredentials=newHttpLoginCredentials(Unknown{NetworkUsername=testUser,NetworkPassword=testPasswordUnknown}
Dim pdf As var = urlToPdf.RenderUrlAsPdf(uri)
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory, "UrlToPdfExample2.Pdf"))
VB   C#

Note: We are using the same customization as for the HtmlToPdf 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