ff-admin-server/src/helpers/pdfExport.ts

54 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-10-18 15:23:51 +02:00
import { readFileSync } from "fs";
2024-12-21 10:18:07 +01:00
import Handlebars from "handlebars";
import puppeteer from "puppeteer";
2024-10-18 15:23:51 +02:00
export abstract class PdfExport {
static getTemplate(template: string) {
return readFileSync(process.cwd() + "/src/templates/" + template, "utf8");
}
2024-10-19 16:24:41 +02:00
static async renderFile({
template,
2024-12-21 10:18:07 +01:00
title = "pdf-export Mitgliederverwaltung",
2024-10-19 16:24:41 +02:00
filename,
data,
}: {
template: string;
title: string;
filename: string;
data: any;
}) {
2024-12-21 10:18:07 +01:00
const templateHtml = this.getTemplate(template);
const templateCompiled = Handlebars.compile(templateHtml);
const html = templateCompiled(data);
const browser = await puppeteer.launch({
headless: true,
args: ["--no-sandbox", "--disable-gpu", "--disable-setuid-sandbox"],
});
const page = await browser.newPage();
await page.setContent(html, { waitUntil: "domcontentloaded" });
await page.pdf({
path: process.cwd() + `/export/${filename}.pdf`, // Name der PDF-Datei
format: "A4",
printBackground: false,
margin: {
top: "15mm",
bottom: "15mm",
left: "10mm",
right: "10mm",
},
displayHeaderFooter: true,
headerTemplate: `<h1 style="font-size:10px; text-align:center; width:100%;">${title}</h1>`,
footerTemplate: `
<div style="font-size:10px; text-align:center; width:100%; color:#888;">
Seite <span class="pageNumber"></span> von <span class="totalPages"></span>
</div>
`,
});
2024-10-18 15:23:51 +02:00
2024-12-21 10:18:07 +01:00
await browser.close();
2024-10-18 15:23:51 +02:00
}
}