Files
scrollsmith/generatePDF.js
Madison Grubb 96480a351f
Some checks failed
ci/woodpecker/cron/ci Pipeline failed
make it start working again
2025-12-11 23:13:07 -05:00

45 lines
1.2 KiB
JavaScript

import puppeteer from "puppeteer";
import { dungeonTemplate } from "./dungeonTemplate.js";
import fs from "fs/promises";
export async function generatePDF(data, outputPath = "dungeon.pdf") {
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
const page = await browser.newPage();
const toBase64DataUrl = (buffer) =>
`data:image/png;base64,${buffer.toString("base64")}`;
const readImageData = async (path) =>
fs
.readFile(path)
.then(toBase64DataUrl)
.catch(() => {
console.warn(
"Warning: Could not read image file, proceeding without map in PDF",
);
return null;
});
const imageData = data.map ? await readImageData(data.map) : null;
const dataWithImage = imageData
? { ...data, map: imageData }
: (({ map, ...rest }) => rest)(data);
const html = dungeonTemplate(dataWithImage);
await page.setContent(html, { waitUntil: "networkidle0" });
await page.pdf({
path: outputPath,
format: "A4",
landscape: true,
printBackground: true,
preferCSSPageSize: true,
});
await browser.close();
console.log(`Dungeon PDF saved to ${outputPath}`);
}