Effective Methods to Convert HTML to PDF in C#

cover page of converting html to pdf with c#

Converting HTML to PDF is a common task for developers who need to generate printable documents or preserve web content offline. With Spire.PDF for .NET, developers can achieve this conversion through multiple approaches that suit different environments. Whether you prefer using the built-in HTML-to-PDF capabilities with the QT plugin, or you want more control through ChromeHtmlConverter, Spire.PDF provides flexible solutions. This tutorial covers several ways to convert HTML to PDF using C# in .NET applications.

Method Best For Features
1. Convert HTML/URL to PDF With QT Plugin Developers who seek quick setup with minimal customization Login session support; Shorter code with faster conversion process
2. ChromeHtmlConverter with Output Logs Developers who need high-fidelity output and diagnostics Pixel-perfect rendering; Executes JS and dynamic content; Logs useful for debugging

Convert HTML/URL to PDF with QT Plugin

Before guiding you to the specific code sample of how to convert HTML files to PDF format, let me introduce Spire.PDF for .NET to you. It is a powerful C# library designed for creating, editing, and converting PDF documents. Except for HTML to PDF conversion, you can also use it to add digital signatures, create PDF Portfolios, extract elements like texts and images, and PDF file merging and splitting.

More reasons to help you choose Spire.PDF for .NET:

  • Compress PDF files from 10 – 100 times to reduce file size
  • Widely compatibility of C# environments
  • Add encryption to PDF files to protect your file privacy
  • More features waiting for you to explore...

To run the conversion process smoothly, you should use the C# API with QT plugin. In the following content, you will learn the step-by-step tutorial.

Step 1. Download Spire.PDF for .NET code library from the official download page to add it in your C# program.

Tip: To unlock all powerful functions of Spire.PDF, please request a 30-day trial license for yourself.

Step 2. Download the plugin on your computer. You can click the following link according to your own computer system.

Step 3. After downloading, unzip package somewhere on your disk to get the "plugins" folder like the pic shows below.

result of converting word to pdf with spire doc for java

We recommend that you set the "Platform target" of your project to x64 or x86 accordingly.

result of converting word to pdf with spire doc for java

Step 4. After adding the plugin, you just need to copy the following code sample to manage the conversion process.

If you have the original HTML file, copy the following code to your C# program:

using System.IO;
using Spire.Additions.Qt; 
using System.Drawing;
using Spire.Pdf.Graphics;

namespace ConvertHtmlStringToPdfWithPlugin
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get the HTML string from a .html file
            string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");

            //Specify the output file path
            string fileName = "HtmlStringToPdf.pdf";

            //Specify the plugin path
            string pluginPath = "F:\\Libraries\\Plugin\\plugins-windows-x64\\plugins";

            //Set plugin path
            HtmlConverter.PluginPath = pluginPath;

            //Convert HTML string to PDF
            HtmlConverter.Convert(htmlString, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0), LoadHtmlType.SourceCode);       
        }
    }
}

If you only get the URL, the code sample below is what you need:

using Spire.Pdf.Graphics;
using Spire.Additions.Qt; 
using System.Drawing;

namespace ConvertUrlToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Specify the URL path
            string url = "https://www.wikipedia.org/";

            //Specify the output file path
            string fileName = "UrlToPdf.pdf";

            //Specify the plugin path
             string pluginPath = "F:\\Libraries\\Plugin\\plugins-windows-x64\\plugins";

            //Set the plugin path
             HtmlConverter.PluginPath = pluginPath;

            //Convert URL to PDF
            HtmlConverter.Convert(url, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0));
        }
    }
}

RESULT:

result of converting word to pdf with spire doc for java

Convert HTML to PDF using ChromeHtmlConverter with Output Logs

Unlike standard conversion methods that rely solely on engine defaults or basic libraries, ChromeHtmlConverter leverages the power of a headless Chrome browser to render HTML content exactly as it appears in a real browser environment. It provides output logs, which are essential for diagnosing rendering issues, monitoring conversion performance, or maintaining compliance in production environments.

Let's now look at the specific code to use Spire.PDF for .NET and ChromeHtmlConverter to manage this conversion:

using Spire.Additions.Chrome;

namespace ConvertHtmlToPdfUsingChrome
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Specify the input URL and output PDF file path
            string inputUrl = @"https://www.e-iceblue.com/Tutorials/Spire.PDF/Spire.PDF-Program-Guide/C-/VB.NET-Convert-Image-to-PDF.html";
            string outputFile = @"HtmlToPDF.pdf";

            // Specify the log file path
            string logFilePath = @"Logs.txt";

            //Specify the path to the Chrome plugin
            string chromeLocation = @"C:\Program Files\Google\Chrome\Application\chrome.exe";

            //Create an instance of the ChromeHtmlConverter class
            ChromeHtmlConverter converter = new ChromeHtmlConverter(chromeLocation);
            //Enable logging
            converter.Logger = new Logger(logFilePath);

            //Create an instance of the ConvertOptions class
            ConvertOptions options = new ConvertOptions();
            //Set conversion timeout
            options.Timeout = 10 * 3000;
            //Set paper size and page margins of the converted PDF
            options.PageSettings = new PageSettings()
            {
                PaperWidth = 8.27,
                PaperHeight = 11.69,
                MarginTop = 0,
                MarginLeft = 0,
                MarginRight = 0,
                MarginBottom = 0

            };

            //Convert the URL to PDF
            converter.ConvertToPdf(inputUrl, outputFile, options);
        }
    }
}

The output log looks like below:

main interface of cloudxdocs online word to pdf converter

Read more details with the following post:

Convert HTML to PDF using ChromeHtmlConverter

Conclusion:

Spire.PDF for .NET offers a range of tools to convert HTML/URL to PDF in C#, whether you're dealing with local HTML files or remote web pages. Depending on your project requirements—such as rendering complexity, output quality, or dependency preferences, you can select the most suitable method.