Convert HTML to PDF in node.js
npm install @loudsrl/html-to-pdfA library for converting HTML with CSS to PDF.
This library uses Puppeteer to generate PDF's.
Some systems may work out of the box, others may not. To allow Puppeteer to spin up correctly, you may need to install some additional system dependencies.
For pointers on how to make puppeteer work in your environment, see https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md#running-puppeteer-in-docker
This library exports a method allowing conversion of HTML to PDF. When invoked with a valid HTML template as the first argument, a Buffer is returned containing a PDF document, along with the application/pdf mime type. The second argument is a configuration object, allowing customisation of Puppeteer, or the output of the PDF.
``ecmascript 6
const HTMLToPDF = require('convert-html-to-pdf').default;
const htmlToPDF = new HTMLToPDF(
);
htmlToPDF.convert()
.then((buffer) => {
// do something with the PDF file buffer
})
.catch((err) => {
// do something on error
});
`Or, if using async await:
`ecmascript 6
const HTMLToPDF = require('convert-html-to-pdf').default; const getPDF = async () => {
const htmlToPDF = new HTMLToPDF(
);
try {
const pdf = await htmlToPDF.convert();
// do something with the PDF file buffer
} catch (err) {
// do something on error
}
};
`For PDF's that should contain imagery or web fonts, it's recommended to base 64 encode any assets and embed within the markup using a data URI. This will yield faster results. If you'd rather request assets over HTTP, you can do this by enabling the
waitForNetworkIdle configuration option.##### Example of an asset encoded as base 64
`ecmascript 6
const HTMLToPDF = require('convert-html-to-pdf').default;
const htmlToPDF = new HTMLToPDF(