45 lines
1.2 KiB
JavaScript
45 lines
1.2 KiB
JavaScript
import puppeteer from 'puppeteer';
|
|
import { resolve, basename } from 'path';
|
|
import { existsSync, mkdirSync } from 'fs';
|
|
import { fileURLToPath } from 'url';
|
|
|
|
const OUTPUT_DIR = resolve(fileURLToPath(import.meta.url), '../../../output/pdf');
|
|
|
|
async function generatePdf(htmlPath) {
|
|
const absolutePath = resolve(htmlPath);
|
|
if (!existsSync(absolutePath)) {
|
|
console.error(`File not found: ${absolutePath}`);
|
|
process.exit(1);
|
|
}
|
|
|
|
mkdirSync(OUTPUT_DIR, { recursive: true });
|
|
|
|
const pdfName = basename(absolutePath, '.html') + '.pdf';
|
|
const pdfPath = resolve(OUTPUT_DIR, pdfName);
|
|
|
|
const browser = await puppeteer.launch({ headless: true });
|
|
const page = await browser.newPage();
|
|
|
|
await page.goto(`file://${absolutePath}`, { waitUntil: 'networkidle0' });
|
|
|
|
await page.pdf({
|
|
path: pdfPath,
|
|
format: 'A4',
|
|
printBackground: true,
|
|
margin: { top: 0, right: 0, bottom: 0, left: 0 },
|
|
preferCSSPageSize: true,
|
|
});
|
|
|
|
await browser.close();
|
|
console.log(`PDF generated: ${pdfPath}`);
|
|
return pdfPath;
|
|
}
|
|
|
|
const htmlFile = process.argv[2];
|
|
if (!htmlFile) {
|
|
console.error('Usage: node generate-pdf.mjs <html-file>');
|
|
process.exit(1);
|
|
}
|
|
|
|
generatePdf(htmlFile);
|