Create PDF in C# from HTML File
Published: 2022-01-24 03:25:56

---
canonical_url: https://ironpdf.com/docs/questions/csharp-html-to-pdf-example-file-and-code/
---

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](https://ironpdf.com/downloads/faq/ChromePdfRendererExample.Pdf).

The source code for this entire article is available for C# as a [C# HTML to PDF Project Source Code Download](https://ironpdf.com/downloads/faq/IronPdfDemo.zip).

The following tutorial will walk you though the process of using IronPDF as a [PDF Generator C#](https://ironpdf.com/use-case/pdf-generator-csharp/). 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](https://ironsoftware.com/contact-us/).

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](https://www.nuget.org/packages/IronPdf/).

Or you can use [direct link to download the library](https://ironpdf.com/packages/IronPdf.zip).

### 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.

**C#:**
```
var ChromePdfRenderer = new ChromePdfRenderer();  // new instance of ChromePdfRenderer
```

**VB:**
```
Dim ChromePdfRenderer As New ChromePdfRenderer() ' new instance of ChromePdfRenderer
```

then if you need to turn HTML into PDF

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

**VB:**
```
' 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"))
```

or if you want to turn web page into pdf

**C#:**
```
// 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"));
```

**VB:**
```
' 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"))
```

and that is it!

Corresponding results are:

![Hello World](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tgvko0ku4la8nu4wl046.png)

![Google Homepage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ebvvmepv2qzwxx5822xo.png)

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:

![Some company invoice](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d1lig9cellh5nas1icgn.png)

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:

**C#:**
```
// read html from file
var html = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "TestInvoice1.html"));
var ChromePdfRenderer = new ChromePdfRenderer();
var pdf = ChromePdfRenderer.RenderHtmlAsPdf(html);
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "ChromePdfRendererExample1.Pdf"));
```

**VB:**
```
' 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"))
```

Result is:

![End result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pvityfryci11tkt0ndbq.png)

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](https://ironpdf.com/docs/questions/asp-net-mvc-pdf-binary/)

**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 ChromePdfRenderer constructor.

**C#:**
```
var pdfPrintOptions= 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(pdfPrintOptions);
```

**VB:**
```
Dim pdfPrintOptions= 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(pdfPrintOptions)
```

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

**C#:**
```
var ChromePdfRenderer = new ChromePdfRenderer();
ChromePdfRenderer.RenderingOptions = pdfPrintOptions;
```

**VB:**
```
Dim ChromePdfRenderer As New ChromePdfRenderer()
ChromePdfRenderer.RenderingOptions = pdfPrintOptions
```

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:

![Test Invoice #101](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kj5nplz7ffoki7s2j5ye.png)

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](https://ironpdf.com/object-reference/api/IronPdf.PdfDocument.html).

### 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 the HelloWorld example, the difference is that we are using a different url: 

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

**VB:**
```
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"))
```

Result is:

![Just another company invoice](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v59k3jdmh92n38ks7fjf.png)

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 out invoice hidden behind some basic user authentication. We need to turn it into a 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:

![Authentication required](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zsy8z4fcevu0i8ow8v4g.png)

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

So how can we bypass authentication? By setting out HttpLoginCredentials:

**C#:**
```
var uri = new Uri("http://localhost:51169/Invoice");
var urlToPdf = new ChromePdfRenderer
{
    PrintOptions = new PdfPrintOptions()
    {
        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"
    }
};
var pdf = urlToPdf.RenderUrlAsPdf(uri);
pdf.SaveAs(Path.Combine(Directory.GetCurrentDirectory(), "UrlToPdfExample2.Pdf"));
```

**VB:**
```
Dim uri As New Uri("http://localhost:51169/Invoice")
Dim urlToPdf = New ChromePdfRenderer With {
	.PrintOptions = New PdfPrintOptions() 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"))
```

**Note: We are using the same customization as for the ChromePdfRenderer Example2.**

Result is:

![Invoice Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wgt8zc65h9iuaooav7wh.png)

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:

![Blank page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/13k424mehcpn61yui7rc.png)

Also see Jean's [.Net HTML to PDF Tutorial](https://ironpdf.com/tutorials/html-to-pdf/)