Categories
JavaScript Answers

How to convert HTML to PDF with Node.js?

Spread the love

Sometimes, we want to convert HTML to PDF with Node.js.

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

How to convert HTML to PDF with Node.js?

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

To install it, we run

npm i html-pdf

Then we write

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


pdf.create(html, config).toFile('path/to/output/generated.pdf', (err, res) => {
  if (err) {
    return console.log(err);
  }
  console.log(res);
});

to call pdf.create with the html string to convert to a PDF.

And then we call toFile to write the PDF content to a file on disk.

The callback’s res parameter has the results of writing the PDF.

And err has the errors.

Conclusion

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

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 *