38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
import puppeteer, { PaperFormat } from "puppeteer";
|
|
|
|
import { env } from "../config/env.js";
|
|
|
|
interface PdfOptions {
|
|
format?: PaperFormat;
|
|
width?: string;
|
|
height?: string;
|
|
margin?: { top?: string; right?: string; bottom?: string; left?: string };
|
|
}
|
|
|
|
export async function renderPdf(html: string, options?: PdfOptions) {
|
|
const browser = await puppeteer.launch({
|
|
executablePath: env.PUPPETEER_EXECUTABLE_PATH,
|
|
headless: true,
|
|
args: ["--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage"],
|
|
});
|
|
|
|
try {
|
|
const page = await browser.newPage();
|
|
await page.setContent(html, { waitUntil: "networkidle0" });
|
|
|
|
const pdf = await page.pdf({
|
|
format: options?.width || options?.height ? undefined : (options?.format || "A4"),
|
|
width: options?.width,
|
|
height: options?.height,
|
|
margin: options?.margin,
|
|
printBackground: true,
|
|
preferCSSPageSize: true,
|
|
});
|
|
|
|
// Normalize Puppeteer's Uint8Array output to a Node Buffer so Express sends a valid PDF payload.
|
|
return Buffer.from(pdf);
|
|
} finally {
|
|
await browser.close();
|
|
}
|
|
}
|