Menu Close

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

Convert HTML to PDF with Node.js

In this article, we’ll look at how to convert HTML to PDF with Node.js and JavaScript.

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

To use the library, we first install it by running:

npm i html-pdf 

Then, we can write:

const pdf = require('html-pdf');

const html = '<b>Hello World</b>';
const options = {
    format: 'Letter'
}

pdf.create(html, options).toFile('./pdfname.pdf', (err, res) => {
    if (err) {
        console.log(err);
    }
}); 

to import the html-pdf package.

Then we add the html variable with the HTML string that we want to convert to a PDF file.

Next, set the options variable to an object that has some options for how to render the PDF.

Then we call pdf.create with html and options to render the HTML into a PDF with the given options.

The toFile method takes the file path to save the PDF to and a callback that runs when the PDF conversion is done.

err is defined when there’s an error with converting the PDF.

Therefore, we should see hello world in bold in the rendered PDF.

Posted in JavaScript, NodeJs, NPM

You can also read...