To convert HTML to PDF with Node.js, 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 use it by importing the library.
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.