1.
2.
3.
4.
5.
6.
7.
// 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);
HTML to PDF
How to create PDFs
in C# with HTML to PDF
Converter
Tutorial
Download the HTML to PDF .NET Library from IronPDF FREE
Create a PDF with an HTML String in .NET C#
Export a PDF Using Existing HTML URL
Generate a PDF From an Existing HTML File
Add Headers And Footers
C# HTML to PDF Settings
Apply HTML Templating
Attach a Cover Page to a PDF
Add a Watermark
Download as C# Source Code
Compare with Other PDF Libraries
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
Table of Contents
This C# PDF tutorial will guide you step-by-step how to convert an HTML page to PDF in ASP.NET C#
applications and websites (C# htmltopdfconverter). With C# we can create PDF documents using HTML
as the 'content' for the PDF, applying editing and generation functionality.
Interact with the tutorial: https://ironpdf.com/tutorials/html-to-pdf/
Share the tutorial:
by Jean Ashberg
HTML to PDF
C# Conversion
1
// 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);
https://www.nuget.org/packages/IronPdf
https://ironpdf.com/tutorials/html-to-pdf/#download-modal
Manually install into your project
Download DLL
or
nuget.org/packages/IronPdf/
Install with NuGet
1. Download the HTML to PDF .NET Library from
IronPDF FREE
Step 1
Human support directly from our .NET development team
Works with the documents you already have, including HTML, ASPX forms, MVC views and image files
Rapid installation with Microsoft Visual Studio
FREE for development. Licenses from $399.
IronPDF Features:
IronPDF 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.
VB.NET : Convert HTML to PDF
https://ironpdf.com/
The tool we will be using in this tutorial is IronPDF, a popular C# PDF generation and editing library. This
library has comprehensive PDF editing and generation functionality via HTML to PDF. IronPDF stands out in
that it supports .NET Framework and .NET Core on Windows, Linux, Azure and MacOS.
With C# and IronPDF, creating PDF documents 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.
Creating PDF files programmatically in .NET can
be a frustrating task. The PDF document file
format was designed more for printers than for
developers.
https://youtu.be/cEKjADq1EyU
Watch the Tutorial
HTML to PDF :
A Quick Tutorial for C# .Net
Convert HTML to PDF in VB.NET and C# with IronPDF
2
1.
2.
var PDF = Renderer.RenderHtmlAsPdf("<img src='image1.png'/>", @"C:\MyProject\Assets\");
// this will render C:\MyProject\Assets\image1.png
BaseUrlPath:
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
1.
2.
3.
4.
5.
6.
7.
// 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);
https://ironpdf.com/c%23-pdf-documentation/html/M_IronPdf_HtmlToPdf_RenderHtmlAsPdf.htm
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.
C# HTML to PDF rendering is undertaken by a fully functional version of the Google Chromium engine,
embedded within IronPDF DLL.
2. Create a PDF with an HTML String in .NET C#
How to Tutorials
using IronPdf;
Alternatively, the IronPDF DLL can be downloaded and manually installed to the project or GAC from
https://ironpdf.com/packages/IronPdf.zip
Remember to add this statement to the top of any cs class file using IronPDF:
Install via DLL
https://www.nuget.org/packages/IronPdf
PM > Install-Package IronPdf
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.
Install via NuGet
3
1.
2.
Renderer.PrintOptions.EnableJavaScript = true;
Renderer.PrintOptions.RenderDelay = 500; //milliseconds
https://ironpdf.com/docs/questions/javascript-to-pdf/
IronPDF 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.
1.
2.
3.
4.
// 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");
We can demonstrate compliance with the Javascript standard by rendering an advanced d3.js Javascript
chord chart from a csv dataset like this:
3.2. Javascript
1.
2.
3.
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
//or
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
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.
3.1. Print and Screen CSS
1.
2.
3.
4.
5.
6.
// 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");
Lets render a page from Wikipedia.com in the following example:
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
3. Export a PDF Using Existing HTML URL
https://ironpdf.com/docs/questions/webfonts-azure/
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 web-fonts such as Google Fonts and even jQuery.
4
5
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 SimpleHeaderFooter
class - or with images and rich html content using the HtmlHeaderFooter class.
5. Add Headers And Footers
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 XML to PDF you can use XSLT templating to print your XML content to PDF.
1.
2.
3.
4.
5.
// 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);
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.
4. Generate a PDF From an Existing HTML File
1.
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
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.
3.3. Responsive CSS
6
{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
We may "mail-merge" content into the text and even HTML of headers and footers using placeholders
such as:
5.2. Dynamic Data in PDF Headers and Footers
1.
Renderer.PrintOptions.Footer = new HtmlHeaderFooter() { HtmlFragment = "<div
style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>" };
The HtmlHeaderFooter class allows for rich headers and footers to be generated using HTML5 content
which may even include images, stylesheets and hyperlinks.
5.1. HTML Headers and Footers
1.
2.
3.
4.
5.
6.
7.
Renderer.PrintOptions.Footer = new SimpleHeaderFooter()
{
LeftText = "{date} {time}",
RightText = "Page {page} of {total-pages}",
DrawDividerLine = true,
FontSize = 14
};
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
// 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);
7
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 a remote url.
Full documentation of the HTML C# PDF Creator Settings may be found at
https://ironpdf.com/c%23-pdf-documentation/html/T_IronPdf_PdfPrintOptions.htm
The full set of PDF PrintOptions includes:
1.
2.
Renderer.PrintOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4;
Renderer.PrintOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Landscape;
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.
1.
Renderer.PrintOptions.PrintHtmlBackgrounds = true;
We may wish to turn on or off background images from html elements:
1.
2.
Renderer.PrintOptions.MarginTop = 50; //millimeters
Renderer.PrintOptions.MarginBottom = 50;
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:
1.
Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
For example we may wish to choose to only accept "print" style CSS3 directives:
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.
6. C# HTML to PDF Settings
{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
8
If the Html file is longer, often we can use arbitrary placeholders such as and replace them with
real data later.
[[NAME]]
1.
String.Format("<h1>Hello {0} !<h1>","World");
To template or "batch create" PDFs is a common requirement for Intranet 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"
7. Apply HTML Templating
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 a String. Supports 'mail-merge'
GrayScale Outputs a black-and-white PDFl documents
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 Htm
9
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
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>
*/
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/
7.1. Advanced Templating With Handlebars.Net
1.
2.
3.
4.
5.
6.
7.
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");
}
The following example will create 3 PDFs, each personalized to a user.
10
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
<!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 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.
1.
<div style='page-break-after: always;'>&nbsp;</div>
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.
7.2. Add Page Breaks using HTML5
You can learn more about the handlebars html templating standard and its C# using from
https://github.com/rexm/Handlebars.Net
1.
2.
IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
Renderer.RenderHtmlAsPdf(HtmlInstance).SaveAs("Handelbars.pdf")
To render this html we can simply use the RenderHtmlAsPdf method.
11
Html Strings to PDFs using C#
Html files (supporting CSS, Javascript and images) to PDF
C# HTML to PDF using a URL
C# PDF editing and settings examples
Rendering Javascript canvas charts such as d3.js to a PDF
The PDF Library for C#
1.
2.
3.
4.
5.
6.
The full free Html to PDF C# 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:
10. Download as C# Source Code
1.
2.
3.
4.
5.
// 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");
A final C# PDF 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".
9. Add a Watermark
1.
2.
var PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/");
PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF).SaveAs("Combined.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 static method to combine the
2 documents.
PdfDocument.Merge
8. Attach a Cover Page to a PDF
The FAQ outlines more tips and tricks with Page Breaks
12
iTextSharp is an open source partial port of the iText java library for PDF generation and editing.
A key difference with HTML to PDF between C# iTextSharp and IronPDF is that IronPDF is has more
advanced and accurate HTML-To-PDF rendering by using an embedded Chrome based web browser.
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.
iTextSharp
WKHtmlToPdf 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.
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.
WKHtmlToPdf
PDFSharp 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.
PDFSharp
11. Compare with Other PDF Libraries
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
Developers may also be interested in the IronPdf.PdfDocument Class reference:
https://ironpdf.com/c%23-pdf-documentation/html/T_IronPdf_PdfDocument.htm
This object model shows how PDF documents may be:
Class Reference
13
View the Object Reference
Explore the Object Reference for IronPDF, outlining the details of all of
IronPDF’s features, namespaces, classes, methods fields and enums.
View the object reference
https://ironpdf.com/csharp-pdf.pdf
Download
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.
Download C# PDF Quickstart guide
C# HTML to PDF
VB.NET HTML to PDF
The source code for this project is available in C# and VB.NET on GitHub.
Use this code as an easy way to get up and running in just a few minutes. The
project is saved as a Microsoft Visual Studio 2017 project, but is compatible with
any .NET IDE.
Explore this Tutorial on GitHub
Download
The full free HTML to PDF C# Source Code for this tutorial is available to
download as a zipped Visual Studio 2017 project file.
Download this Tutorial as C# Source Code
Tutorial Quick Access
Aspose PDF, Spire PDF, EO PDF, and SelectPdf 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 .Net Core compatibility and a fair price point.
Other Commercial Libraries
A full breakdown of the differences is available in our iTextSharp C# FAQ.
14
Ask a Question
Open a support ticket
with our development team.
Support
Get Started
View code examples
and tutorials.
Documentation
See Licenses
Free for development.
License from $399.
Licensing
Download
Get set up in 5 minutes.
Try IronPDF Free
The C# PDF solution you've been looking for.