HTML to PDF C# Conversion
Published: 2021-11-22 06:24:22

---
canonical_url: https://ironpdf.com/tutorials/html-to-pdf/
---

This C\# PDF tutorial will teach you how to build an HTML to PDF converter in C\# applications and websites. We will build a C\# html-to-pdf converter. The output PDF documents from IronPDF are pixel identical to the PDF functionality in the Google Chrome web browser.

With C\# we will:
<ul>
  <li>Create a PDF document using HTML as the 'content' for the PDF from within a C# application</li>
  <li>Apply editing and PDF generation functionality in C#</li>
</ul>

<hr class="separator"></hr>

<h4 class="tutorial-segment-title">Overview</h4>

## How to Code an HTML to PDF Converter in C#

<ol>
  <li>Download the HTML to PDF C# library</li>
  <li>Create PDF from a HTML String in .NET C#</li>
  <li>Export PDF from existing HTML URL</li>
  <li>Add headers, footers and apply HTML templating</li>
  <li>Attach a cover page a watermark to front or back</li>
</ol>

## Convert HTML to PDF in VB.NET and C# with IronPDF

Creating PDF files programmatically in .NET can be a frustrating task. The PDF document file format was designed more for printers than for developers. Also, C\# doesn't have many suitable libraries or features for PDF generation built-in.

The tool we will be using in this tutorial is <a href="https://www.ironpdf.com/" target="_blank">IronPDF, a popular C# PDF generation and editing library.</a> This library has comprehensive PDF editing and generation functionality via <em>HTML to PDF.</em> IronPDF stands out in that it supports .NET Framework , .Net Standard, .NET Core and <strong>.NET 5</strong> on Windows, Linux, Azure and MacOS.

With C\# and IronPDF, the logic to "generate PDF document" or "HTML to PDF conversion" can be straightforward. Much of the PDF document design and layout can use existing HTML assets or be delegated to web design staff.

This method of dynamic PDF generation in .Net with HTML5 works equally well in console applications, windows forms applications, WPF, as well as websites and MVC. IronPDF is compatible with any .Net Framework project from Version 4 upwards, .Net Core from version 2 upwards.

### VB.NET: Convert HTML to PDF

<a href="https://ironpdf.com/" taget="_blank">IronPDF</a> is a C\# Library that allows developers to create PDF documents easily in C\#, F\#, and VB.Net for .NET Core and .NET Framework. This ensures that we, as .NET coders, do not need to learn proprietary file formats or new APIs. We can easily output dynamic PDF files from our programs and web applications.

### IronPDF Features:
<ul>
  <li>Html to PDF document conversion with a perfect Google Chrome rendering engine which is always kept up to date</li>
  <li>Human support directly from our .NET development team</li>
  <li>Works with the documents you already have, including HTML, ASP.NET. ASPX forms, ASP.NET , ASP.NET. RazoMVC views and image files</li>
  <li>Rapid installation with Microsoft Visual Studio</li>
  <li>FREE for development. Licenses from $499</li>
</ul>

<hr class="separator"></hr>

<h4 class="tutorial-segment-title">Step 1</h4>

## 1. Download the HTML to PDF .NET Library from IronPDF FREE

### Install via NuGet

In Visual Studio, right click on your project solution explorer and select "Manage Nuget Packages...". From there simply search for IronPDF and install the latest version... click ok to any dialog boxes that come up.

This will work in any C\# .NET Framework project from Framework 4 and above, or .NET Core 2 and above. It will also work just as well in VB.Net projects.

`PM > Install-Package IronPdf`

<a href="https://www.nuget.org/packages/IronPdf" target="_blank">https://www.nuget.org/packages/IronPdf</a>

### Install via DLL

Alternatively, the IronPDF DLL can be downloaded and manually installed to the project or GAC from <a href="https://ironpdf.com/packages/IronPdf.zip" target="_blank">https://ironpdf.com/packages/IronPdf.zip</a>

Remember to add this statement to the top of any <strong>cs</strong> class file using IronPDF:

`using IronPdf;`

<hr class="separator"></hr>

<h4 class="tutorial-segment-title">How to Tutorials</h4>

## 2. Create a PDF with an HTML String in .NET C\#

<strong>How to: Convert HTML String to PDF?</strong> It is a very efficient and rewarding skill to <em>create a new PDF file in C#.</em>

We can simply use the <a href="https://ironpdf.com/object-reference/api/IronPdf.ChromePdfRenderer.html" target="_blank">ChromePdfRenderer.RenderHtmlAsPdf</a> method to turn any HTML (HTML5) string into a PDF <strong>C# HTML to PDF rendering</strong> is undertaken by a fully functional version of the Google Chromium engine, embedded within IronPDF DLL.

<strong>C#:</strong>
```cs
/**
PDF from HTML String
anchor-create-a-pdf-with-an-html-string-in-net-c
**/
// Render any HTML fragment or document to HTML
var Renderer = new IronPdf.ChromePdfRenderer();
var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
var OutputPath = "pixel-perfect.pdf";
PDF.SaveAs(OutputPath);
```

<strong>VB:</strong>
```cs
'''
'''PDF from HTML String
'''anchor-create-a-pdf-with-an-html-string-in-net-c
'''*
' Render any HTML fragment or document to HTML
Dim Renderer = New IronPdf.ChromePdfRenderer()
Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")
Dim OutputPath = "pixel-perfect.pdf"
PDF.SaveAs(OutputPath)
```
RenderHtmlAsPdf fully supports CSS, JavaScript and Images. If these assets are on a hard disk, we may wish to set the second parameter of RenderHtmlAsPdf

### IronPDF will render your HTML exactly as it appears in Chrome

##### 1.First set your global rendering engine

```
IronPdf.Installation.DefaultRenderingEngine =
IronPdf.Rendering.PdfRenderingEngine.Chrome; //Default = Chrome
```

API: <a href="https://ironpdf.com/object-reference/api/IronPdf.Rendering.PdfRenderingEngine.html#fields" target="_blank">https://ironpdf.com/object-reference/api/IronPdf.Rendering.PdfRenderingEngine.html#fields</a>

##### 2. This code example will render PDFs which are pixel perfect to the latest Chrome desktop browser

```
ChromePdfRenderer Renderer = new ChromePdfRenderer();
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
Renderer.RenderingOptions.PrintHtmlBackgrounds = false;
Renderer.RenderingOptions.CreatePdfFormsFromHtml = false;
Renderer.RenderingOptions.FitToPaper = false;
```

##### 3. To compare the result, open your HTML in the Chrome desktop web browser

Note: Export any HTML string and assets to stand alone HTML files and edit them manually, or ask a friendly web developer to help.

![Google Chrome](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5s3hhb1mj3lhybpek2cb.png)

##### 4. Open the <strong>Print Preview</strong> window (Ctrl + P on Windows)

![Print Preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2kskypuli0ylhwjw1rmw.png)

##### 5. Select the <strong>Save as PDF</strong> option

Once Print to PDF in Chrome is perfect - IronPDF will match it

<strong>BaseUrlPath</strong>

<strong>C#:</strong>
```cs
    var PDF = Renderer.RenderHtmlAsPdf("<img src='image1.png'/>", @"C:\MyProject\Assets\");
   // this will render C:\MyProject\Assets\image1.png
```

<strong>VB:</strong>
```cs
   Dim PDF = Renderer.RenderHtmlAsPdf("<img src='image1.png'/>", "C:\MyProject\Assets\")
   ' this will render C:\MyProject\Assets\image1.png
```

All referenced CSS stylesheets, images and JavaScript files will be relative to the BaseUrlPath and can be kept in a neat and logical structure. You may also, of course opt to reference images, stylesheets and assets online, including <a href ="https://ironpdf.com/docs/questions/webfonts-azure/" target="_blank">web-fonts such as Google Fonts</a> and even jQuery.

<hr class="separator"></hr>

## 3. Export a PDF Using Existing HTML URL

#### (URL to PDF)

Rendering existing URLs as PDFs with C\# is very efficient and intuitive. This also allows teams to split PDF design and back-end PDF rendering work across multiple teams.

Lets render a page from Wikipedia.com in the following example:

<strong>C#:</strong>

```cs
/**
HTML URL to PDF
anchor-export-a-pdf-using-existing-html-url
**/
// Create a PDF from any existing web page
var Renderer = new IronPdf.ChromePdfRenderer();
var PDF = Renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Portable_Document_Format");
PDF.SaveAs("wikipedia.pdf");
```

<strong>VB:</strong>
```cs
'''
'''HTML URL to PDF
'''anchor-export-a-pdf-using-existing-html-url
'''*
' Create a PDF from any existing web page
Dim Renderer = New IronPdf.ChromePdfRenderer()
Dim PDF = Renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Portable_Document_Format")
PDF.SaveAs("wikipedia.pdf")
```

You will notice that hyperlinks and even HTML forms are preserved within the PDF generated by our C\# code.

When rendering existing web pages we have some tricks we may wish to apply:

### 3.1 Print and Screen CSS

In modern CSS3 we have CSS directives for both print and screen. We can instruct IronPDF to render "Print" CSSs which are often simplified or overlooked. By default "Screen" CSS styles will be rendered, which <a href="https://ironpdf.com/" target="_blank">IronPDF</a> users have found most intuitive.

<strong>C#:</strong>

```cs
/**
Print and Screen CSS
anchor-print-and-screen-css
**/
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen;
//or
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
```

<strong>VB:</strong>

```cs
'''
'''Print and Screen CSS
'''anchor-print-and-screen-css
'''*
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Screen
'or
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
```

### 3.2 JavaScript

IronPDF supports JavaScript, jQuery and even AJAX. We may need to instruct <a href="https://ironpdf.com/docs/questions/javascript-to-pdf/" target="_blank">IronPDF to <strong>wait</strong> for JS or AJAX</a> to finish running before rendering a snapshot of our web-page.

<strong>C\#:</strong>
```cs
/**
PDF with Javascript
anchor-javascript
**/
Renderer.RenderingOptions.EnableJavaScript = true;
Renderer.RenderingOptions.RenderDelay = 500; //milliseconds
```

<strong>VB:</strong>
```cs
'''
'''PDF with Javascript
'''anchor-javascript
'''*
Renderer.RenderingOptions.EnableJavaScript = True
Renderer.RenderingOptions.RenderDelay = 500 'milliseconds
```

We can demonstrate compliance with the JavaScript standard by rendering an advanced <a href="https://bl.ocks.org/mbostock/4062006" target="_blank" rel="nofollow">d3.js JavaScript chord chart</a> from a csv dataset like this:

<strong>C\#:</strong>

```cs
// Create a PDF Chart a live rendered dataset using d3.js and javascript
var Renderer = new ChromePdfRenderer();
var PDF = Renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006");
PDF.SaveAs("chart.pdf");
```

<strong>VB:</strong>

```cs
' Create a PDF Chart a live rendered dataset using d3.js and javascript
Dim Renderer = New ChromePdfRenderer()
Dim PDF = Renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006")
PDF.SaveAs("chart.pdf")
```

### 3.3 Responsive CSS

Html to PDF using response CSS in .NET! <a href="https://ironpdf.com/docs/questions/html-to-pdf-responsive-css/" target="_blank">Resonsive web pages</a> are designed to be viewed in a browser. IronPDF does not open a real browser window within your server's OS. This can lead to responsive elements rendering at their smallest size.

We recommend using <strong>Print</strong> CSS media types to navigate this issue. Print CSS should not normally be responsive.

<strong>C\#:</strong>

```cs
/**
Responsive CSS
anchor-responsive-css
**/
Renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
```

<strong>VB:</strong>

```cs
'''
'''Responsive CSS
'''anchor-responsive-css
'''*
Renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
```

## 4. How To: Generate PDF From Existing HTML Page(s)

We can also render any HTML page to PDF on our hard disk. All relative assets such as CSS, images and js will be rendered as if the file had been opened using the <strong>file://</strong> protocol.

<strong>C#:</strong>
```cs
/**
PDF from Existing HTML
anchor-generate-a-pdf-from-an-existing-html-file
**/
// Create a PDF from an existing HTML using C#
 var Renderer = new IronPdf.ChromePdfRenderer();
 var PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html");
 var OutputPath = "Invoice.pdf";
 PDF.SaveAs(OutputPath);
```

<strong>VB:</strong>
```cs
'''
'''PDF from Existing HTML
'''anchor-generate-a-pdf-from-an-existing-html-file
'''*
' Create a PDF from an existing HTML using C#
 Dim Renderer = New IronPdf.ChromePdfRenderer()
 Dim PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html")
 Dim OutputPath = "Invoice.pdf"
 PDF.SaveAs(OutputPath)
```

This method has the advantage of allowing the developer the opportunity to test the HTML content in a browser during development. We recommend Chrome as it is the web browser on which IronPDF's rendering engine is based.

To convert <a href="https://ironpdf.com/docs/questions/xml-to-pdf/" target="_blank">XML to PDF you can use XSLT templating to print your XML content to PDF.</a>

<hr class="separator"></hr>

## 5. Add Headers And Footers

Headers and footers can be added to PDFs when they are rendered, or to existing PDF files using IronPDF.

With IronPDF, headers and footers can contain simple text-based content using the <em>SimpleHeaderFooter</em> class - or with images and rich HTML content using the <em>HtmlHeaderFooter</em> class.

<strong>C#:</strong>
```cs
/**
Add Headers and Footers
anchor-add-headers-and-footers
**/
// Create a PDF from an existing HTML
var Renderer = new IronPdf.ChromePdfRenderer();
Renderer.RenderingOptions.MarginTop = 50;  //millimeters
Renderer.RenderingOptions.MarginBottom = 50;
Renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
Renderer.RenderingOptions.TextHeader = new TextHeaderFooter()
{
    CenterText = "{pdf-title}",
    DrawDividerLine = true,
    FontSize = 16
};
Renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
{
    LeftText = "{date} {time}",
    RightText = "Page {page} of {total-pages}",
    DrawDividerLine = true,
    FontSize = 14
};
var PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html");
var OutputPath = "Invoice.pdf";
PDF.SaveAs(OutputPath);
// This neat trick opens our PDF file so we can see the result
System.Diagnostics.Process.Start(OutputPath);
```

<strong>VB:</strong>
```cs
'''
'''Add Headers and Footers
'''anchor-add-headers-and-footers
'''*
' Create a PDF from an existing HTML
Dim Renderer = New IronPdf.ChromePdfRenderer()
Renderer.RenderingOptions.MarginTop = 50 'millimeters
Renderer.RenderingOptions.MarginBottom = 50
Renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
Renderer.RenderingOptions.TextHeader = New TextHeaderFooter() With {
	.CenterText = "{pdf-title}",
	.DrawDividerLine = True,
	.FontSize = 16
}
Renderer.RenderingOptions.TextFooter = New TextHeaderFooter() With {
	.LeftText = "{date} {time}",
	.RightText = "Page {page} of {total-pages}",
	.DrawDividerLine = True,
	.FontSize = 14
}
Dim PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html")
Dim OutputPath = "Invoice.pdf"
PDF.SaveAs(OutputPath)
' This neat trick opens our PDF file so we can see the result
System.Diagnostics.Process.Start(OutputPath)
```

<strong>C#:</strong>
```cs
Renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
{
    LeftText = "{date} {time}",
    RightText = "Page {page} of {total-pages}",
    DrawDividerLine = true,
    FontSize = 14
};
```

<strong>VB:</strong>
```cs
Renderer.RenderingOptions.TextFooter = New TextHeaderFooter() With {
	.LeftText = "{date} {time}",
	.RightText = "Page {page} of {total-pages}",
	.DrawDividerLine = True,
	.FontSize = 14
}
```
### 5.1 HTML Headers and Footers

The HtmlHeaderFooter class allows for rich headers and footers to be generated using HTML5 content which may even include images, stylesheets and hyperlinks.

<strong>C#:</strong>
```cs
Renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter() 
{ HtmlFragment = "<div style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>" };
```

<strong>VB:</strong>
```cs
Renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {.HtmlFragment = "<div style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>"}
```

### 5.2 Dynamic Data in PDF Headers and Footers

We may "mail-merge" content into the text and even HTML of headers and footers using placeholders such as:

<ul>
  <li>{page} for the current page number</li>
  <li>{total-pages} for the total number of pages in the PDF</li>
  <li>{url} for the URL of the rendered PDF if rendered from a web page</li>
  <li>{date} for today's date</li>
  <li>{time} for the current time</li>
  <li>{html-title} for the title attribute of the rendered HTML document</li>
  <li>{pdf-title} for the document title, which may be set via the PrintOptions</li>
</ul>

<hr class="separator"></hr>

## 6. C# HTML to PDF Conversion Settings

There are many nuances to how our users and clients may expect PDF content to be rendered.
The ChromePdfRenderer class contains a <strong>PrintOptions</strong> object which can be used to set these options.

For example we may wish to choose to only accept "print" style CSS3 directives: 

<strong>C#:</strong>
```cs
/**
Print Style CSS
anchor-c-html-to-pdf-settings
**/
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
```

<strong>VB:</strong>
```cs
'''
'''Print Style CSS
'''anchor-c-html-to-pdf-settings
'''*
Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
```

We may also wish to change the size of our print margins to create more whitespace on the page, to make room for large headers or footers, or even set zero margins for commercial printing of brochures or posters:

<strong>C#:</strong>
```cs
/**
Print Margins Size
anchor-c-html-to-pdf-settings
**/
Renderer.RenderingOptions.MarginTop = 50;  //millimeters
Renderer.RenderingOptions.MarginBottom = 50;
```

<strong>VB:</strong>
```cs
'''
'''Print Margins Size
'''anchor-c-html-to-pdf-settings
'''*
Renderer.RenderingOptions.MarginTop = 50 'millimeters
Renderer.RenderingOptions.MarginBottom = 50
```

We may wish to turn on or off background images from html elements:

<strong>C#:</strong>
```cs
/**
Print Background Images
anchor-c-html-to-pdf-settings
**/
Renderer.RenderingOptions.PrintHtmlBackgrounds = true;
```

<strong>VB:</strong>
```cs
'''
'''Print Background Images
'''anchor-c-html-to-pdf-settings
'''*
Renderer.RenderingOptions.PrintHtmlBackgrounds = True
```

It is also possible to set our output PDFs to be rendered on any virtual paper size - including portrait and landscape sizes and even custom sizes which may be set in millimeters or inches.

<strong>C#:</strong>
```cs
/**
Print Paper Size
anchor-c-html-to-pdf-settings
**/
Renderer.RenderingOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4;
Renderer.RenderingOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Landscape;
```

<strong>VB:</strong>
```cs
'''
'''Print Paper Size
'''anchor-c-html-to-pdf-settings
'''*
Renderer.RenderingOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4
Renderer.RenderingOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Landscape
```

Full documentation of the HTML <a href="https://ironpdf.com/use-case/csharp-pdf-creator/">C# PDF Creator</a> Settings may be found at <a href="https://ironpdf.com/object-reference/api/IronPdf.PdfPrintOptions.html" target="_blank">https://ironpdf.com/object-reference/api/IronPdf.PdfPrintOptions.html</a> 

The full set of PDF PrintOptions includes:

<ul>
  <li><strong>CreatePdfFormsFromHtml</strong> Turns all HTML forms elements into editable PDF forms.</li>
  <li><strong>CssMediaType</strong> Enables Media="screen" or "print" CSS Styles and StyleSheets.</li>
  <li><strong>CustomCssUrl</strong> Allows a custom CSS style-sheet to be applied to Html before rendering. May be a local file path, or a remote url.</li>
  <li><strong>DPI</strong> Printing output DPI. 300 is standard for most print jobs. Higher resolutions produce clearer images and text, but also larger PDF files.</li>
  <li><strong>EnableJavaScript</strong> Enables JavaScript and Json to be executed before the page is rendered. Ideal for printing from Ajax / Angular Applications. Also see RenderDelay.</li>
  <li><strong>FirstPageNumber</strong> First page number to be used in PDF headers and footers.</li>
  <li><strong>FitToPaper</strong> Where possible, zooms the PDF content to 1 page width.</li>
  <li><strong>TextFooter</strong> Sets the header content for every PDF page as a String. Supports 'mail-merge'</li>
  <li><strong>TextHeader</strong> Sets the footer content for every PDF page as a String. Supports 'mail-merge'
</li>
  <li><strong>HtmlFooter</strong> Sets the header content for every PDF page as Html</li>
  <li><strong>HtmlHeader</strong> Sets the footer content for every PDF page as Html</li>
  <li><strong>MarginBottom</strong> Paper margin in millimeters. Set to zero for border-less and commercial printing applications</li>
  <li><strong>MarginLeft</strong> Paper margin in millimeters</li>
  <li><strong>MarginRight</strong> Paper margin in millimeters</li>
  <li><strong>MarginTop</strong> Paper margin in millimeters. Set to zero for border-less and commercial printing applications</li>
  <li><strong>PaperOrientation</strong> The PDF paper orientation</li>
  <li><strong>PaperSize</strong> Set an output paper size for PDF pages. System.Drawing.Printing.PaperKind. Use SetCustomPaperSize(int width, int height) for custom sizes</li>
  <li><strong>PrintHtmlBackgrounds</strong> Prints background-colors and images from Html</li>
  <li><strong>RenderDelay</strong> Milliseconds delay to wait after Html is rendered before printing. This can use useful when considering the rendering of JavaScript, Ajax or animations</li>
  <li><strong>Title</strong> PDF Document Name and Title meta-data. Not required</li>
  <li><strong>Zoom</strong> The zoom level in %. Enlarges the rendering size of Html documents</li>
</ul>

<hr class="separator"></hr>

## 7. Apply HTML Templating

To template or "batch create" PDFs is a common requirement for Internet and website developers.

Rather than templating a PDF document itself, with IronPDF we can template our HTML using existing, well tried technologies. When the HTML template is combined with data from a query-string or database we end up with a dynamically generated PDF document.

In the simplest instance, using the C# String.Format method is effective for basic "mail-merge"

<strong>C#:</strong>
```cs
/**
HTML Templating
anchor-apply-html-templating
**/       
String.Format("<h1>Hello {0} !<h1>","World");
```

<strong>VB:</strong>
```cs
'''
'''HTML Templating
'''anchor-apply-html-templating
'''*       
String.Format("<h1>Hello {0} !<h1>","World")
```

If the Html file is longer, often we can use arbitrary placeholders such as `[[NAME]]` and replace them with real data later.

The following example will create 3 PDFs, each personalized to a user.

<strong>C#:</strong>
```cs
var HtmlTemplate = "<p>[[NAME]]</p>";
var Names = new[] { "John", "James", "Jenny" };
foreach (var name in Names) {
    var HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);
    var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance);
    Pdf.SaveAs(name + ".pdf");
}
```

<strong>VB:</strong>
```cs
Dim HtmlTemplate = "<p>[[NAME]]</p>"
Dim Names = { "John", "James", "Jenny" }
For Each name In Names
	Dim HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name)
	Dim Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance)
	Pdf.SaveAs(name & ".pdf")
Next name
```

### 7.1 Advanced Templating With Handlebars.Net

A sophisticated method to merge C# data with HTML for PDF generation is using the Handlebars Templating standard.

Handlebars makes it possible to create dynamic html from C# objects and class instances including database records. Handlebars is particularly effective where a query may return an unknown number of rows such as in the generation of an invoice.

We must first add an additional Nuget Package to our project: <a href="https://www.nuget.org/packages/Handlebars.Net/" target="_blank">https://www.nuget.org/packages/Handlebars.Net/</a>

<strong>C#:</strong>
```cs
/**
Handlebars Templating
anchor-advanced-templating-with-handlebars-net
**/       
string source =
@"<div class=""entry"">
  <h1>{{title}}</h1>
  <div class=""body"">
    {{body}}
  </div>
</div>";
var template = Handlebars.Compile(source);
var data = new {
    title = "My new post",
    body = "This is my first post!"
};
var result = template(data);
/* Would render:
<div class="entry">
  <h1>My New Post</h1>
  <div class="body">
    This is my first post!
  </div>
</div>
*/
```

<strong>VB:</strong>
```cs
'''
'''Handlebars Templating
'''anchor-advanced-templating-with-handlebars-net
'''*       
Dim source As String = "<div class=""entry"">
  <h1>{{title}}</h1>
  <div class=""body"">
    {{body}}
  </div>
</div>"
Dim template = Handlebars.Compile(source)
Dim data = New With {
	Key .title = "My new post",
	Key .body = "This is my first post!"
}
Dim result = template(data)
' Would render:
'<div class="entry">
'  <h1>My New Post</h1>
'  <div class="body">
'    This is my first post!
'  </div>
'</div>
'
```
To render this html we can simply use the RenderHtmlAsPdf method.

<strong>C#:</strong>
```cs
IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();
Renderer.RenderHtmlAsPdf(HtmlInstance).SaveAs("Handelbars.pdf")
```

<strong>VB:</strong>
```cs
Dim Renderer As New IronPdf.ChromePdfRenderer()
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Renderer.RenderHtmlAsPdf(HtmlInstance).SaveAs("Handelbars.pdf")
```

You can learn more about the handlebars html templating standard and its C# using from <a href="https://github.com/rexm/Handlebars.Net" target="_blank" rel="nofollow">https://github.com/rexm/Handlebars.Net</a>

### 7.2 Add Page Breaks using HTML5

A common requirement in a PDF document is for pagination. Developers need to control where PDF pages start and end for a clean, readable layout.

The easiest way to do this is with a less known CSS trick which will render a page break into any printed HTML document.

<strong>HTML:</strong>
```cs
<div style='page-break-after: always;'>&nbsp;</div>
```

The provided HTML works, but is hardly best practice. We found this example to be very helpful in our understanding of a neat and tidy way to lay out multi-page html content.

```cs
/**
Add Multipage Breaks
anchor-add-page-breaks-using-html
**/   
<!DOCTYPE html>
<!--https://stackoverflow.com/questions/1630819/google-chrome-printing-page-breaks-->
<html>
  <head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <title>Paginated HTML</title>
    <style type="text/css" media="print">
      div.page
      {
        page-break-after: always;
        page-break-inside: avoid;
      }
    </style>
  </head>
  <body>
    <div class="page">
      <h1>This is Page 1</h1>
    </div>
    <div class="page">
      <h1>This is Page 2</h1>
    </div>
    <div class="page">
      <h1>This is Page 3</h1>
    </div>
  </body>
</html>
```

The FAQ outlines more <a href="https://ironpdf.com/docs/questions/html-to-pdf-page-breaks/" target="_blank">tips and tricks with Page Breaks</a>

<hr class="separator"></hr>

## 8. Attach a Cover Page to a PDF

IronPDF makes it easy to Merge pdf documents. The most common usage of this technique is to add a cover page or back page to an existing rendered PDF document.

To do so we first render a cover page, and then use the `PdfDocument.Merge` static method to combine the 2 documents.

<strong>C#:</strong>
```cs
/**
Add Cover Page
anchor-attach-a-cover-page-to-a-pdf
**/   
var PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/");
PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF).SaveAs("Combined.Pdf");
```

<strong>VB:</strong>
```cs
'''
'''Add Cover Page
'''anchor-attach-a-cover-page-to-a-pdf
'''*   
Dim PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/")
PdfDocument.Merge(New PdfDocument("CoverPage.pdf"), PDF).SaveAs("Combined.Pdf")
```

<hr class="separator"></hr>

## 9. Add a Watermark

A final <a href="https://ironpdf.com/use-case/csharp-pdf/" target="_blank">C# PDF</hr> trick is to add a watermark to PDF documents. This can be used to add a notice to each page that a document is "confidential" or a "sample".

<strong>C#:</strong>
```cs
/**
Add Watermark
anchor-add-a-watermark
**/   
// Stamps a watermark onto a new or existing PDF
IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer();
var pdf =  Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>",  IronPdf.Editing.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf");
pdf.SaveAs(@"C:\Path\To\Watermarked.pdf");
```

<strong>VB:</strong>
```cs
'''
'''Add Watermark
'''anchor-add-a-watermark
'''*   
' Stamps a watermark onto a new or existing PDF
Dim Renderer As New IronPdf.ChromePdfRenderer()
Dim pdf = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", IronPdf.Editing.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf")
pdf.SaveAs("C:\Path\To\Watermarked.pdf")
```
<hr class="separator"></hr>

## 10. Download as C# Source Code

The full <strong>free Html to PDF converter C# Source Code</strong> for this tutorial is available to download as a zipped Visual Studio 2017 project file. It will use its rendering engine to generate PDF document objects in C#.

<a href="https://ironpdf.com/tutorials/html-to-pdf/downloads/CSharp-Html-To-Pdf-Tutorial.zip" target="_blank">Download this tutorial as a Visual Studio project</a>

The free download contains everything you need to create a PDF from HTML - including working C# PDF code exmaples for:

<ol>
  <li>Convert an Html String to PDF using C#</li>
  <li>Html file to PDF in C# (supporting CSS, JavaScript and images)</li>
  <li>C# HTML to PDF using a URL ("url to pdf")</li>
  <li>C# PDF editing and settings examples</li>
  <li>Rendering JavaScript canvas charts such as d3.js to a PDF</li>
  <li>The PDF Library for C#</li>
</ol>

### Class Reference

Developers may also be interested in the IronPdf.PdfDocument Class reference:

<a href="https://ironpdf.com/object-reference/api/IronPdf.PdfDocument.html" target="_blank">https://ironpdf.com/object-reference/api/IronPdf.PdfDocument.html</a>

This object model shows how PDF documents may be:

This object model shows how PDF documents may be:

<ul>
  <li>Encrypted and password protected</li>
  <li>Edited or 'stamped' with new html content</li>
  <li>Enhanced with foreground and background images</li>
  <li>Merged, joined, truncated and spliced at a page or document level</li>
  <li>OCR processed to extract plain text and images</li>
</ul>

{% youtube cEKjADq1EyU %}

<hr class="separator"></hr>

### PDFSharp 
<strong>PDFSharp</strong> is a free open source library which allows logical editing and creation of PDF documents in .Net.

A key difference between PDFSharp and IronPDF is that IronPDF has an embedded Web Browser which allows faithful creation of PDFs from HTML, CSS, JS and images.

The IronPDF API also differs from PDFSharp in that it is based around use cases rather than the technical structure of PDF documents. Many find this more logical and intuitive to use.

It can convert html to pdf, but Html to PDF conversion is limited: including html file to PDF file.

### WKHtmlToPdf
<strong>WKHtmlToPdf</strong> is a free, open source library written in C++ which allows PDF documents to be rendered from HTML.

A key difference between WKHtmlToPdf and IronPDF is that IronPDF is written in C# and is stable and thread safe for use in .NET applications and Websites.

IronPdf also supports Css3 and html5 fully, where as WKHtmlToPdf is almost a decade out of date.

The IronPDF API also differs from WKHtmlToPdf in that it has a large and advanced API allowing PDF documents to be edited, Manipulated Imported, Exported, Signed, Secured and Watermarked.

Html to pdf conversion is stable but using a very out dated rendering engine.

### iTextSharp
iTextSharp is an open source partial port of the iText java library for PDF generation and editing. Convert Html to pdf- that is possible, but I notice its rendering was limited to what is available in Java or uses html to pdf conversion from WKHtmlToPdf under the LGPL open sourced license.

A key difference with HTML to PDF between <a href="https://ironpdf.com/use-case/csharp-itextsharp/" target="_blank">C# iTextSharp</a> and IronPDF is that IronPDF has more advanced and accurate HTML-To-PDF rendering by using an embedded Chrome based web browser rather than the legacy WKHtmlToPdf used in iText.

The IronPDF API also differs from iTextSharp in that IronPDF has explicit licenses for commercial or private usage, where as iTextSharp's AGLP license is only suitable for applications where the full source code is presented for free to every user - even users across the internet.

A full breakdown of the differences is available in our <a href="https://ironpdf.com/docs/questions/itextsharp/" target="_blank">iTextSharp C#</a> FAQ.

### Other Commercial Libraries
<em>Aspose PDF, Spire PDF, EO PDF,</em> and <em>SelectPdf</em> are competitor .Net commercial PDF libraries by other vendors. It is unfair for tutorials on this website to comment on them comparatively, as we clearly believe in the quality of IronPDF. Suffice to say: we believe IronPDF to have a comparatively strong feature set, excellent <em>.Net Core</em> compatibility and a fair price point. 

<hr class="separator"></hr>

## 12. Watch HTML to PDF Tutorial Video

{% youtube y4hbMBuxqo4 %}