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 28 29 30 31 32 33 34 35 36 37 38 |
const fs = require('fs'); const puppeteer = require('puppeteer'); const path = require('path'); const inputSVG = process.argv[2]; const outputPDF = process.argv[3] || 'output.pdf'; (async () => { if (!inputSVG) { console.error(' process.exit(1); } const svgContent = fs.readFileSync(inputSVG, 'utf-8'); const htmlContent = `<html><body style="margin:0;">${svgContent}</body></html>`; const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.setContent(htmlContent, { waitUntil: 'networkidle0' }); const dimensions = await page.evaluate(() => { const svg = document.querySelector('svg'); return { width: svg.getAttribute('width') || '800px', height: svg.getAttribute('height') || '600px', }; }); await page.pdf({ path: outputPDF, width: dimensions.width, height: dimensions.height, printBackground: true }); await browser.close(); console.log(` })(); |