HTML-to-PDF Conversion in C# – A Complete Guide
Tags: csharp, dotnet, html, pdf
Published: 2021-08-05 10:55:55

---
title: HTML-to-PDF Conversion in C# – A Complete Guide
published: true
date: 2021-08-03 11:04:41 UTC
tags: csharp, dotnet, html, pdf
canonical_url: https://www.syncfusion.com/blogs/post/html-to-pdf-conversion-in-csharp.aspx
cover_image: https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/HTML-to-PDF-Conversion-in-C-A-Complete-Guide-672x372.png
---

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](https://www.syncfusion.com/pdf-framework/net/html-to-pdf "Link to the 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](https://en.wikipedia.org/wiki/Blink_(browser_engine) "Link to Blink (browser engine) Wikipedia page") and [WebKit](https://en.wikipedia.org/wiki/WebKit "Link to WebKit Wikipedia page") 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](#install-and-configure-the-html-to-pdf-converter)
- [Convert HTML File to PDF](#convert-html-to-pdf)
- [Convert existing URL to PDF](#convert-url-to-pdf)
- [Convert ASP.NET Core Web Razor page to PDF](#convert-asp-net-core-web-razor-page-to-pdf)
- [Convert ASP.NET Core MVC view to PDF](#convert-asp-net-core-mvc-view-to-pdf)
- [Convert HTML forms to fillable PDF Forms](#convert-html-forms-to-pdf-forms)
- [Convert a part of a webpage to PDF](#convert-part-of-webpage-to-pdf)
- [Convert authenticated webpage to PDF](#convert-authenticated-webpage-to-pdf)
- [HTTP GET and POST](#http-get-and-post)
- [HTML-to-PDF conversion with proxy](#html-to-pdf-with-proxy)
- [Virtual viewport](#virtual-viewport)
- [Additional delay](#additional-delay)
- [Add headers and footers](#add-headers-and-footers)
- [Automatically create a table of contents](#create-toc-in-html-to-pdf-conversion)
- [Automatically create bookmark hierarchy](#create-bookmark-hierarchy)
- [Encrypt PDF with a password](#encrypt-pdf-with-password)

## 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](https://docs.microsoft.com/en-us/dotnet/core/tutorials/with-visual-studio "Link to Tutorial: Create a .NET console application using Visual Studio").
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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Select-the-Manage-NuGet-Packages-option.png)
3. Now, search for the [Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Windows](https://www.nuget.org/packages/Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Windows/ "Link to the Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Windows NuGet package") package and then install it. This NuGet package is for Windows.  
For Linux platform: [Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Linux](https://www.nuget.org/packages/Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Linux/ "Link to the Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Linux NuGet package").  
For Mac platform: [Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Mac](https://www.nuget.org/packages/Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Mac/ "Link to the Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Mac NuGet package").  
 ![Install the Syncfusion.HtmlToPdfConverter.Blink.Net.Core.Windows package](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Install-the-Syncfusion.HtmlToPdfConverter.Blink_.Net_.Core_.Windows-package.png)

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 path](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Copy-the-blink-binaries-to-your-local-project-path.png)Refer to the following code to convert HTML string to PDF.
```csharp
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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Converting-a-HTML-String-to-PDF.png)<figcaption>Converting an HTML String to PDF</figcaption>

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

```csharp
//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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Converting-a-HTML-File-to-PDF.png)<figcaption>Converting an HTML File to PDF</figcaption>

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

```csharp
//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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Converting-Existing-URL-to-PDF.png)<figcaption>Converting Existing Website URL to PDF</figcaption>

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

```csharp
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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/converting-an-ASP.NET-core-Web-Razor-page-to-PDF.png)<figcaption>Converting an ASP.NET Core Web Razor Page to PDF</figcaption>

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

```csharp
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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Converting-an-ASP.NET-Core-MVC-View-to-PDF.png)<figcaption>Converting an ASP.NET Core MVC View to PDF</figcaption>

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

```csharp
//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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Converting-HTML-Forms-to-Fillable-PDF-Forms.png)<figcaption>Converting HTML Forms to Fillable PDF Forms</figcaption>

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

```csharp
//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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Converting-the-HTML-elements-to-PDF.png)<figcaption>Converting HTML Elements to PDF</figcaption>

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

```csharp
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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Converting-a-webpage-with-form-authentication-to-PDF.png)<figcaption>Converting a Webpage with Form Authentication to PDF</figcaption>

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

```csharp
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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Converting-a-Webpage-with-Windows-Authentication-to-PDF.png)<figcaption>Converting a Webpage with Windows Authentication to PDF</figcaption>

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

```csharp
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.

```csharp
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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Internet-Properties-Window.png)
3. Then, set the proxy server address and port in the LAN settings window.  
 ![Local Area Network(LAN) Settings window](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Local-Area-NetworkLAN-Settings-window.png)

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

```csharp
//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.

```csharp
//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.

```csharp
//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](https://help.syncfusion.com/file-formats/pdf/working-with-headers-and-footers "Link to Working with Headers and Footers documentation").

Refer to the following code snippet.

```csharp
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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Add-Headers-and-Footers-while-Converting-HTML-to-PDF.png)<figcaption>Headers and Footers in Converting HTML to PDF</figcaption>

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

```csharp
//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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Automatically-Creating-Table-of-Contents-in-HTML-to-PDF-Conversion.png)<figcaption>Creating a Table of Contents in HTML to PDF Conversion</figcaption>

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

```csharp
//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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Customizing-the-Style-of-TOC-Creation.png)<figcaption>Customizing the Style of a Table Of Contents</figcaption>

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

```csharp
//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](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Creating-Bookmark-Hierarchy-in-a-PDF.png)<figcaption>Creating Bookmark Hierarchy in a PDF</figcaption>

## 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](https://help.syncfusion.com/file-formats/pdf/working-with-security "Link to Working with Security documentation").

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

```csharp
//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#](https://github.com/SyncfusionExamples/html_to_pdf_conversion "Link to HTML-to-PDF document conversion in C# demo on GitHub") 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](https://www.syncfusion.com/pdf-framework/net/html-to-pdf "Link to the HTML-To-PDF converter"). 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](https://www.syncfusion.com/account/downloads "Link to license and download page of Essential Studio") page. If you are not yet a Syncfusion customer, you can try our 30-day [free trial](https://www.syncfusion.com/downloads "Link to the free evaluation of the Syncfusion Essential Studio") to check out our available features.

You can also contact us through our [support forum](https://www.syncfusion.com/forums "Link to the Syncfusion support forum"), [Direct-Trac](https://www.syncfusion.com/support/directtrac "Link to the Syncfusion support system Direct Trac"), or [feedback portal](https://www.syncfusion.com/feedback/pdf "Link to Syncfusion Feedback Portal"). We are happy to assist you!

## Related blogs

- [Create and Validate PDF Digital Signatures in C#](https://www.syncfusion.com/blogs/post/create-validate-pdf-digital-signatures-csharp.aspx "Link to Digitally Sign and Verify Signatures in PDF Files Using C#: A Complete Guide blog")
- [How to Find Corrupted PDF Files in C# Easily](https://dev.to/syncfusion/how-to-find-corrupted-pdf-files-in-c-easily-16hi "Link to How to Find Corrupted PDF Files in C# Easily blog")
- [How to Convert an Image to PDF in ASP.NET Core](https://www.syncfusion.com/blogs/post/how-to-convert-image-to-pdf-in-asp-net-core.aspx "Link to How to Convert Image to PDF in ASP.NET Core blog")
- [Easy Ways to Redact PDFs Using C#](https://www.syncfusion.com/blogs/post/easy-ways-to-redact-pdfs-using-c.aspx "Link to Easy Ways to Redact PDFs Using C# blog")
- [7 Ways to Compress PDF Files in C#, VB.NET](https://www.syncfusion.com/blogs/post/7-ways-to-compress-pdf-files.aspx "Link to 7 Ways to Compress PDF Files in C#, VB.NET blog")