-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
executable file
·157 lines (113 loc) · 4.05 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/env node
/**
*
* (c) 2013-2018 Wishtack
* https://wishtack.io
*
*/
const addZero = require('add-zero');
const commander = require('commander');
const easyPdfMerge = require('easy-pdf-merge');
const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer');
const rimraf = require('rimraf');
const util = require('util');
class GitbookPrinter {
constructor({baseUrl, outPath, summaryPath}) {
this._baseUrl = baseUrl.replace(/\/+$/, '');
this._outPath = outPath;
this._partialsPath = path.join(this._outPath, 'partials');
this._summaryPath = summaryPath;
}
async savePdf() {
/* Clean up target. */
await util.promisify(rimraf)(this._outPath);
/* Create target directories. */
fs.mkdirSync(this._outPath);
fs.mkdirSync(this._partialsPath);
/* Download partial files. */
const pdfFilePathList = await this._downloadChapterList();
/* Merge files. */
await util.promisify(easyPdfMerge)(pdfFilePathList, path.join(this._outPath, 'gitbook.pdf'));
}
async _downloadChapterList() {
/* Open browser. */
const browser = await puppeteer.launch();
const page = await browser.newPage();
/* Get chapters list from summary. */
const chapterPathList = await this._getChapterPathList();
let pdfFilePathList = [];
for (const [index, chapterPath] of chapterPathList.entries()) {
const pageUrl = `${this._baseUrl}/${chapterPath}`;
const pdfFilePath = this._getChapterPdfFilePath({index, chapterPath});
console.debug(`Printing: ${pageUrl}...`);
await this._printPage({
page,
pageUrl,
pdfFilePath
});
/* Add file to list in order to merge all files later. */
pdfFilePathList = [...pdfFilePathList, pdfFilePath];
console.debug(`Created: ${pdfFilePath}.`);
}
await browser.close();
return pdfFilePathList;
}
_getChapterPdfFilePath({index, chapterPath}) {
const chapterIndexDigitCount = 3;
let chapterFileName = addZero(index, chapterIndexDigitCount);
if (chapterPath.length > 0) {
chapterFileName += `-${chapterPath.replace(/\//g, '-')}`;
}
chapterFileName += '.pdf';
return path.join(this._partialsPath, chapterFileName);
}
async _printPage({page, pageUrl, pdfFilePath}) {
await page.goto(pageUrl, {
waitUntil: 'networkidle0'
});
await page.evaluate(() => {
const style = document.createElement('style');
style.textContent = '[data-test="headermobile"],[data-test="headerdesktop"] { display: none; }';
style.textContent += 'h1 { page-break-before: always }';
document.head.appendChild(style);
});
await page.pdf({
path: pdfFilePath,
format: 'A4',
landscape: false
});
}
async _getChapterPathList() {
const summary = fs.readFileSync(this._summaryPath, 'utf-8');
return summary
.split('\n')
/* Ignore empty lines. */
.filter(line => line.length > 0)
/* Grab link URLs. */
.map(line => line.match(/\((.*?).md\)/))
.filter(match => match != null)
.map(match => match[1])
/* Remove /README suffix. */
.map(url => url.replace(/README$/, ''));
}
}
commander
.option('-b, --base-url <baseUrl>', 'Gitbook Base URL.')
.option('-s, --summary-path <summaryPath>', 'File Path to SUMMARY.md.')
.option('-o, --out <outDirPath>', 'Output directory.')
.parse(process.argv);
if (commander.baseUrl == null || commander.summaryPath == null) {
commander.help();
}
new GitbookPrinter({
baseUrl: commander.baseUrl,
summaryPath: commander.summaryPath,
outPath: commander.out || 'out'
})
.savePdf()
.catch(console.error);
module.exports = {
GitbookPrinter
};