可以自动生成PDF文档了,仍需要完善一些细节

This commit is contained in:
:NoBody: committed 2026-04-20 22:49:44 +08:00
1 parent 1d37f84b6c
commit 1918fc7a3e
19 files changed
+683 -65

No files matched your search

+37 -53
View File
@@ -1,62 +1,46 @@
import MarkdownIt from "markdown-it";
import { Browser, chromium } from "playwright";
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 async function mdToPdf(
markdownContent: string,
outputPath = "output.pdf",
): Promise<void> {
const { chromium } = await import("playwright");
const md = new MarkdownIt();
const htmlContent = md.render(markdownContent);
const browser = await chromium.launch({
executablePath: resolveChromiumPath(),
headless: true,
args: ["--no-sandbox", "--disable-dev-shm-usage"],
});
// export async function mdToPdf(
// markdownContent: string,
// outputPath = "output.pdf",
// ): Promise<void> {
// const md = new MarkdownIt();
// const htmlContent = md.render(markdownContent);
try {
const page = await browser.newPage();
const fullHtml = `
<html>
<head>
<style>
body { font-family: "Noto Sans CJK SC", sans-serif; margin: 40px; }
h1 { color: #333; }
code { background: #f4f4f4; padding: 2px 4px; }
</style>
</head>
<body>${htmlContent}</body>
</html>
`;
// try {
// const page = await browser.newPage();
// const fullHtml = `
// <html>
// <head>
// <style>
// body { font-family: "Noto Sans CJK SC", sans-serif; margin: 40px; }
// h1 { color: #333; }
// code { background: #f4f4f4; padding: 2px 4px; }
// </style>
// </head>
// <body>${htmlContent}</body>
// </html>
// `;
await page.setContent(fullHtml);
await page.pdf({
path: outputPath,
format: "A4",
printBackground: true,
margin: { top: "20mm", bottom: "20mm", left: "10mm", right: "10mm" },
});
} finally {
await browser.close();
}
}
// await page.setContent(fullHtml);
// await page.pdf({
// path: outputPath,
// format: "A4",
// printBackground: true,
// margin: { top: "20mm", bottom: "20mm", left: "10mm", right: "10mm" },
// });
// } finally {
// await browser.close();
// }
// }
// if (import.meta.main) {
// await mdToPdf("# Test Title\n\nHello **PDF**", "output.pdf");
// console.log("PDF generated: output.pdf");
// }
if (import.meta.main) {
await mdToPdf("# Test Title\n\nHello **PDF**", "output.pdf");
console.log("PDF generated: output.pdf");
console.log();
}