可以自动生成PDF文档了,仍需要完善一些细节
This commit is contained in:
1 parent
1d37f84b6c
commit
1918fc7a3e
19 files changed
+683
-65
No files matched your search
@@ -0,0 +1,83 @@
|
||||
import { Browser } from "playwright";
|
||||
import MarkdownIt from "markdown-it";
|
||||
import { PFiles } from "../file.ts";
|
||||
|
||||
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();
|
||||
if (this.pfiles != null) {
|
||||
this.pfiles.pcolumes.forEach((colume) => {
|
||||
this.html_pages.push(`<h1>${colume.name}</h1>`);
|
||||
colume.pfiles.forEach((pfile) => {
|
||||
const html = MD.render(pfile.content);
|
||||
this.html_pages.push(
|
||||
`<div style='page-break-after: always;'>${html}</div>`,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async build_as_pdf(path = "output.pdf") {
|
||||
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, format: "A4" });
|
||||
} 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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user