Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (151).NET Core  (25)Angular  (49)ASP.NET  (48)ASP.NET Core  (64)ASP.NET MVC  (86)Azure  (28)Blazor  (97)DocIO  (20)Essential JS 2  (71)Essential Studio  (163)File Formats  (20)Flutter  (111)JavaScript  (148)Microsoft  (101)PDF  (59)React  (33)Succinctly series  (122)Syncfusion  (480)TypeScript  (30)Uno Platform  (3)UWP  (4)Vue  (26)Webinar  (25)Windows Forms  (55)WinUI  (21)WPF  (122)Xamarin  (130)XlsIO  (24)Other CategoriesBarcode  (4)BI  (29)Bold BI  (3)Build conference  (6)Business intelligence  (53)Button  (4)C#  (107)Chart  (51)Cloud  (9)Company  (445)Dashboard  (6)Data Science  (3)Data Validation  (5)DataGrid  (47)Development  (257)Doc  (7)DockingManager  (1)eBook  (93)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (20)Extensions  (13)File Manager  (4)Gantt  (9)Gauge  (7)Git  (4)Grid  (27)HTML  (9)Installer  (2)Knockout  (2)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (227)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (23)Performance  (6)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (6)Road Map  (9)Scheduler  (26)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (19)Solution Services  (2)Spreadsheet  (9)SQL  (7)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (60)UI  (131)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (1)Visual Studio  (19)Visual Studio Code  (11)Web  (215)What's new  (140)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
HTML-to-PDF Conversion in C# - A Complete Guide

HTML-to-PDF Conversion in C# – A Complete Guide

While going through a webpage, you may want to download the HTML content as a PDF file for further reference. In that case, you need a versatile converter to convert the exact content of HTML to PDF.

Using the Syncfusion HTML-to-PDF converter library, you can convert an entire webpage into a PDF file, or just convert a portion of the page with C#. Your PDF will look exactly like the webpage you have converted. The HTML-to-PDF converter preserves all graphics, text, fonts, links, and the layout of the original HTML document or webpage. It uses the Chromium Blink engine and WebKit to convert HTML pages to PDF documents. It can be easily integrated into any application with five simple lines of code.

In this blog post, we are going to cover in detail HTML to PDF conversion in C#, provided by the Syncfusion HTML-to-PDF converter.

Contents:

Install and configure the HTML-to-PDF converter library in your project

You can install the HTML-to-PDF library in Visual Studio or with the command line in the NuGet package manager:

  1. First, create a new .NET Core console application.
  2. In the Solution Explorer window, right-click on the project and select Manage NuGet Packages. Refer to the following screenshot.
    Select the Manage NuGet Packages option
  3. Now, search for the Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Windows package and then install it. This NuGet package is for Windows.
    For Linux platform: Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Linux.
    For Mac platform: Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Mac.
    Install the Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Windows package
  1. Next, you need to refer to the Blink binaries like in the following code to run the HTML-to-PDF converter.
    The BlinkBinariesWindows folder is available in the package’s installed location. Copy the Blink binaries to your local project path and set the path to the BlinkPath property of BlinkConverterSettings. This is mandatory to set the BlinkPath property with the BlinkBinaries folder. Otherwise, the converter will throw the Blink assemblies are missing exception.
    Copy the blink binaries to your local project pathRefer to the following code to convert HTML string to PDF.

    using Syncfusion.HtmlConverter;
    using Syncfusion.Pdf;
    using System.IO;
    
    namespace HTML_File_To_PDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Initialize the HTML to PDF converter with the Blink rendering engine.
                HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);
    
                BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();
    
                //Set the BlinkBinaries folder path.
                blinkConverterSettings.BlinkPath = @"../../../../../BlinkBinariesWindows/";
    
                //Assign Blink converter settings to HTML converter.
                htmlConverter.ConverterSettings = blinkConverterSettings;
    
                //Convert HTML string to PDF.
                PdfDocument document = htmlConverter.Convert("<h1>Hello world</h1>","");
    
                FileStream fileStream = new FileStream("Sample.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    
                //Save and close the PDF document .
                document.Save(fileStream);
                document.Close(true);
            }
        }
    }

By executing this example, you will get a PDF document like in the following image.

Converting an HTML String to PDF
Converting an HTML String to PDF

Convert HTML file to PDF

You can also convert HTML files with images, CSS, forms, hyperlinks, and JavaScript to a PDF document.

Refer to the following code example to convert a local HTML file to PDF.

//Initialize the HTML to PDF converter with the Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();

//Set the BlinkBinaries folder path.
blinkConverterSettings.BlinkPath = @"../../../../../BlinkBinariesWindows/";

//Assign Blink converter settings to the HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;

//Convert HTML File to PDF.
PdfDocument document = htmlConverter.Convert(Path.GetFullPath("../../../../../Data/html_file_converter.htm"));

FileStream fileStream = new FileStream("HTML_file_to_PDF.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

By executing this example, you will get a PDF document like in the following image.

Converting an HTML File to PDF
Converting an HTML File to PDF

Convert URL to PDF

You can easily convert a URL to a PDF with a few lines of code. Using this option, you can create a well-formatted PDF document from your webpage.

Refer to the following code example to convert an existing URL to PDF.

//Initialize the HTML to PDF converter with the Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);
BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();

blinkConverterSettings.ViewPortSize = new Syncfusion.Drawing.Size(1440, 0);

//Set the BlinkBinaries folder path.
blinkConverterSettings.BlinkPath = @"../../../../../BlinkBinariesWindows/";

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;

//Convert existing URL to PDF.
PdfDocument document = htmlConverter.Convert("https://www.syncfusion.com/");

FileStream fileStream = new FileStream("URL_to_PDF.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

//Save and close the PDF document.
document.Save(fileStream);
document.Close(true);

By executing this example, you will get a PDF document like in the following image.

Converting Existing URL to PDF
Converting Existing Website URL to PDF

Convert ASP.NET Core web Razor page to PDF

With the help of our Syncfusion HTML-to-PDF converter, you can convert the ASP.NET core Razor pages to PDF with a few lines of code in C#.

Refer to the following code example to convert an ASP.NET Core web Razor page to PDF.

public async Task<IActionResult> OnPostAsync()
{

   //Initialize the HTML to PDF converter with the Blink rendering engine.
   HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

   BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();

   blinkConverterSettings.ViewPortSize = new Syncfusion.Drawing.Size(1440, 0);

   //Set the BlinkBinaries folder path.
   blinkConverterSettings.BlinkPath = Path.Combine(_env.ContentRootPath, "BlinkBinariesWindows");

   //Assign Blink converter settings to HTML converter.
   htmlConverter.ConverterSettings = blinkConverterSettings;

   string url = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetEncodedUrl(HttpContext.Request);

   //Convert existing current page URL to PDF.
   PdfDocument document = htmlConverter.Convert(url);

   //Saving the PDF to the MemoryStream.
   MemoryStream stream = new MemoryStream();

   document.Save(stream);

   //Download the PDF document in the browser.
   return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "Output.pdf");
}

By executing this example, you will get a PDF document like in the following image.

converting an ASP.NET core Web Razor Page to PDF
Converting an ASP.NET Core Web Razor Page to PDF

Convert ASP.NET Core MVC view to PDF

This topic will explain how to convert an ASP.NET Core MVC view to PDF. An MVC application has a separate view and controller. Here, we are going to convert the current view to PDF.

Refer to the following code example to convert an ASP.NET Core MVC view to PDF.

public IActionResult ExportToPDF()
{
   //Initialize the HTML to PDF converter with the Blink rendering engine. 
   HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

   BlinkConverterSettings settings = new BlinkConverterSettings();
   settings.ViewPortSize = new Syncfusion.Drawing.Size(1440, 0);

   //Set the BlinkBinaries folder path. 
   settings.BlinkPath = Path.Combine(_hostingEnvironment.ContentRootPath, "BlinkBinariesWindows");

   //Assign Blink settings to HTML converter.
   htmlConverter.ConverterSettings = settings;

   //Get the current URL.
   string url = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetEncodedUrl(HttpContext.Request);
     
   url = url.Substring(0, url.LastIndexOf('/'));

   //Convert URL to PDF.
   PdfDocument document = htmlConverter.Convert(url);
   MemoryStream stream = new MemoryStream();
   document.Save(stream);
   return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "MVC_view_to_PDF.pdf");
}

By executing this example, you will get a PDF document like in the following image.

Converting an ASP.NET Core MVC View to PDF
Converting an ASP.NET Core MVC View to PDF

Convert HTML forms to fillable PDF Forms

With the HTML-to-PDF converter library, you can easily convert the web form fields to an interactive PDF form in C#. Enable the EnableForm property by setting its value as true to convert an HTML form to PDF form.

Refer to the following code example to convert HTML forms to PDF forms.

//Initialize the HTML to PDF converter with the Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();

//Convert web forms to PDF interactive forms.
blinkConverterSettings.EnableForm = true;

//Set the BlinkBinaries folder path.
blinkConverterSettings.BlinkPath = @"../../../../../BlinkBinariesWindows/";

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;

//Convert HTML File to PDF.
PdfDocument document = htmlConverter.Convert(Path.GetFullPath("../../../../../Data/HTMLForm.htm"));

FileStream fileStream = new FileStream("HTML_form_to_PDF_form.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

By executing this example, you will get a PDF document like in the following image.

Converting HTML Forms to Fillable PDF Forms
Converting HTML Forms to Fillable PDF Forms

Convert a part of a webpage to PDF

The Blink rendering engine also provides support for converting part of an HTML document like a table, a div, or image elements from the URL or HTML string. You can convert the HTML element by specifying the HTML element ID like in the following code example.

//Initialize the HTML to PDF converter with the Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();

//Set the BlinkBinaries folder path.
blinkConverterSettings.BlinkPath = @"../../../../../BlinkBinariesWindows/";

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;

//Convert particular table from HTML. 
PdfDocument document = htmlConverter.ConvertPartialHtml(File.ReadAllText("../../../../../Data/partialdemo.html"),"", "details");
FileStream fileStream = new FileStream("partial_Web_to_PDF.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

//Save and close the PDF document.
document.Save(fileStream);
document.Close(true);

By executing this example, you will get a PDF document like in the following image.

Converting HTML Elements to PDF
Converting HTML Elements to PDF

Convert authenticated webpage to PDF

Our Syncfusion HTML-to-PDF converter can convert any webpage to a PDF file. However, some webpages require authentication before access can be granted. In such cases, we have to provide the authentication details to the converter. That way, the converter can log in to access the page.

In this section, we are going to convert webpages with various authentication types into PDF.

Form authentication

The HTML-to-PDF converter for C# can convert webpages that use the ASP.NET forms authentication mechanism to login.

In this case, if the forms authentication is set to use cookies to store the forms-authentication ticket, then the corresponding cookie needs to be sent by the converter to the page that is to be converted.

You can set the value of the cookie in the Cookies property available in the BlinkConverterSettings.

Refer to the following code snippets to convert the secured webpage to PDF.

string cookieName = ".AspNetCore.Identity.Application";
//Get cookie value from HttpRequest object for the requested page.
string cookieValue = string.Empty;
if (Request.Cookies[cookieName] != null)
{
   cookieValue = Request.Cookies[cookieName];
}

//Initialize HTML to PDF converter with the Blink rendering engine. 
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings settings = new BlinkConverterSettings();

settings.ViewPortSize = new Syncfusion.Drawing.Size(1440, 0);

//Add cookies as name and value pair.
settings.Cookies.Add(cookieName, cookieValue);

//Set the BlinkBinaries folder path. 
settings.BlinkPath = Path.Combine(_hostingEnvironment.ContentRootPath, "BlinkBinariesWindows");

//Assign Blink settings to HTML converter.
htmlConverter.ConverterSettings = settings;

//Get the current URL.
string url = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetEncodedUrl(HttpContext.Request);

url = url.Substring(0, url.LastIndexOf('/'));

//Convert URL to PDF.
PdfDocument document = htmlConverter.Convert(url);
MemoryStream stream = new MemoryStream();
document.Save(stream);
return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Pdf, "MVC_view_to_PDF.pdf");

By executing this example, you will get a PDF document like in the following image.

Converting a Webpage with Form Authentication to PDF
Converting a Webpage with Form Authentication to PDF

Windows authentication

The webpage you want to convert may be protected with Windows authentication. The Blink rendering engine provides support for converting Windows authenticated webpages to a PDF document by providing the username and password.

Refer to the following code example.

HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();

//Set the BlinkBinaries folder path.
blinkConverterSettings.BlinkPath = @"/BlinkBinaries/";

blinkConverterSettings.Username = "username";

blinkConverterSettings.Password = "password";

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;

//Convert URL to PDF.
PdfDocument document = htmlConverter.Convert("https://www.example.com");

FileStream fileStream = new FileStream("Sample.pdf", FileMode.CreateNew, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

By executing this example, you will get a PDF document like in the following image.

Converting a Webpage with Windows Authentication to PDF
Converting a Webpage with Windows Authentication to PDF

HTTP GET and POST

Also, the HTML-to-PDF converter for C# supports transmitting parameters to a webpage. There are two methods to access a webpage:

  • GET
  • POST

By default, Blink uses the GET method. By using the HTTP GET method, the parameters can be passed in the query string.

In the POST method, you can pass the parameters using the HttpPostFields property.

Refer to the following code example to access a webpage using the HTTP POST method.

HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings settings = new BlinkConverterSettings();

//Set the BlinkBinaries folder path.
settings.BlinkPath = @"/BlinkBinaries/";

//Add HTTP post parameters to HttpPostFields.
settings.HttpPostFields.Add("firstName", "Andrew");
settings.HttpPostFields.Add("lastName", "Fuller");

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = settings;

//Convert URL to PDF.
PdfDocument document = htmlConverter.Convert("https://www.example.com");

FileStream fileStream = new FileStream("Sample.pdf", FileMode.CreateNew, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

Use the following code snippet to access a webpage using the HTTP GET method.

HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings settings = new BlinkConverterSettings();

//Set the BlinkBinaries folder path.
settings.BlinkPath = @"/BlinkBinaries/";

string url = "https://www.example.com";

Uri getMethodUri = new Uri(url);
string httpGetData = getMethodUri.Query.Length > 0 ? "&" : "?" + String.Format("{0}={1}", "firstName", "Andrew");

httpGetData += String.Format("&{0}={1}", "lastName", "Fuller");

string urlToConvert = url + httpGetData;

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = settings;

//Convert URL to PDF.
PdfDocument document = htmlConverter.Convert(urlToConvert);

FileStream fileStream = new FileStream("Sample.pdf", FileMode.CreateNew, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

HTML-to-PDF conversion with proxy

The Syncfusion HTML-to-PDF converter supports both system proxy and manual proxy.

System proxy

By default, the HTML-to-PDF converter for C# uses system proxy settings for converting HTML to PDF. If the proxy server is configured in the system, then the rendering engine automatically uses the same settings for the conversion.

Follow these steps to configure the system proxy settings:

  1. First, navigate to Control Panel > Network and Internet > Internet Options.
  2. From the Internet properties window, open LAN settings under the connections tab.
    Internet Properties Window
  3. Then, set the proxy server address and port in the LAN settings window.
    Local Area Network(LAN) Settings window

Manual proxy

You can specify the manual proxy settings for the conversion using the ProxySettings property.

Refer to the following code example to configure the manual proxy settings for the HTML-to-PDF conversion.

//Initialize the HTML to PDF converter with the Blink rendering engine.

HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings settings = new BlinkConverterSettings();

//Set the BlinkBinaries folder path.

settings.BlinkPath = @"/BlinkBinaries/";

//Set manual proxy settings.

settings.ProxySettings.HostName = "127.0.0.1";

settings.ProxySettings.PortNumber = 8080;

settings.ProxySettings.Type = BlinkProxyType.HTTP;

//Assign Blink converter settings to HTML converter.

htmlConverter.ConverterSettings = settings;

//Convert URL to PDF.

PdfDocument document = htmlConverter.Convert("https://www.google.com");

FileStream fileStream = new FileStream("Sample.pdf", FileMode.CreateNew, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

Virtual Viewport

You can adjust the HTML content size in a PDF using the ViewPortSize property of the HTML-to-PDF converter for C#.

Refer to the following code example to adjust the viewport size.

//Initialize the HTML to PDF converter with the Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();

//Set the BlinkBinaries folder path.
blinkConverterSettings.BlinkPath = @"/BlinkBinaries/";

//Set Blink viewport size.
blinkConverterSettings.ViewPortSize = new Size(800, 0);

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;

//Convert URL to PDF.
PdfDocument document = htmlConverter.Convert("https://www.google.com");

FileStream fileStream = new FileStream("Sample.pdf", FileMode.CreateNew, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

Additional delay

Additional delay is the waiting time of the converter to load external resources (styles, scripts, images, etc.). You can set that delay time using the AdditionalDelay property while converting HTML to PDF.

Refer to the following code example to set additional delay time.

//Initialize the HTML to PDF converter with the Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();

//Set the BlinkBinaries folder path.
blinkConverterSettings.BlinkPath = @"/BlinkBinaries/";

// Set additional delay; units in milliseconds.
blinkConverterSettings.AdditionalDelay = 3000;

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;

//Convert URL to PDF.
PdfDocument document = htmlConverter.Convert("https://www.google.com");

FileStream fileStream = new FileStream("Sample.pdf", FileMode.CreateNew, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

Add headers and footers

With the HTML-to-PDF converter for C#, you can place common content applicable for all the pages either in the header or the footer.

You can also add images, text, shapes, page numbers, and hyperlinks in the header and footers.

Note: For more information, refer to Working with Headers and Footers documentation.

Refer to the following code snippet.

using Syncfusion.Drawing;
using Syncfusion.HtmlConverter;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;

static void Main(string[] args)
  {
     //Initialize the HTML to PDF converter with the Blink rendering engine.
     HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

     BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();
     //Adding header.
     blinkConverterSettings.PdfHeader = CreateHeader();
     //Adding footer.
     blinkConverterSettings.PdfFooter = CreateFooter();

     //Set the BlinkBinaries folder path.
     blinkConverterSettings.BlinkPath = @"../../../../../BlinkBinariesWindows/";

     //Assign Blink converter settings to HTML converter.
     htmlConverter.ConverterSettings = blinkConverterSettings;

     //Convert HTML File to PDF.
     PdfDocument document = htmlConverter.Convert(Path.GetFullPath("../../../../../Data/html_file_converter.htm"));

     FileStream fileStream = new FileStream("Headers_and_Footers.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

     //Save and close the PDF document. 
     document.Save(fileStream);
     document.Close(true);
  }

  //Create header for HTML to PDF converter.
  public static PdfPageTemplateElement CreateHeader()
  {
      RectangleF bounds = new RectangleF(0, 0, PdfPageSize.A4.Width, 30);

      //Create a new page template and assigning the bounds.
      PdfPageTemplateElement header = new PdfPageTemplateElement(bounds);

      PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 14);

      PdfBrush brush = new PdfSolidBrush(Color.Black);

      string headerText = "Syncfusion HTML to PDF Converter";

      SizeF textSize = font.MeasureString(headerText);

      string date = DateTime.Now.ToString("dd/M/yyyy");

      //Create a text field to draw in header.
      PdfCompositeField compositeField = new PdfCompositeField(font, brush, headerText);
      //Drawing text field in header.
      compositeField.Draw(header.Graphics, new PointF((bounds.Width - textSize.Width) / 2, 5));
      //Drawing date text in header.
      header.Graphics.DrawString(date, font, brush, new PointF(10, 5));
      //Drawing line in header.
      header.Graphics.DrawLine(PdfPens.Gray, new PointF(0, bounds.Height - 2), new PointF(bounds.Width, bounds.Height - 2));

      return header;
  }

  //Create footer for HTML to PDF converter.
  public static PdfPageTemplateElement CreateFooter()
  {
      RectangleF bounds = new RectangleF(0, 0, PdfPageSize.A4.Width, 30);

      //Create a new page template and assigning the bounds.
      PdfPageTemplateElement footer = new PdfPageTemplateElement(bounds);

      PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 7);

      PdfBrush brush = new PdfSolidBrush(Color.Black);

      string footerText = "Copyright © 2001 - 2021 Syncfusion Inc. All Rights Reserved";

       SizeF textSize = font.MeasureString(footerText);

       //Create a text field to draw in the footer.
       PdfCompositeField compositeField = new PdfCompositeField(font, brush, footerText);

       //Create page number field to show page numbering in footer, this field automatically gets an update for each page.
       PdfPageNumberField pageNumber = new PdfPageNumberField(font, brush);
       PdfPageCountField count = new PdfPageCountField(font, brush);
       PdfCompositeField pageNumberField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumber, count);

       //Drawing line in footer.
       footer.Graphics.DrawLine(PdfPens.Gray, new PointF(0, 2), new PointF(bounds.Width, 2));
       //Drawing text field in footer
       compositeField.Draw(footer.Graphics, new PointF((bounds.Width - textSize.Width) / 2, 5));
       //Drawing page number field in footer.
       pageNumberField.Draw(footer.Graphics, new PointF((bounds.Width - 70), 5));

       return footer;
  }

By executing this example, you will get a PDF document like in the following image.

Add Headers and Footers while Converting HTML to PDF
Headers and Footers in Converting HTML to PDF

Automatically create a table of contents

A table of contents helps us easily navigate within a document while searching for a piece of specific information or a topic. With the help of the HTML-to-PDF converter, you can automatically create a table of contents in a PDF document using C#.

To do so, you just need to enable the EnableToc property in the converter settings. Then, the TOC will be automatically created from the <h> tag. There’s support for <h1> to <h6> header levels.

Refer to the following code example to automatically create a table of content in a PDF document.

//Initialize the HTML to PDF converter with the Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();

//Set the BlinkBinaries folder path.
blinkConverterSettings.BlinkPath = @"../../../../../BlinkBinariesWindows/";

//Enable automatic TOC creation.
blinkConverterSettings.EnableToc = true;

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;

//Convert HTML File to PDF.
PdfDocument document = htmlConverter.Convert("https://help.syncfusion.com/file-formats/pdf/convert-html-to-pdf/blink");

FileStream fileStream = new FileStream("toc_creation.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

By executing this example, you will get a PDF document like in the following image.

Creating a Table of Contents in HTML to PDF Conversion
Creating a Table of Contents in HTML to PDF Conversion

Customize the style of the TOC creation

You can also customize the style of the TOC using the HtmlToPdfTocStyle API.

Refer to the following code snippet to customize the level 1 (H1) heading in a TOC.

//Initialize the HTML to PDF converter with the Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();

//Set the BlinkBinaries folder path.
blinkConverterSettings.BlinkPath = @"../../../../../BlinkBinariesWindows/";

//Enable automatic TOC creation.
blinkConverterSettings.EnableToc = true;

//Set the style for level 1(H1) items in the table of contents.

HtmlToPdfTocStyle tocstyleH1 = new HtmlToPdfTocStyle();

tocstyleH1.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Regular);

tocstyleH1.BackgroundColor = new PdfSolidBrush(new PdfColor(Color.FromArgb(68, 114, 196)));

tocstyleH1.ForeColor = PdfBrushes.White;

tocstyleH1.Padding = new PdfPaddings(5, 5, 3, 3);

//Apply this style to level 1 (H1) headings of the TOC.
blinkConverterSettings.Toc.SetItemStyle(1, tocstyleH1);

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;

//Convert HTML File to PDF.
PdfDocument document = htmlConverter.Convert("https://help.syncfusion.com/file-formats/pdf/convert-html-to-pdf/blink");

FileStream fileStream = new FileStream("toc_creation.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

By executing this example, you will get a PDF document like in the following image.

Customizing the Style of a Table Of Contents
Customizing the Style of a Table Of Contents

Automatically create bookmark hierarchy

You can use bookmarks to navigate to various headings within a PDF document. With the help of the HTML-to-PDF converter, you can easily create a bookmark hierarchy.

For that, you just need to enable the EnableBookmarks property in the converter settings. Then, the bookmarks will be automatically created from the <h> tags. It provides support from <h1> to <h6> header levels.

Refer to the following code example to automatically create bookmarks in a PDF document.

//Initialize the HTML to PDF converter with the Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();

//Set the BlinkBinaries folder path.
blinkConverterSettings.BlinkPath = @"../../../../../BlinkBinariesWindows/";

//Enable automatic bookmark creation.
blinkConverterSettings.EnableBookmarks = true;

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;

//Convert HTML File to PDF.
PdfDocument document = htmlConverter.Convert("https://help.syncfusion.com/file-formats/pdf/convert-html-to-pdf/blink");

FileStream fileStream = new FileStream("bookmark_creation.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

By executing this example, you will get a PDF document like in the following image.

Creating Bookmark Hierarchy in a PDF
Creating Bookmark Hierarchy in a PDF

Encrypt PDFs with passwords

With the password-protection support in our HTML-to-PDF converter, you can keep sensitive information more secure.

Note: For more information, refer to Working with Security documentation.

Refer to the following code example to set a password to a converted PDF document.

//Initialize the HTML to PDF converter with the Blink rendering engine.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.Blink);

BlinkConverterSettings blinkConverterSettings = new BlinkConverterSettings();
blinkConverterSettings.ViewPortSize = new Syncfusion.Drawing.Size(800, 0);

//Set the BlinkBinaries folder path.
blinkConverterSettings.BlinkPath = @"../../../../../BlinkBinariesWindows/";

//Assign Blink converter settings to HTML converter.
htmlConverter.ConverterSettings = blinkConverterSettings;

//Convert particular div in a web page to PDF.
PdfDocument document = htmlConverter.Convert("https://www.syncfusion.com/");

//Set password to the PDF document.
document.Security.UserPassword = "syncfusion";
document.Security.Permissions = PdfPermissionsFlags.CopyContent | PdfPermissionsFlags.Print;

FileStream fileStream = new FileStream("Web_to_PDF_password.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite);

//Save and close the PDF document. 
document.Save(fileStream);
document.Close(true);

Resource

You can download all of these samples from the HTML-to-PDF document conversion in the C# demo.

Conclusion

Thanks for reading! In this blog post, we have learned the various ways to convert HTML content to a PDF document in C# using our Syncfusion HTML-to-PDF converter library. So, try out these methods and leave your feedback in the comments section of this blog post!

For existing customers, the new version of Essential Studio is available for download from the License and Downloads page. If you are not yet a Syncfusion customer, you can try our 30-day free trial to check out our available features.

You can also contact us through our support forum, Direct-Trac, or feedback portal. We are happy to assist you!

Related blogs

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top