-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
46 lines (43 loc) · 2.16 KB
/
index.js
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
const fs = require("fs").promises;
const { URL } = require("url");
const fetch = require("node-fetch");
const log = require("npmlog");
const { JSDOM } = require("jsdom");
const wkhtmltopdf = require("wkhtmltopdf");
const getStream = require("get-stream");
const baseURL = new URL("https://developer.apple.com/library/archive/documentation/");
const bookURL = new URL("Cocoa/Conceptual/CocoaViewsGuide/", baseURL);
(async () => {
const toc = await (await fetch(new URL("book.json", bookURL))).json();
await Promise.all(toc.sections.filter(({ title }) => title !== "Revision History").map(async ({ href, title }) => {
const sectionURL = new URL(href, bookURL);
log.info(`Loading article '${title}'...`);
const { window: section } = await JSDOM.fromURL(sectionURL, {
resources: "usable"
});
log.info(`Constructed DOM tree for article '${title}'`);
section.addEventListener("load", async () => {
log.info(`Finished loading article '${title}'`);
log.info(`Generating '${title}.pdf'...`);
const articleHTML = section.document.querySelector("article").innerHTML;
const styleSheets = [...section.document.styleSheets];
const cssRules = styleSheets.reduce((acc, cur) => [...acc, ...cur.cssRules], []);
const cssText = cssRules.map(cssRule => cssRule.cssText).join("\n");
const pdfDom = new JSDOM();
const { document } = pdfDom.window;
document.body.innerHTML = articleHTML;
const styleEl = document.createElement("style");
const baseEl = document.createElement("base");
const charsetEl = document.createElement("meta");
styleEl.innerHTML = cssText;
baseEl.href = sectionURL;
charsetEl.setAttribute("charset", "utf-8");
document.head.append(styleEl, charsetEl, baseEl);
const pdf = await getStream.buffer(wkhtmltopdf(pdfDom.serialize()));
section.close();
pdfDom.window.close();
await fs.writeFile(`${title}.pdf`, pdf);
log.info(`Finished generating '${title}.pdf'`);
});
}));
})();