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
.