For many this is the most efficient way to generate PDF files from .Net, because there is no additional API to learn, or complex design system to navigate

C#PDFHTML

17th January 2018 by Jean Ashberg

C# HTML to PDF

Rendering PDF files from HTML in C# .Net applications and websites

Creating PDF files programmatically in .Net can be a frustrating task, as the PDF document file format was designed more for printers that for for developers

In this C# PDF tutorial we will show that with C# we can create PDF documents using HTML as the 'content' for the PDF. This ensures that we, as .net coders, do not need to learn proprietary file formats or new APIs to output dynamic PDF files from our programs and web-applications.

The tool we will be using in this tutorial is IronPDF, a popular C# PDF generation and editing library.

With C# and IronPDF, creating PDF documents can be straightforward, and much of the PDF document design and layout work can use existing HTML assets or be delegated to web design staff.

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

Getting Set Up with a C# PDF Library

First we will need to download a popular C# PDF Generator (also equally viable for VB.Net, ASP.Net and F#).

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... clicking ok to any dialog boxes that come up.

This will work in any C# .Net Framework project from Framework 4 and above. It will also work just as well for VB.Net projects.

PM > Install-Package IronPdf 

https://www.nuget.org/packages/IronPdf

Alternatively, the IronPDF DLL can be downloaded and manually installed to the project or GAC from http://ironpdf.com/packages/IronPdf.zip

Remember to add this statement to the top of any cs class file which used IronPDF

  using IronPdf;

Creating a PDF from an HTML String in .NET

C# HTML String to PDF is a very efficient and rewarding way to create a new PDF file in C#.

We can simply use the HtmlToPdf.RenderHtmlAsPdf method to turn any HTML (HTML5) string into a PDF. The C# HTML to PDF rendering is undertaken by a fully functional version of Google Chromium engine which is embedded within IronPDF.dll.

// Render any HTML fragment or document to HTML
var Renderer = new IronPdf.HtmlToPdf();
var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
var OutputPath = "HtmlToPDF.pdf";
PDF.SaveAs(OutputPath);

// This neat trick opens our PDF file so we can see the result in our default PDF viewer
System.Diagnostics.Process.Start(OutputPath);
Public Shared Sub wrapper()
'WRAPR1
' Render any HTML fragment or document to HTML
Dim Renderer = New IronPdf.HtmlToPdf()
Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")
Dim OutputPath = "HtmlToPDF.pdf"
PDF.SaveAs(OutputPath)

' This neat trick opens our PDF file so we can see the result in our default PDF viewer
System.Diagnostics.Process.Start(OutputPath)
'WRAPR1
End Sub

' Render any HTML fragment or document to HTML
Dim Renderer = New IronPdf.HtmlToPdf()
Dim PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")
Dim OutputPath = "HtmlToPDF.pdf"
PDF.SaveAs(OutputPath)

' This neat trick opens our PDF file so we can see the result in our default PDF viewer
System.Diagnostics.Process.Start(OutputPath)
VB   C#

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 BaseUrlPath

 var PDF = Renderer.RenderHtmlAsPdf("<img src='image1.png'/>", @"C:\MyProject\Assets\");
// this will render C:\MyProject\Assets\image1.png
Public Shared Sub wrapper()
'WRAPR1
 Dim PDF = Renderer.RenderHtmlAsPdf("<img src='image1.png'/>", "C:\MyProject\Assets\")
' this will render C:\MyProject\Assets\image1.png
'WRAPR1
End Sub

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

All referenced 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 web-fonts such as GoogleFonts and even jQuery.

Creating a PDF from Existing HTML

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

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

// Create a PDF from any existing web page
var Renderer = new IronPdf.HtmlToPdf();
var PDF = Renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Portable_Document_Format");
PDF.SaveAs("wikipedia.pdf");

// This neat trick opens our PDF file so we can see the result
System.Diagnostics.Process.Start("wikipedia.pdf");
Public Shared Sub wrapper()
'WRAPR1
' Create a PDF from any existing web page
Dim Renderer = New IronPdf.HtmlToPdf()
Dim PDF = Renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Portable_Document_Format")
PDF.SaveAs("wikipedia.pdf")

' This neat trick opens our PDF file so we can see the result
System.Diagnostics.Process.Start("wikipedia.pdf")
'WRAPR1
End Sub

' Create a PDF from any existing web page
Dim Renderer = New IronPdf.HtmlToPdf()
Dim PDF = Renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Portable_Document_Format")
PDF.SaveAs("wikipedia.pdf")

' This neat trick opens our PDF file so we can see the result
System.Diagnostics.Process.Start("wikipedia.pdf")
VB   C#

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:

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 IronPDF users have found most intuitive.

Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
//or
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
Public Shared Sub wrapper()
'WRAPR1
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
'or
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen
'WRAPR1
End Sub

Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
'or
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen
VB   C#

Javascript IronPDF fully supports Javascript, jQuery and even AJAX. We may need to instruct IronPDF to wait for JS or ajax to finish running before rendering a snapshot of our web-page.

Renderer.PrintOptions.EnableJavaScript = true;
Renderer.PrintOptions.RenderDelay = 500; //milliseconds
Public Shared Sub wrapper()
'WRAPR1
Renderer.PrintOptions.EnableJavaScript = True
Renderer.PrintOptions.RenderDelay = 500 'milliseconds
'WRAPR1
End Sub

Renderer.PrintOptions.EnableJavaScript = True
Renderer.PrintOptions.RenderDelay = 500 'milliseconds
VB   C#

We can demonstrate full compliance with the Javascript standard by rendering an advanced d3.js Javascript chord chart from a csv dataset like this:

// Create a PDF Chart a live rendered dataset using d3.js and javascript
var Renderer = new HtmlToPdf();
var PDF = Renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006");
PDF.SaveAs("chart.pdf");
Public Shared Sub wrapper()
'WRAPR1
' Create a PDF Chart a live rendered dataset using d3.js and javascript
Dim Renderer = New HtmlToPdf()
Dim PDF = Renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006")
PDF.SaveAs("chart.pdf")
'WRAPR1
End Sub

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

Responsive CSS Responsive web pages 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 Print css media types to navigate this issue. Print CSS should not normally be responsive.

Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
Public Shared Sub wrapper()
'WRAPR1
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
'WRAPR1
End Sub

Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
VB   C#

Creating a PDF from an existing HTML file

We can also render any HTML file 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 file:// protocol.

// Create a PDF from an existing HTML using C#
 var Renderer = new IronPdf.HtmlToPdf();
 var PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html");
 var OutputPath = "Invoice.pdf";
 PDF.SaveAs(OutputPath);
Public Shared Sub wrapper()
'WRAPR1
' Create a PDF from an existing HTML using C#
 Dim Renderer = New IronPdf.HtmlToPdf()
 Dim PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html")
 Dim OutputPath = "Invoice.pdf"
 PDF.SaveAs(OutputPath)
'WRAPR1
End Sub

' Create a PDF from an existing HTML using C#
 Dim Renderer = New IronPdf.HtmlToPdf()
 Dim PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html")
 Dim OutputPath = "Invoice.pdf"
 PDF.SaveAs(OutputPath)
VB   C#

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 being the web browser on which IronPDF's rendering engine is based.

Adding Headers And Footers

Headers and footers can be added to PDFs when they are rendered, or after the fact using IronPDF.

With IronPdf, Headers and footers can contain simple text based content using the SimpleHeaderFooter class - or with images and rich html content using the HtmlHeaderFooter class.

// Create a PDF from an existing HTML
var Renderer = new IronPdf.HtmlToPdf();

Renderer.PrintOptions.MarginTop = 50;  //millimeters
Renderer.PrintOptions.MarginBottom = 50;
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;

Renderer.PrintOptions.Header = new SimpleHeaderFooter()
{
    CenterText = "{pdf-title}",
    DrawDividerLine = true,
    FontSize = 16
};

Renderer.PrintOptions.Footer = new SimpleHeaderFooter()
{
    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);
Public Shared Sub wrapper()
'WRAPR1
' Create a PDF from an existing HTML
Dim Renderer = New IronPdf.HtmlToPdf()

Renderer.PrintOptions.MarginTop = 50 'millimeters
Renderer.PrintOptions.MarginBottom = 50
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print

Renderer.PrintOptions.Header = New SimpleHeaderFooter() With {
	.CenterText = "{pdf-title}",
	.DrawDividerLine = True,
	.FontSize = 16
}

Renderer.PrintOptions.Footer = New SimpleHeaderFooter() 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)
'WRAPR1
End Sub

' Create a PDF from an existing HTML
Dim Renderer = New IronPdf.HtmlToPdf()

Renderer.PrintOptions.MarginTop = 50 'millimeters
Renderer.PrintOptions.MarginBottom = 50
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print

Renderer.PrintOptions.Header = New SimpleHeaderFooter() With {
	.CenterText = "{pdf-title}",
	.DrawDividerLine = True,
	.FontSize = 16
}

Renderer.PrintOptions.Footer = New SimpleHeaderFooter() 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)
VB   C#
Renderer.PrintOptions.Footer = new SimpleHeaderFooter()
{
    LeftText = "{date} {time}",
    RightText = "Page {page} of {total-pages}",
    DrawDividerLine = true,
    FontSize = 14
};
Public Shared Sub wrapper()
'WRAPR1
Renderer.PrintOptions.Footer = New SimpleHeaderFooter() With {
	.LeftText = "{date} {time}",
	.RightText = "Page {page} of {total-pages}",
	.DrawDividerLine = True,
	.FontSize = 14
}
'WRAPR1
End Sub

Renderer.PrintOptions.Footer = New SimpleHeaderFooter() With {
	.LeftText = "{date} {time}",
	.RightText = "Page {page} of {total-pages}",
	.DrawDividerLine = True,
	.FontSize = 14
}
VB   C#

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.

Renderer.PrintOptions.Footer = new HtmlHeaderFooter() { HtmlFragment = "<div style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>" };
Public Shared Sub wrapper()
'WRAPR1
Renderer.PrintOptions.Footer = New HtmlHeaderFooter() With {.HtmlFragment = "<div style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>"}
'WRAPR1
End Sub

Renderer.PrintOptions.Footer = New HtmlHeaderFooter() With {.HtmlFragment = "<div style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>"}
VB   C#

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:

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

C# HTML to PDF Settings

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

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

Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
Public Shared Sub wrapper()
'WRAPR1
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
'WRAPR1
End Sub

Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
VB   C#

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

Renderer.PrintOptions.MarginTop = 50;  //millimeters
Renderer.PrintOptions.MarginBottom = 50;
Public Shared Sub wrapper()
'WRAPR1
Renderer.PrintOptions.MarginTop = 50 'millimeters
Renderer.PrintOptions.MarginBottom = 50
'WRAPR1
End Sub

Renderer.PrintOptions.MarginTop = 50 'millimeters
Renderer.PrintOptions.MarginBottom = 50
VB   C#

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

Renderer.PrintOptions.PrintHtmlBackgrounds = true;
Public Shared Sub wrapper()
'WRAPR1
Renderer.PrintOptions.PrintHtmlBackgrounds = True
'WRAPR1
End Sub

Renderer.PrintOptions.PrintHtmlBackgrounds = True
VB   C#

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


Renderer.PrintOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4;
Renderer.PrintOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Landscape;
Public Shared Sub wrapper()
'WRAPR1

Renderer.PrintOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4
Renderer.PrintOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Landscape
'WRAPR1
End Sub


Renderer.PrintOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4
Renderer.PrintOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Landscape
VB   C#

A full documentation of C# Html to PDF Settings may be found at http://ironpdf.com/c%23-pdf-documentation/html/T_IronPdf_PdfPrintOptions.htm

The full set of PDF PrintOptions includes:

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

HTML Templating

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

Rather than templating a PDF document its self, with IronPDF we ma 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, suing the C# String.Format method is effective for basic "mail-merge"

String.Format("<h1>Hello {0} !<h1>","World");
Public Shared Sub wrapper()
'WRAPR1
String.Format("<h1>Hello {0} !<h1>","World")
'WRAPR1
End Sub

String.Format("<h1>Hello {0} !<h1>","World")
VB   C#

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.

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");
}
Public Shared Sub wrapper()
'WRAPR1
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
'WRAPR1
End Sub

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
VB   C#

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 https://www.nuget.org/packages/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>
*/
Public Shared Sub wrapper()
'WRAPR1
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>
'
'WRAPR1
End Sub

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>
'
VB   C#

To render this html we can simply use the RenderHtmlAsPdf method.

IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
Renderer.RenderHtmlAsPdf(HtmlInstance).SaveAs("Handelbars.pdf")
Public Shared Sub wrapper()
'WRAPR1
Dim Renderer As New IronPdf.HtmlToPdf()
Renderer.RenderHtmlAsPdf(HtmlInstance).SaveAs("Handelbars.pdf")
'WRAPR1
End Sub

Dim Renderer As New IronPdf.HtmlToPdf()
Renderer.RenderHtmlAsPdf(HtmlInstance).SaveAs("Handelbars.pdf")
VB   C#

You can learn more about the handlebars html templating standard and its C# using from https://github.com/rexm/Handlebars.Net

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 knows CSS trick which will render a page break into any printed HTML document.

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

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

<!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>
HTML

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

var PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/");
PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF).SaveAs("Combined.Pdf");
Public Shared Sub wrapper()
'WRAPR1
Dim PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/")
PdfDocument.Merge(New PdfDocument("CoverPage.pdf"), PDF).SaveAs("Combined.Pdf")
'WRAPR1
End Sub

Dim PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/")
PdfDocument.Merge(New PdfDocument("CoverPage.pdf"), PDF).SaveAs("Combined.Pdf")
VB   C#

Adding a WaterMark

A final C# PDF trick is to add a watermark to PDF documents. Such as a notice on each page that a document is "confidential" or a "sample"

// Stamps a watermark onto a new or existing PDF
IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
var pdf =  Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf");
pdf.SaveAs(@"C:\Path\To\Watermarked.pdf");
Public Shared Sub wrapper()
'WRAPR1
' Stamps a watermark onto a new or existing PDF
Dim Renderer As New IronPdf.HtmlToPdf()
Dim pdf = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf")
pdf.SaveAs("C:\Path\To\Watermarked.pdf")
'WRAPR1
End Sub

' Stamps a watermark onto a new or existing PDF
Dim Renderer As New IronPdf.HtmlToPdf()
Dim pdf = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")
pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf")
pdf.SaveAs("C:\Path\To\Watermarked.pdf")
VB   C#

Downloading this Tutorial as C# Source Code

The full C# Html-to-PDF Source Code for this tutorial is available to download as a zipped Visual Studio 2017 project file.

Download this tutorial as a Visual Studio project

The free download contains working C# PDF code examples code for:

  1. Html Strings to PDFs using C#
  2. Html files (supporting CSS, Javascript and images) to PDF
  3. C# HTML to PDF using a URL
  4. C# PDF editing settings examples
  5. Rendering Javascript canvas charts such as d3.js to a PDF
  6. The PDF Library for C#

Downloadable C# PDF QuickStart Guide

To make developing PDFs in your .Net applications easier, we have compiled a quick-start guide as a PDF document. This "Cheat-Sheet" provide quick access to common functions and examples for generating and editing PDFs in C# and VB.Net - and may help save time in getting started using IronPDF in your .NEt project.

Going Forwards

Developers may also be interested in the IronPdf.PdfDocument Class reference: http://ironpdf.com/c%23-pdf-documentation/html/T_IronPdf_PdfDocument.htm

This object model shows how PDF documents may be:

  • Encrypted and password protected
  • Edited or 'stamped' with new html content
  • Enhanced with foreground and background images
  • Merged, joined, truncated and spliced at a page or document level
  • OCR processed to extract plain text and images
.Net Software Engineer For many this is the most efficient way to generate PDF files from .Net, because there is no additional API to learn, or complex design system to navigate

Jean Ashberg

.Net Software Engineer

Jean is an independent software developer for corporate internal information solutions based in the Massachusetts, USA.  

Jean was an early adopter or IronPDF, and has repeatedly been involved in ‘speccing-out’ product improvement and building a roadmap to creating a single stable library for C# that covers all major PDF product feature use cases.