-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate-pdf.ts
47 lines (39 loc) · 1.58 KB
/
generate-pdf.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { readdir } from 'node:fs/promises';
import { chromium } from "playwright-core";
const dir = import.meta.dirname;
async function generate() {
const browser = await chromium.launch({ headless: true, args: ["--disable-web-security"] })
const page = await browser.newPage({ bypassCSP: true })
await page.route("file:///style.css", async (r) => {
const cssFile = Bun.file(`./style.css`)
const cssText = await cssFile.text()
r.fulfill({ status: 200, contentType: "text/css;charset=utf-8", body: cssText.replaceAll("/images/", `file:///${dir}/images/`) })
});
await page.route(/html$/, async (r, req) => {
const htmlFile = Bun.file(req.url().replace(`file://${dir}/`, "./"))
const htmlText = await htmlFile.text()
r.fulfill({ status: 200, contentType: "text/html;charset=utf-8", body: htmlText.replaceAll("/images/", `file:///${dir}/images/`) })
})
const files = (await readdir("./sets")).filter((f) => f !== "template.html")
for (const file of files) {
page.goto(`file://${dir}/sets/${file}`)
await page.waitForLoadState()
// console.info("waitForLoadState")
await page.waitForSelector("page")
// console.log("waitForSelector")
await page.waitForLoadState("domcontentloaded")
await page.waitForLoadState("networkidle")
const title = (await page.title()).replaceAll(":", "").replaceAll(" ", "-").replaceAll("[", "").replaceAll("]", "")
await page.pdf({
path: `./storage/${title}.pdf`,
printBackground: true,
scale: 1,
width: "21cm",
height: "29.7cm"
})
console.info(`Generated "${title}.pdf" PDF`)
}
await page.close()
process.exit(0)
}
void generate()