import { Browser } from "playwright"; import { PFiles } from "../file.ts"; import MarkdownIt from "markdown-it"; import TurndownService from "turndown"; 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"), ); } //原文->中间体(html)->目标格式(pdf/md/...) //生成pdf的流程:原文->中间体(html)->playwright渲染->pdf //生成md的流程:原文->中间体(html)->turndown转换->md export class DocuBuilder { pages: Array; browser: Browser | null; pfiles: PFiles | null = null; constructor() { this.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_markdown() { const turndownService = new TurndownService(); const md_page = turndownService.turndown(this.as_html_page()); this.pages = [md_page]; } as_html_page(): string { this.pages = []; const md = new MarkdownIt({ html: true, linkify: true, typographer: true, }); this.pages.push(this.pfiles?.cover_html ?? ""); this.pages.push(this.pfiles?.style_html ?? ""); this.pages.push(this.pfiles?.other_htmls.join("\n") ?? ""); if (this.pfiles != null) { let id = 1; this.pfiles.pcolumes.forEach((colume) => { let c_id = 1; this.pages.push( `${colume.name}`, ); colume.pfiles.forEach((pfile) => { const html = md.render(pfile.content); this.pages.push( `
${html}
`, ); }); }); } this.pages.push(this.pfiles?.end_html ?? ""); //console.debug(structuredClone(this.pages).join("\n")); return this.pages.join("\n"); } async build_as_raw(file_name: string) { await Deno.writeFile( file_name, new TextEncoder().encode(this.pages.join("\n")), ); } // deno-lint-ignore no-explicit-any async build_as_pdf(pw_config: any) { if (this.browser == null) { throw new Error("Browser is not initialized. Call with_browser() first."); } if (this.pfiles != null && this.pages.length === 0) { this.as_html_page(); } const page = await this.browser.newPage(); try { await page.setContent(this.pages.join("\n")); await page.pdf( pw_config, ); // // 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(); } } async close_browser() { if (this.browser == null) { return; } await this.browser.close(); this.browser = null; } } export class IndexBuilder { constructor() { } }