Files
wpep/tools/gp/pdf_builder/builder.ts
T

112 lines
3.0 KiB
TypeScript

import { Browser } from "playwright";
import { PFiles } from "../file.ts";
import MarkdownIt from "markdown-it";
function resolveChromiumPath(): string {
const chromiumPath = Deno.env.get("CHROMIUM_PATH");
if (chromiumPath) {
return chromiumPath;
}
throw new Error(
[
"CHROMIUM_PATH is not set.",
"Use the provided flake shell or set CHROMIUM_PATH manually.",
'Example: export CHROMIUM_PATH="$(command -v chromium)"',
].join("\n"),
);
}
export class DocuBuilder {
html_pages: Array<string>;
browser: Browser | null;
pfiles: PFiles | null = null;
constructor() {
this.html_pages = [];
this.browser = null;
}
async with_browser() {
const { chromium } = await import("playwright");
const browser = await chromium.launch({
executablePath: resolveChromiumPath(),
headless: true,
args: ["--no-sandbox", "--disable-dev-shm-usage"],
});
this.browser = browser;
}
with_files_sync(dir: string) {
this.pfiles = new PFiles(dir);
}
as_html_page() {
this.html_pages = [];
const md = new MarkdownIt({
html: true,
linkify: true,
typographer: true,
});
this.html_pages.push(this.pfiles?.cover_html ?? "");
this.html_pages.push(this.pfiles?.style_html ?? "");
if (this.pfiles != null) {
let id = 1;
this.pfiles.pcolumes.forEach((colume) => {
let c_id = 1;
this.html_pages.push(`<h1 class="global">${colume.name}</h1>`);
colume.pfiles.forEach((pfile) => {
const html = md.render(pfile.content);
this.html_pages.push(
`<div style='page-break-after: always;' class="global c${c_id++} passages" id="page-${id++}">${html}</div>`,
);
});
});
}
this.html_pages.push(this.pfiles?.end_html ?? "");
console.debug(structuredClone(this.html_pages).join("\n"));
}
async build_as_pdf(name = "output") {
if (this.browser == null) {
throw new Error("Browser is not initialized. Call with_browser() first.");
}
if (this.pfiles != null && this.html_pages.length === 0) {
this.as_html_page();
}
const page = await this.browser.newPage();
try {
await page.setContent(this.html_pages.join("\n"));
await page.pdf({
path: `outputs/${name}-computer.pdf`,
format: "A4",
printBackground: true,
margin: { top: "20mm", bottom: "20mm", left: "10mm", right: "10mm" },
//displayHeaderFooter: true,
});
await page.pdf({
path: `outputs/${name}-smartphone.pdf`,
format: "A4",
printBackground: true,
margin: { top: "20mm", bottom: "20mm", left: "10mm", right: "10mm" },
//displayHeaderFooter: true,
scale: 1.75,
});
} finally {
await page.close();
await this.browser.close();
this.browser = null;
}
}
async close_browser() {
if (this.browser == null) {
return;
}
await this.browser.close();
this.browser = null;
}
}