56 lines
1.6 KiB
JavaScript
56 lines
1.6 KiB
JavaScript
import log4js from 'log4js';
|
|
import { loadConfig } from '../config.js';
|
|
|
|
const config = loadConfig();
|
|
const logger = log4js.getLogger('PDF Factory');
|
|
logger.level = config.server.logLevel;
|
|
|
|
/**
|
|
* Generates a PDF from HTML content using Puppeteer
|
|
* @param {string} html - The HTML content to convert to PDF
|
|
* @param {Object} options - PDF generation options
|
|
* @param {number} options.width - Document width in mm
|
|
* @param {number} options.height - Document height in mm
|
|
* @returns {Promise<Buffer>} The PDF buffer
|
|
*/
|
|
export async function generatePDF(html, options = {}) {
|
|
try {
|
|
// Dynamically import puppeteer to handle cases where it might not be installed
|
|
const puppeteer = await import('puppeteer');
|
|
|
|
const browser = await puppeteer.default.launch({
|
|
headless: true,
|
|
args: ['--no-sandbox', '--disable-setuid-sandbox']
|
|
});
|
|
|
|
const page = await browser.newPage();
|
|
|
|
// Set content with HTML
|
|
await page.setContent(html, {
|
|
waitUntil: 'networkidle0'
|
|
});
|
|
|
|
// Generate PDF with specified dimensions
|
|
const pdfBuffer = await page.pdf({
|
|
format: options.format || undefined,
|
|
width: options.width ? `${options.width}mm` : undefined,
|
|
height: options.height ? `${options.height}mm` : undefined,
|
|
printBackground: true,
|
|
preferCSSPageSize: true,
|
|
margin: {
|
|
top: '0mm',
|
|
right: '0mm',
|
|
bottom: '0mm',
|
|
left: '0mm'
|
|
}
|
|
});
|
|
|
|
await browser.close();
|
|
|
|
return pdfBuffer;
|
|
} catch (error) {
|
|
logger.error('Error generating PDF:', error.message);
|
|
throw error;
|
|
}
|
|
}
|