Categories
JavaScript Answers

How to convert HTML to PDF with Node.js and JavaScript?

Spread the love

To convert HTML to PDF with Node.js and JavaScript, we use the html-pdf-node package.

To install it, we run

npm i html-pdf-node

Then we write

const htmlToPdf = require("html-pdf-node");

const options = { format: "A4" };
const file = { content: "<h1>Welcome to html-pdf-node</h1>" };
const pdfBuffer = await htmlToPdf.generatePdf(file, options);
console.log("PDF Buffer:-", pdfBuffer);

to convert the file.content string into a buffer with the PDF file with the generatePdf function.

We can also write

const htmlToPdf = require("html-pdf-node");

const options = { format: "A4" };
const file = { url: "https://example.com" };
const pdfBuffer = await htmlToPdf.generatePdf(file, options);
console.log("PDF Buffer:-", pdfBuffer);

to call generatePdf to get the PDF from the file.url URL and convert that to a PDF buffer.

A promise is returned so we use await to get the pdfBuffer.

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 *