UNPKG

html-pdf-js

Version:

`html-pdf-js` is a JavaScript library that enables the generation of PDF documents from HTML content using JavaScript. It leverages the power of the HTML5 canvas and PDF.js to render and convert HTML pages into PDF files, making it an ideal tool for gener

50 lines (44 loc) 2.16 kB
const puppeteer = require('puppeteer'); const pdfGenerator = { htmlToPdf: async (pdfPath = '', htmlTemplate = null, options = {}) => { const { format = 'A4', margin = { top: '0in', bottom: '0in', left: '0in', right: '0in' }, waitUntil = 'networkidle0', } = options; return new Promise(async (resolve, reject) => { try { if (!pdfPath) { throw new Error(`Please provide pdf save path`); } if (!htmlTemplate) { throw new Error(`Please provide html code to generate PDF.`); } // const browser = await puppeteer.launch(); const browser = await puppeteer.launch({ headless: 'new', // Ensure headless mode is used // headless: true, args: [ '--no-sandbox', // Disables sandboxing for compatibility with certain servers '--disable-setuid-sandbox', // Prevents privilege escalation issues '--disable-dev-shm-usage', // Avoids shared memory issues '--disable-accelerated-2d-canvas', // Optimizes performance '--no-first-run', // Avoids unnecessary initial configurations '--no-zygote', // Disables zygote process creation '--single-process', // Runs Chromium as a single process '--disable-gpu' // Ensures compatibility with non-GPU environments ], }); const page = await browser.newPage(); await page.setContent(htmlTemplate, { waitUntil }); await page.pdf({ path: pdfPath, format, margin }); await browser.close(); resolve(pdfPath); } catch (e) { console.error('error in htmlToPdf function =----->> ', e); reject(e); } }); }, }; module.exports = pdfGenerator;