HTML to PDF C# Conversion

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:

  • Create a PDF certificate using HTML as the 'content' for the PDF from within a C# application.
  • Apply editing and PDF generation functionality in C#

Overview

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. And C# doesn't have many suitable libraries or features for PDF generation built-in.

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 , .Cyberspace Standard, .Internet Core and .NET 5 on Windows, Linux, Azure and MacOS.

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

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

VB.NET : Convert HTML to PDF

IronPDF is a C# Library that allows developers to create PDF documents easily in C#, F#, and VB.NET for .NET Cadre and .Internet Framework. This ensures that we, every bit .NET coders, do not need to acquire proprietary file formats or new APIs. We tin can easily output dynamic PDF files from our programs and web applications.

IronPDF Features:

  • HTML to PDF document conversion with a perfect Google Chrome rendering engine which is always kept up to date
  • Human support directly from our .NET development team
  • Works with the documents yous already accept, including HTML, ASP.NET. ASPX forms, ASP.NET , ASP.NET. RazoMVC views and image files
  • Rapid installation with Microsoft Visual Studio
  • Complimentary for development. Licenses from $499

Step ane

1. Download the HTML to PDF .Cyberspace Library from IronPDF FREE

C# PDF DLL

Download DLL

or

C# Nuget Library for PDF

Install with NuGet

Install via NuGet

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

This volition piece of work in any C# .NET Framework project from Framework iv and above, or .NET Core 2 and to a higher place. It will also work just likewise in VB.NET projects.

            PM > Install-Bundle IronPdf                      

https://world wide web.nuget.org/packages/IronPdf

Install via DLL

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

Call up to add this statement to the top of whatsoever cs class file using IronPDF:

                          using IronPdf;          

How to Tutorials

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

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

We can simply use the ChromePdfRenderer.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.

            /** PDF from HTML String anchor-create-a-pdf-with-an-html-string-in-net-c **/ // Return any HTML fragment or document to HTML var Renderer = new IronPdf.ChromePdfRenderer(); using var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>"); var OutputPath = "pixel-perfect.pdf"; PDF.SaveAs(OutputPath);          
                /** PDF from HTML Cord anchor-create-a-pdf-with-an-html-string-in-net-c **/ // Return any HTML fragment or certificate to HTML var Renderer = new IronPdf.ChromePdfRenderer(); using var PDF = Renderer.RenderHtmlAsPdf("<h1>Hi IronPdf</h1>"); var OutputPath = "pixel-perfect.pdf"; PDF.SaveAs(OutputPath);              
                ''' '''PDF from HTML String '''anchor-create-a-pdf-with-an-html-cord-in-cyberspace-c '''* ' Render any HTML fragment or document to HTML Dim Renderer = New IronPdf.ChromePdfRenderer() Using PDF = Renderer.RenderHtmlAsPdf("<h1>Hullo IronPdf</h1>") 	Dim OutputPath = "pixel-perfect.pdf" 	PDF.SaveAs(OutputPath) Cease Using              

VB C#

RenderHtmlAsPdf fully supports CSS, Javascript and Images. If these assets are on a hd, we may wish to set the second parameter of RenderHtmlAsPdf

IronPDF will render your HTML exactly equally information technology appears in Chrome

i. First set your global rendering engine

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

VB C#

API: https://ironpdf.com/object-reference/api/IronPdf.Rendering.PdfRenderingEngine.html#fields

2. This lawmaking 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 = fake; Renderer.RenderingOptions.CreatePdfFormsFromHtml = simulated; Renderer.RenderingOptions.FitToPaper = false;          
                ChromePdfRenderer Renderer = new ChromePdfRenderer(); Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print; Renderer.RenderingOptions.PrintHtmlBackgrounds = false; Renderer.RenderingOptions.CreatePdfFormsFromHtml = false; Renderer.RenderingOptions.FitToPaper = fake;              
                Dim Renderer As New ChromePdfRenderer() Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print Renderer.RenderingOptions.PrintHtmlBackgrounds = False Renderer.RenderingOptions.CreatePdfFormsFromHtml = False Renderer.RenderingOptions.FitToPaper = Fake              

VB C#

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

Annotation: Export whatsoever HTML string and assets to stand lone HTML files and edit them manually, or ask a friendly web developer to assist

4. Open the Print Preview window (Ctrl+P on Windows)

five. Select the Save as PDF choice

Once Impress to PDF in Chrome is perfect - IronPDF will match information technology

BaseUrlPath:

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

VB C#

All referenced CSS stylesheets, images and javascript files will be relative to the BaseUrlPath and can exist kept in a smashing and logical structure. Yous may also, of course opt to reference images, stylesheets and assets online, including web-fonts such as Google Fonts and even jQuery.


three. Consign 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 dissever PDF design and back-terminate PDF rendering piece of work beyond multiple teams.

Lets return a folio from Wikipedia.com in the following instance:

            /** HTML URL to PDF ballast-export-a-pdf-using-existing-html-url **/ // Create a PDF from any existing spider web page var Renderer = new IronPdf.ChromePdfRenderer(); using var PDF = Renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Portable_Document_Format"); PDF.SaveAs("wikipedia.pdf");                      
                /** HTML URL to PDF anchor-consign-a-pdf-using-existing-html-url **/ // Create a PDF from whatsoever existing web folio var Renderer = new IronPdf.ChromePdfRenderer(); using var PDF = Renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Portable_Document_Format"); PDF.SaveAs("wikipedia.pdf");                              
                ''' '''HTML URL to PDF '''anchor-export-a-pdf-using-existing-html-url '''* ' Create a PDF from whatever existing web page Dim Renderer = New IronPdf.ChromePdfRenderer() Using PDF = Renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Portable_Document_Format") 	PDF.SaveAs("wikipedia.pdf") End Using              

VB C#

Y'all will notice that hyperlinks and fifty-fifty 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 utilise:

3.1. Impress and Screen CSS

In mod CSS3 nosotros have css directives for both impress and screen. Nosotros can instruct IronPDF to render "Print" CSSs which are oftentimes simplified or disregarded. By default "Screen" CSS styles volition exist rendered, which IronPDF users accept found most intuitive.

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

VB C#

three.ii. Javascript

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

            /** PDF with Javascript anchor-javascript **/ Renderer.RenderingOptions.EnableJavaScript = true; Renderer.RenderingOptions.RenderDelay = 500; //milliseconds          
                /** PDF with Javascript anchor-javascript **/ Renderer.RenderingOptions.EnableJavaScript = true; Renderer.RenderingOptions.RenderDelay = 500; //milliseconds              
                ''' '''PDF with Javascript '''anchor-javascript '''* Renderer.RenderingOptions.EnableJavaScript = Truthful Renderer.RenderingOptions.RenderDelay = 500 'milliseconds              

VB C#

We can demonstrate compliance with the Javascript standard by rendering an avant-garde d3.js Javascript chord nautical chart from a csv dataset like this:

            // Create a PDF Nautical chart a live rendered dataset using d3.js and javascript var Renderer = new ChromePdfRenderer(); using var PDF = Renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006"); PDF.SaveAs("chart.pdf");          
                // Create a PDF Chart a live rendered dataset using d3.js and javascript var Renderer = new ChromePdfRenderer(); using var PDF = Renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006"); PDF.SaveAs("nautical chart.pdf");              
                ' Create a PDF Chart a alive rendered dataset using d3.js and javascript Dim Renderer = New ChromePdfRenderer() Using PDF = Renderer.RenderUrlAsPdf("https://bl.ocks.org/mbostock/4062006") 	PDF.SaveAs("chart.pdf") Stop Using              

VB C#

3.iii. Responsive CSS

HTML to PDF using response CSS in .NET! Responsive web pages are designed to be viewed in a browser. IronPDF does not open a real browser window inside your server'southward Os. This can lead to responsive elements rendering at their smallest size.

We recommend using Print css media types to navigate this effect. Impress CSS should not normally be responsive.

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

VB C#


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

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

            /** 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();  using var PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html");  var OutputPath = "Invoice.pdf";  PDF.SaveAs(OutputPath);          
                /** PDF from Existing HTML ballast-generate-a-pdf-from-an-existing-html-file **/ // Create a PDF from an existing HTML using C#  var Renderer = new IronPdf.ChromePdfRenderer();  using var PDF = Renderer.RenderHTMLFileAsPdf("Avails/TestInvoice1.html");  var OutputPath = "Invoice.pdf";  PDF.SaveAs(OutputPath);              
                ''' '''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()  Using PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html") 	 Dim OutputPath = "Invoice.pdf" 	 PDF.SaveAs(OutputPath)  Stop Using              

VB C#

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

To convert XML to PDF yous can use XSLT templating to print your XML content to PDF.


Headers and footers tin can exist 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 grade.

            /** Add Headers and Footers anchor-add together-headers-and-footers **/ // Create a PDF from an existing HTML var Renderer = new IronPdf.ChromePdfRenderer();  Renderer.RenderingOptions.MarginTop = fifty;  //millimeters Renderer.RenderingOptions.MarginBottom = 50; Renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Impress;  Renderer.RenderingOptions.TextHeader = new TextHeaderFooter() {     CenterText = "{pdf-championship}",     DrawDividerLine = true,     FontSize = sixteen };  Renderer.RenderingOptions.TextFooter = new TextHeaderFooter() {     LeftText = "{appointment} {time}",     RightText = "Page {page} of {total-pages}",     DrawDividerLine = truthful,     FontSize = 14 };  using var PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html"); var OutputPath = "Invoice.pdf"; PDF.SaveAs(OutputPath);  // This neat trick opens our PDF file so we can encounter the result System.Diagnostics.Process.Start(OutputPath);          
                /** Add together Headers and Footers anchor-add together-headers-and-footers **/ // Create a PDF from an existing HTML var Renderer = new IronPdf.ChromePdfRenderer();  Renderer.RenderingOptions.MarginTop = 50;  //millimeters Renderer.RenderingOptions.MarginBottom = l; Renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;  Renderer.RenderingOptions.TextHeader = new TextHeaderFooter() {     CenterText = "{pdf-title}",     DrawDividerLine = true,     FontSize = 16 };  Renderer.RenderingOptions.TextFooter = new TextHeaderFooter() {     LeftText = "{engagement} {time}",     RightText = "Page {page} of {total-pages}",     DrawDividerLine = truthful,     FontSize = 14 };  using var PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html"); var OutputPath = "Invoice.pdf"; PDF.SaveAs(OutputPath);  // This peachy play a joke on opens our PDF file so nosotros tin can see the result System.Diagnostics.Process.First(OutputPath);              
                ''' '''Add together Headers and Footers '''ballast-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 = "{engagement} {time}", 	.RightText = "Page {page} of {full-pages}", 	.DrawDividerLine = Truthful, 	.FontSize = 14 }  Using PDF = Renderer.RenderHTMLFileAsPdf("Assets/TestInvoice1.html") 	Dim OutputPath = "Invoice.pdf" 	PDF.SaveAs(OutputPath) 	 	' This smashing trick opens our PDF file so we tin can run into the outcome 	System.Diagnostics.Process.Kickoff(OutputPath) Terminate Using              

VB C#

            Renderer.RenderingOptions.TextFooter = new TextHeaderFooter() {     LeftText = "{appointment} {time}",     RightText = "Page {page} of {total-pages}",     DrawDividerLine = truthful,     FontSize = 14 };          
                Renderer.RenderingOptions.TextFooter = new TextHeaderFooter() {     LeftText = "{date} {time}",     RightText = "Page {page} of {total-pages}",     DrawDividerLine = true,     FontSize = xiv };              
                Renderer.RenderingOptions.TextFooter = New TextHeaderFooter() With { 	.LeftText = "{date} {time}", 	.RightText = "Page {page} of {total-pages}", 	.DrawDividerLine = True, 	.FontSize = 14 }              

VB C#

5.ane. 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.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()  { HtmlFragment = "<div style='text-align:right'><em way='colour:pink'>page {page} of {total-pages}</em></div>" };          
                Renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()  { HtmlFragment = "<div way='text-align:right'><em way='color:pink'>page {folio} of {total-pages}</em></div>" };              
                Renderer.RenderingOptions.HtmlFooter = New HtmlHeaderFooter() With {.HtmlFragment = "<div fashion='text-align:right'><em style='color:pinkish'>folio {folio} of {total-pages}</em></div>"}              

VB C#

5.2. Dynamic Data in PDF Headers and Footers

We may "mail-merge" content into the text and fifty-fifty 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 championship attribute of the rendered HTML document
  • {pdf-title} for the document title, which may exist set via the PrintOptions

vi. 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 PrintOptions object which can be used to prepare these options.

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

            /** Print Style CSS anchor-c-html-to-pdf-settings **/ Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;          
                /** Print Style CSS anchor-c-html-to-pdf-settings **/ Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Impress;              
                ''' '''Impress Style CSS '''anchor-c-html-to-pdf-settings '''* Renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print              

VB C#

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 zippo margins for commercial press of brochures or posters:

            /** Impress Margins Size ballast-c-html-to-pdf-settings **/ Renderer.RenderingOptions.MarginTop = 50;  //millimeters Renderer.RenderingOptions.MarginBottom = 50;          
                /** Print Margins Size anchor-c-html-to-pdf-settings **/ Renderer.RenderingOptions.MarginTop = 50;  //millimeters Renderer.RenderingOptions.MarginBottom = 50;              
                ''' '''Impress Margins Size '''ballast-c-html-to-pdf-settings '''* Renderer.RenderingOptions.MarginTop = 50 'millimeters Renderer.RenderingOptions.MarginBottom = 50              

VB C#

We may wish to plough on or off background images from HTML elements:

            /** Print Background Images anchor-c-html-to-pdf-settings **/ Renderer.RenderingOptions.PrintHtmlBackgrounds = true;          
                /** Print Groundwork Images ballast-c-html-to-pdf-settings **/ Renderer.RenderingOptions.PrintHtmlBackgrounds = true;              
                ''' '''Impress Groundwork Images '''anchor-c-html-to-pdf-settings '''* Renderer.RenderingOptions.PrintHtmlBackgrounds = Truthful              

VB C#

Information technology is also possible to set our output PDFs to be rendered on whatsoever virtual paper size - including portrait and landscape sizes and fifty-fifty custom sizes which may be gear up in millimeters or inches.

            /** Print Newspaper Size anchor-c-html-to-pdf-settings **/ Renderer.RenderingOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4; Renderer.RenderingOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Landscape;          
                /** Print Newspaper Size anchor-c-html-to-pdf-settings **/ Renderer.RenderingOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4; Renderer.RenderingOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Landscape;              
                ''' '''Impress Paper Size '''anchor-c-html-to-pdf-settings '''* Renderer.RenderingOptions.PaperSize = PdfPrintOptions.PdfPaperSize.A4 Renderer.RenderingOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Landscape              

VB C#

Total documentation of the HTML C# PDF Creator Settings may be found at https://ironpdf.com/object-reference/api/IronPdf.PdfPrintOptions.html

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 way-sheet to be applied to Html before rendering. May be a local file path, or a remote url.
  • DPI Press output DPI. 300 is standard for well-nigh print jobs. Higher resolutions produce clearer images and text, simply 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 Kickoff page number to be used in PDF headers and footers.
  • FitToPaper Where possible, zooms the PDF content to 1 page width.
  • TextFooter Sets the header content for every PDF page as a Cord. Supports 'mail-merge'
  • TextHeader Sets the footer content for every PDF page as a Cord. Supports 'post-merge'
  • HtmlFooter Sets the header content for every PDF page as Html
  • HtmlHeader Sets the footer content for every PDF folio equally Html
  • MarginBottom Paper margin in millimeters. Set to null for border-less and commercial printing applications
  • MarginLeft Paper margin in millimeters
  • MarginRight Newspaper margin in millimeters
  • MarginTop Paper margin in millimeters. Set to zero for border-less and commercial printing applications
  • PaperOrientation The PDF newspaper orientation.
  • PaperSize Set an output paper size for PDF pages. Arrangement.Drawing.Printing.PaperKind. Use SetCustomPaperSize(int width, int top) for custom sizes
  • PrintHtmlBackgrounds Prints groundwork-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
  • Championship PDF Certificate Proper noun and Championship meta-information. Not required
  • Zoom The zoom level in %. Enlarges the rendering size of Html documents

seven. Utilise HTML Templating

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

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

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

            /** HTML Templating anchor-apply-html-templating **/        Cord.Format("<h1>Hello {0} !</h1>","World");          
                /** HTML Templating anchor-apply-html-templating **/        Cord.Format("<h1>Hullo {0} !</h1>","World");              
                ''' '''HTML Templating '''anchor-apply-html-templating '''*        Cord.Format("<h1>Hello {0} !</h1>","World")              

VB C#

If the HTML file is longer, often nosotros can employ arbitrary placeholders such as [[NAME]] and replace them with real data later.

The post-obit example will create 3 PDFs, each personalized to a user.

            var HtmlTemplate = "<p>[[Proper noun]]</p>";  var Names = new[] { "John", "James", "Jenny" };  foreach (var name in Names) {     var HtmlInstance = HtmlTemplate.Supercede("[[NAME]]", proper name);     var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance);     Pdf.SaveAs(name + ".pdf"); }          
                var HtmlTemplate = "<p>[[Proper name]]</p>";  var Names = new[] { "John", "James", "Jenny" };  foreach (var proper noun in Names) {     var HtmlInstance = HtmlTemplate.Replace("[[Proper noun]]", name);     var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance);     Pdf.SaveAs(name + ".pdf"); }              
                Dim HtmlTemplate = "<p>[[NAME]]</p>"  Dim Names = { "John", "James", "Jenny" }  For Each name In Names 	Dim HtmlInstance = HtmlTemplate.Replace("[[Name]]", proper noun) 	Dim Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance) 	Pdf.SaveAs(proper name & ".pdf") Next proper name              

VB C#

vii.1. Avant-garde 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 together an additional Nuget Package to our projection: https://www.nuget.org/packages/Handlebars.NET/

            /** Handlebars Templating anchor-advanced-templating-with-handlebars-net **/        cord source = @"<div class=""entry"">   <h1>{{title}}</h1>   <div form=""torso"">     {{torso}}   </div> </div>";  var template = Handlebars.Compile(source);  var information = new {     title = "My new post",     trunk = "This is my first mail service!" };  var outcome = template(information);  /* Would render: <div form="entry">   <h1>My New Mail service</h1>   <div grade="body">     This is my first post!   </div> </div> */          
                /** Handlebars Templating anchor-advanced-templating-with-handlebars-net **/        string source = @"<div class=""entry"">   <h1>{{championship}}</h1>   <div form=""torso"">     {{body}}   </div> </div>";  var template = Handlebars.Compile(source);  var data = new {     title = "My new postal service",     torso = "This is my offset mail service!" };  var result = template(data);  /* Would return: <div class="entry">   <h1>My New Post</h1>   <div class="body">     This is my first post!   </div> </div> */              
                ''' '''Handlebars Templating '''ballast-avant-garde-templating-with-handlebars-net '''*        Dim source As String = "<div class=""entry"">   <h1>{{title}}</h1>   <div form=""body"">     {{body}}   </div> </div>"  Dim template = Handlebars.Compile(source)  Dim information = New With { 	Key .title = "My new post", 	Fundamental .body = "This is my offset post!" }  Dim effect = template(data)  ' Would render: '<div course="entry"> '  <h1>My New Mail</h1> '  <div class="body"> '    This is my first post! '  </div> '</div> '              

VB C#

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

            IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer(); using var PDF = Renderer.RenderHtmlAsPdf(HtmlInstance); PDF.SaveAs("Handelbars.pdf")          
                IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer(); using var PDF = Renderer.RenderHtmlAsPdf(HtmlInstance); PDF.SaveAs("Handelbars.pdf")              
                Dim Renderer Equally New IronPdf.ChromePdfRenderer() Using PDF = Renderer.RenderHtmlAsPdf(HtmlInstance) 	'INSTANT VB TODO TASK: The post-obit line uses invalid syntax: 	'PDF.SaveAs("Handelbars.pdf") End Using              

VB C#

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

7.2. Add together Page Breaks using HTML5

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

The easiest way to do this is with a less known CSS play a joke on which volition render a page break into whatever printed HTML document.

            <div style='page-break-afterward: always;'>&nbsp;</div>          
                <div style='page-break-later: always;'>&nbsp;</div>              

HTML

The provided HTML works, only is hardly best practice. We constitute this example to be very helpful in our understanding of a bang-up and tidy mode to lay out multi-page html content.

            /** Add Multipage Breaks anchor-add-page-breaks-using-html **/    <!DOCTYPE html> <!--https://stackoverflow.com/questions/1630819/google-chrome-printing-page-breaks--> <html>   <caput>     <meta http-equiv="content-type" content="text/html;charset=UTF-8" />     <title>Paginated HTML</title>     <fashion type="text/css" media="print">       div.folio       {         page-break-subsequently: always;         page-break-inside: avert;       }     </fashion>   </caput>   <body>     <div form="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>          
                /** Add Multipage Breaks anchor-add together-page-breaks-using-html **/    <!DOCTYPE html> <!--https://stackoverflow.com/questions/1630819/google-chrome-printing-folio-breaks--> <html>   <caput>     <meta http-equiv="content-type" content="text/html;charset=UTF-8" />     <title>Paginated HTML</title>     <style type="text/css" media="print">       div.page       {         folio-suspension-after: always;         page-break-inside: avoid;       }     </style>   </caput>   <body>     <div form="page">       <h1>This is Folio 1</h1>     </div>     <div grade="folio">       <h1>This is Page 2</h1>     </div>     <div grade="page">       <h1>This is Page 3</h1>     </div>   </body> </html>              

HTML

The FAQ outlines more tips and tricks with Page Breaks


8. Adhere a Comprehend Page to a PDF

IronPDF makes it easy to Merge PDF documents. The well-nigh mutual usage of this technique is to add a cover page or back page to an existing rendered PDF certificate.

To practise so we showtime return a encompass page, and then use the PdfDocument.Merge static method to combine the 2 documents.

            /** Add Embrace Page anchor-adhere-a-cover-folio-to-a-pdf **/    using var PDF = Renderer.RenderUrlAsPdf("https://world wide web.nuget.org/packages/IronPdf/"); PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF).SaveAs("Combined.Pdf");          
                /** Add Cover Page ballast-attach-a-encompass-folio-to-a-pdf **/    using var PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/"); PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF).SaveAs("Combined.Pdf");              
                ''' '''Add Embrace Folio '''anchor-attach-a-encompass-page-to-a-pdf '''*    Using PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/") 	PdfDocument.Merge(New PdfDocument("CoverPage.pdf"), PDF).SaveAs("Combined.Pdf") End Using              

VB C#


9. Add a Watermark

A final C# PDF play a trick on is to add a watermark to PDF documents. This tin be used to add a discover to each folio that a document is "confidential" or a "sample".

            /** Add Watermark ballast-add-a-watermark **/    // Stamps a watermark onto a new or existing PDF IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer(); using var pdf =  Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");  pdf.WatermarkAllPages("<h2 way='color:cherry'>SAMPLE</h2>",  IronPdf.Editing.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf");  pdf.SaveAs(@"C:\Path\To\Watermarked.pdf");          
                /** Add Watermark anchor-add-a-watermark **/    // Stamps a watermark onto a new or existing PDF IronPdf.ChromePdfRenderer Renderer = new IronPdf.ChromePdfRenderer(); using var pdf =  Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");  pdf.WatermarkAllPages("<h2 manner='colour:cherry'>SAMPLE</h2>",  IronPdf.Editing.WaterMarkLocation.MiddleCenter, 50, -45, "https://world wide web.nuget.org/packages/IronPdf");  pdf.SaveAs(@"C:\Path\To\Watermarked.pdf");              
                ''' '''Add Watermark '''anchor-add together-a-watermark '''*    ' Stamps a watermark onto a new or existing PDF Dim Renderer Equally New IronPdf.ChromePdfRenderer() Using pdf = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf") 	 	pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", IronPdf.Editing.WaterMarkLocation.MiddleCenter, l, -45, "https://www.nuget.org/packages/IronPdf") 	 	pdf.SaveAs("C:\Path\To\Watermarked.pdf") Cease Using              

VB C#


ten. Download as C# Source Code

The full gratuitous Html to PDF converter C# Source Code 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#.

Download this tutorial as a Visual Studio projection

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

  1. Convert an HTML Cord to PDF using C#
  2. HTML file to PDF in C# (supporting CSS, Javascript and images)
  3. C# HTML to PDF using a URL ("url to pdf")
  4. C# PDF editing and settings examples
  5. Rendering Javascript canvass charts such equally d3.js to a PDF
  6. The PDF Library for C#

Form Reference

Developers may likewise be interested in the IronPdf.PdfDocument Grade reference:

https://ironpdf.com/object-reference/api/IronPdf.PdfDocument.html

This object model shows how PDF documents may be:

  • Encrypted and countersign protected
  • Edited or 'stamped' with new html content
  • Enhanced with foreground and background images
  • Merged, joined, truncated and spliced at a folio or document level
  • OCR candy to extract plain text and images

11. Compare with Other PDF Libraries

PDFSharp

PDFSharp is a free open source library which allows logical editing and cosmos of PDF documents in .Internet.

A fundamental 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 besides differs from PDFSharp in that it is based around utilise cases rather than the technical structure of PDF documents. Many detect this more logical and intuitive to use.

It tin catechumen HTML to PDF, but HTML to PDF conversion is express: including .html files to PDF files.

WKHtmlToPdf

WKHtmlToPdf is a gratuitous, open up 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 prophylactic for use in .Cyberspace applications and Websites.

IronPDF also supports CSS3 and HTML5 fully, where as WKHtmlToPdf is almost a decade out of engagement.

The IronPDF API as well 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 only 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. Catechumen HTML to PDF- that is possible, but I notice its rendering was limited to what is bachelor in Java or uses HTML to PDF conversion from WKHtmlToPdf under the LGPL open sourced license.

A key divergence with HTML to PDF between C# iTextSharp 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 every bit iTextSharp'southward AGLP license is only suitable for applications where the total source code is presented for free to every user - even users across the internet.

A full breakdown of the differences is available in our iTextSharp C# FAQ.

Other Commercial Libraries

Aspose PDF, Spire PDF, EO PDF, and SelectPdf are competitor .Cyberspace commercial PDF libraries by other vendors. Information technology 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 insufficiently strong feature set, splendid .NET Core compatibility and a off-white toll point.


12. Watch HTML to PDF Tutorial Video


Tutorial Quick Access

Download this Tutorial as C# Source Lawmaking

The full free HTML to PDF C# Source Code for this tutorial is bachelor to download as a zipped Visual Studio 2017 project file.

Download

Explore this Tutorial on GitHub

The source code for this project is available in C# and VB.Internet on GitHub.

Use this code equally an like shooting fish in a barrel way to go up and running in just a few minutes. The project is saved as a Microsoft Visual Studio 2017 project, simply is compatible with any .NET IDE.

C# HTML to PDF VB.NET HTML to PDF

Download 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 .Cyberspace project.

Download

View the API Reference

Explore the API Reference for IronPDF, outlining the details of all of IronPDF'south features, namespaces, classes, methods fields and enums.

View the API Reference

.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, nor complex design system to navigate

Jean Ashberg

.Cyberspace Software Engineer

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

Jean was an early adopter of 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 production feature use cases.