DEV Community

Jack9012
Jack9012

Posted on

Convert HTML to PDF in C#: A Chrome-Based Approach

Convert HTML to PDF
Converting HTML or web pages to PDF is a common requirement in business applications, from exporting reports and printing invoices to archiving web pages and generating PDFs from dynamic HTML content.

Common approaches include:

  1. HTML rendering libraries that work without a browser but offer limited support for complex CSS and JavaScript.
  2. Headless browser solutions such as PhantomJS or Puppeteer, which require deploying a browser engine.
  3. Rendering with a locally installed Chrome browser , which reuses Google Chrome on the target machine and uses its native rendering engine to handle modern CSS, JavaScript, images, fonts, and complex page layouts.

This article introduces the Spire.Additions.Chrome module included with Spire.PDF for Python . It wraps the process of exporting PDFs through a local Chrome installation, allowing you to convert a web page URL to PDF with just a few lines of C# code.

⚠️ Important prerequisites

  1. Install Google Chrome on the machine that will run the code, and locate the chrome.exe executable.
  2. Close all Chrome windows before running the application ; otherwise, the conversion will fail.
  3. Both web page URLs and local HTML files are supported.

Environment Setup

Install Spire.PDF for Python

The project requires Spire.PDF for Python. The Spire.Additions.Chrome namespace is included with the product, so no separate component needs to be installed.

Locate the Chrome Executable

The default Chrome installation path on Windows is:

C:\Program Files\Google\Chrome\Application\chrome.exe
Enter fullscreen mode Exit fullscreen mode

If Chrome is installed in a different directory, update the chromeLocation value in the code accordingly.

Complete C# Code Example

using Spire.Additions.Chrome;

namespace ConvertHtmlToPdfUsingChrome
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Input web page URL
            string inputUrl = @"https://www.example.com/webpage.html";

            // Output PDF file path
            string outputFile = @"HtmlToPDF.pdf";

            // Path to the local Chrome executable
            string chromeLocation = @"C:\Program Files\Google\Chrome\Application\chrome.exe";

            // Create a Chrome HTML converter instance
            ChromeHtmlConverter converter = new ChromeHtmlConverter(chromeLocation);

            // Configure conversion options
            ConvertOptions options = new ConvertOptions();

            // Set the conversion timeout in milliseconds
            options.Timeout = 10 * 3000;

            // Set the PDF page size and margins:
            // A4 paper in inches, with no margins
            options.PageSettings = new PageSettings()
            {
                PaperWidth = 8.27,
                PaperHeight = 11.69,
                MarginTop = 0,
                MarginLeft = 0,
                MarginRight = 0,
                MarginBottom = 0
            };

            // Convert the web page URL to PDF
            converter.ConvertToPdf(inputUrl, outputFile, options);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Understanding the Code

1. ChromeHtmlConverter

ChromeHtmlConverter is the main conversion class in the Spire.Additions.Chrome namespace, which is included with Spire.PDF for Python .

Its constructor accepts the path to chrome.exe, allowing the converter to launch the local Chrome browser in headless mode and render the page.

Note: Chrome must be closed when you run the code. The library automatically launches a headless Chrome process and closes it when the conversion finishes.

2. ConvertOptions

ConvertOptions controls the conversion settings:

  • Timeout: The conversion timeout in milliseconds. Increase this value for pages that take longer to load. In this example, 10 * 3000 sets a timeout of 30 seconds.
  • PageSettings: The PDF page dimensions and margins, measured in inches. The example uses A4 paper, measuring 8.27 × 11.69 inches, with all margins set to zero for edge-to-edge output.

You can change the width and height to use a custom paper size, or adjust the margin properties to add whitespace around the page content.

3. ConvertToPdf()

ConvertToPdf() performs the conversion. It accepts a web page URL and saves the resulting PDF to the specified local file path.

In addition to URLs, the API also supports local HTML file paths.

Advantages and Limitations

Advantages

  1. Native Chrome rendering Chrome’s rendering engine handles complex web pages, CSS3, dynamically rendered JavaScript content, SVG, and web fonts.
  2. No additional browser engine to bundle Reusing the Chrome installation on the target machine helps reduce the application’s package size.
  3. Simple configuration and API The converter avoids the need to write complex headless browser command-line arguments.
  4. Included with the product Spire.Additions.Chrome is built into Spire.PDF for Python and is available after installing the product.

Limitations

  1. Google Chrome must be installed on the target machine, and all Chrome windows must be closed during conversion.
  2. Server deployments require Chrome to be installed on the server. Container environments also require additional Chrome configuration.
  3. The solution depends on the locally installed browser version, so Chrome updates may affect compatibility.

Common Issues and Troubleshooting

1. Conversion Fails Because of a Chrome Process Conflict

Cause: One or more Chrome windows are still open.

Solution: Close all Chrome windows, then run the application again.

2. The Application Cannot Find chrome.exe

Cause: The configured path is incorrect, or Chrome is installed in a user-specific directory such as AppData\Local.

Solution: Locate chrome.exe in File Explorer and copy its actual path into the code.

3. The Output Is Blank or Images Are Missing

Check for network problems or page-loading timeouts. Increase options.Timeout if necessary.

Also check whether the page requires a login session or cookie-based authentication.

4. The Page Layout Looks Incorrect

Adjust the paper dimensions and margins in PageSettings.

Responsive layouts may also affect the output. If you control the HTML, consider adding print-specific CSS to improve the PDF layout.

Additional Notes on Spire.PDF for Python

Although the example above is written in C#, this Chrome-based HTML-to-PDF capability is provided by Spire.PDF for Python , with Spire.Additions.Chrome included as a built-in namespace. The Python API follows the same general design as the C# API.

The overall workflow is:

  • Install the Spire.PDF for Python package to access the namespace.
  • Install Chrome locally and close it before running the script.
  • Configure the Chrome path, page dimensions, and timeout, then call the conversion method to export the PDF.

Recommended Use Cases

This approach is suitable for:

  • Exporting web-based reports and preview pages from internal management systems.
  • Archiving static web pages, invoices, and other business documents as PDFs.
  • Generating PDFs that need to retain complex front-end layouts and web styling.

Conclusion

Combining the Spire.Additions.Chrome namespace included with Spire.PDF for Python and a local Google Chrome installation provides a straightforward way to convert HTML to PDF with minimal C# code.

Chrome’s rendering engine offers strong support for complex web pages compared with custom HTML rendering engines. The converter also provides a higher-level interface than Puppeteer, reducing the need to manage browser processes manually.

Top comments (0)