htmlpdfs / puppeteer_pdf.js
ABDALLALSWAITI's picture
Update puppeteer_pdf.js
a534d05 verified
Raw
History Blame
2.86 kB
#!/usr/bin/env node
const puppeteer = require('puppeteer');
const fs = require('fs');
const [htmlFile, aspectRatio] = process.argv.slice(2);
if (!htmlFile || !aspectRatio) {
console.error('Usage: node puppeteer_pdf.js <html_file> <aspect_ratio>');
process.exit(1);
}
(async () => {
let browser;
try {
console.log('Starting Puppeteer...');
browser = await puppeteer.launch({
headless: 'new',
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || '/usr/bin/chromium',
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-gpu',
'--no-first-run',
'--no-zygote',
'--single-process'
]
});
const page = await browser.newPage();
// Set viewport based on aspect ratio
let width = 1920, height = 1080;
if (aspectRatio === '9:16') {
width = 1080;
height = 1920;
} else if (aspectRatio === '1:1') {
width = 1080;
height = 1080;
}
await page.setViewport({ width, height, deviceScaleFactor: 1 });
console.log(`Viewport set to ${width}x${height}`);
// Load HTML
const html = fs.readFileSync(htmlFile, 'utf8');
await page.setContent(html, {
waitUntil: 'networkidle0',
timeout: 30000
});
console.log('HTML loaded');
// Wait for fonts and images
await page.evaluate(() => document.fonts.ready);
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('Resources loaded');
// PDF options
const pdfPath = htmlFile.replace('.html', '.pdf');
const options = {
path: pdfPath,
printBackground: true,
preferCSSPageSize: true,
margin: { top: 0, right: 0, bottom: 0, left: 0 }
};
if (aspectRatio === '16:9') {
options.format = 'A4';
options.landscape = true;
console.log('Format: A4 Landscape');
} else if (aspectRatio === '1:1') {
options.width = '210mm';
options.height = '210mm';
console.log('Format: Square 210x210mm');
} else {
options.format = 'A4';
options.landscape = false;
console.log('Format: A4 Portrait');
}
// Generate PDF
await page.pdf(options);
console.log(`PDF created: ${pdfPath}`);
process.exit(0);
} catch (error) {
console.error('Error:', error.message);
process.exit(1);
} finally {
if (browser) {
await browser.close();
}
}
})();