Categories
JavaScript Answers

How to convert HTML to PDF with Node.js?

Spread the love

To convert HTML to PDF with Node.js, we use Puppeteer.

For instance, we write

const puppeteer = require("puppeteer");
const handlebars = require("handlebars");

module.exports.htmlToPdf = async ({ templateHtml, dataBinding, options }) => {
  const template = handlebars.compile(templateHtml);
  const finalHtml = encodeURIComponent(template(dataBinding));

  const browser = await puppeteer.launch({
    args: ["--no-sandbox"],
    headless: true,
  });
  const page = await browser.newPage();
  await page.goto(`data:text/html;charset=UTF-8,${finalHtml}`, {
    waitUntil: "networkidle0",
  });
  await page.pdf(options);
  await browser.close();
};

to define the htmlToPdf function.

In it, we call launch to start a browser.

We call page.goto to go to the URL of the page we want to convert to a PDF.

Next we call pdf to convert it to a PDF.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *