npm i puppeteer
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
const fs = require('fs'); const puppeteer = require('puppeteer'); const path = require('path'); async function htmlToPdf(htmlFilePath, outputPdfPath) { const browser = await puppeteer.launch(); const page = await browser.newPage(); // Read HTML content from file const htmlContent = fs.readFileSync(htmlFilePath, 'utf8'); await page.setContent(htmlContent, { waitUntil: 'domcontentloaded' }); // Create PDF await page.pdf({ path: outputPdfPath, format: 'A4', printBackground: true, }); await browser.close(); console.log(`✅ PDF created at ${outputPdfPath}`); } // Example usage const htmlFile = path.join(__dirname, 'template.html'); const pdfOutput = path.join(__dirname, 'output.pdf'); htmlToPdf(htmlFile, pdfOutput); |