Files
mrp/server/src/lib/pdf.ts

38 lines
1.1 KiB
TypeScript
Raw Normal View History

2026-03-19 16:38:41 -05:00
import puppeteer, { PaperFormat } from "puppeteer";
2026-03-14 14:44:40 -05:00
import { env } from "../config/env.js";
2026-03-19 16:38:41 -05:00
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) {
2026-03-14 14:44:40 -05:00
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" });
2026-03-15 00:00:13 -05:00
const pdf = await page.pdf({
2026-03-19 16:38:41 -05:00
format: options?.width || options?.height ? undefined : (options?.format || "A4"),
width: options?.width,
height: options?.height,
margin: options?.margin,
2026-03-14 14:44:40 -05:00
printBackground: true,
preferCSSPageSize: true,
});
2026-03-15 00:00:13 -05:00
// Normalize Puppeteer's Uint8Array output to a Node Buffer so Express sends a valid PDF payload.
return Buffer.from(pdf);
2026-03-14 14:44:40 -05:00
} finally {
await browser.close();
}
}