How to Convert HTML to PDF Using html-pdf-chrome

Apr 4, 2024 | Programming

If you’ve ever needed to convert HTML content into a PDF document, you understand the struggle of navigating through multiple libraries and formats. Enter html-pdf-chrome, a remarkable tool that utilizes Chrome or Chromium to seamlessly convert HTML into PDF and image formats (like JPEG, PNG, or WebP). This article will guide you through the setup process, usage details, and some troubleshooting tips.

Prerequisites

  • Latest version of Chrome or Chromium
  • Windows, macOS, or Linux operating systems
  • A currently supported version of Node.js

Installation

To get started, install the package using npm by running the following command:

bash
npm install --save html-pdf-chrome

Understanding the Code: An Analogy

Imagine you are a chef in a kitchen, and your task is to prepare a dish using various ingredients. In this analogy, html-pdf-chrome acts as the elegant cooking appliance that simplifies your task.

The code you write is akin to your recipe. The raw HTML input is like your fresh ingredients, and Chrome is your stove, heating everything up to bring your dish to life. Just like fine-tuning the temperature or cooking time can enhance the meal, customizing your options can produce the highest quality PDF output or image. Now, let’s dive into the specifics of using our handy kitchen tool.

Usage

It’s recommended to keep Chrome running alongside your Node.js process to enhance efficiency. This will prevent overhead from restarting Chrome each time a PDF is generated.

To maintain Chrome on the side, consider using pm2. This will ensure that Chrome restarts automatically if it crashes:

bash
# Install pm2 globally
npm install -g pm2

# Start Chrome
pm2 start google-chrome \
  --interpreter none \
  -- --headless \
  --disable-gpu \
  --disable-translate \
  --disable-extensions \
  --safebrowsing-disable-auto-update \
  --disable-sync \
  --remote-debugging-port=

Generating Your PDF

Here is how you can convert your HTML to a PDF file:

javascript
const htmlPdf = require('html-pdf-chrome');

const html = '

Hello, world!

'; const options = { port: 9222 }; // Port Chrome is listening on htmlPdf.create(html, options).then((pdf) => { pdf.toFile('test.pdf'); });

Saving as a Screenshot

To save your page as a screenshot instead of a PDF, you can supply screenshotOptions. Here is an example:

javascript
const htmlPdf = require('html-pdf-chrome');

const html = '

Hello, world!

'; const options = { port: 9222, screenshotOptions: { format: 'png', quality: 100 } }; htmlPdf.create(html, options).then((pdf) => { pdf.toFile('test.png'); });

Customization Options

You can also customize HTTP headers, add custom headers and footers, and control the behavior of the PDF rendering:

javascript
const options = {
  port: 9222,
  extraHTTPHeaders: {
    Authorization: 'Bearer YOUR_TOKEN',
    'X-Custom-Test-Header': 'This is great!'
  },
  printOptions: {
    displayHeaderFooter: true,
    headerTemplate: '
Page of
', footerTemplate: '
Custom footer!
' } }; const pdf = await htmlPdf.create(html, options);

Troubleshooting Tips

If you encounter issues such as CORS restrictions, try using the --disable-web-security Chrome flag. This should be done cautiously and only when you fully trust the code being executed.

While working on your projects, keep the following in mind:

  • If Chrome crashes, make sure you have pm2 running to restart it automatically.
  • Ensure that you have the correct port specified both when starting Chrome and in your implementation.
  • Check that all Node.js dependencies are properly installed.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Conclusion

The html-pdf-chrome library provides a streamlined process for converting HTML into both PDFs and images. Its flexibility to handle various customization options makes it a powerful tool for developers and businesses alike.

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox