-
Notifications
You must be signed in to change notification settings - Fork 1
/
md-to-pdf.ts
57 lines (51 loc) · 1.5 KB
/
md-to-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
48
49
50
51
52
53
54
55
56
57
import { mdToHtml } from "./md-to-html";
import { join } from "path";
import { execSync } from "child_process";
import os from "os";
import { mkdtempSync, readFileSync, writeFileSync } from "fs";
(async () => {
const md = readFileSync(process.argv[2], "utf8");
const tmpDir = mkdtempSync(join(os.tmpdir(), "markdown-to-pdf-"));
const mdChunks = md.split("\n").reduce(
(acc, val) =>
val.startsWith("#") &&
!acc.at(-1).split("\n").filter(Boolean).at(-1)?.startsWith("#")
? [...acc, val]
: [...acc.slice(0, -1), acc.at(-1) + "\n" + val],
[""],
);
let prevI = 0;
for (let i = 0; i < mdChunks.length; i++) {
writeFileSync(
join(tmpDir, `tmp.html`),
await mdToHtml(mdChunks.slice(prevI, i + 1).join("\n"), {
title: "",
}),
"utf8",
);
execSync(
`prince ${join(tmpDir, `tmp.html`)} --pdf-profile='PDF/UA-1' -o ${join(tmpDir, `tmp.pdf`)}`,
);
const pageCount = parseInt(
execSync(
`pdfinfo ${join(tmpDir, `tmp.pdf`)} | grep Pages | awk '{print $2}'`,
).toString(),
);
console.log(
`Chunk ${i}:${prevI}:${pageCount}: ${mdChunks[i].split("\n")[0]}`,
);
if (pageCount > 1) {
prevI = i;
} else {
execSync(
`mv ${join(tmpDir, `tmp.pdf`)} ${join(
tmpDir,
`output.${prevI.toString().padStart(5, "0")}`,
)}`,
);
}
}
execSync(`pdfunite ${join(tmpDir, `output.*`)} ${process.argv[3]}`);
})().catch((error) => {
throw error;
});