-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
generate-output.ts
54 lines (45 loc) · 1.69 KB
/
generate-output.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
import puppeteer from 'puppeteer';
import { Config } from './config';
import { isHttpUrl } from './is-http-url';
/**
* Generate the output (either PDF or HTML).
*/
export const generateOutput = async (
html: string,
relativePath: string,
config: Config,
): Promise<{} | { filename: string; content: string | Buffer }> => {
const browser = await puppeteer.launch({ devtools: config.devtools, ...config.launch_options });
const page = await browser.newPage();
await page.goto(`http://localhost:${config.port}${relativePath}`); // make sure relative paths work as expected
await page.setContent(html); // overwrite the page content with what was generated from the markdown
await Promise.all([
...config.stylesheet.map(
async stylesheet => page.addStyleTag(isHttpUrl(stylesheet) ? { url: stylesheet } : { path: stylesheet }), // add each stylesheet
),
config.css ? page.addStyleTag({ content: config.css }) : undefined, // add custom css
]);
/**
* Trick to wait for network to be idle.
*
* @todo replace with page.waitForNetworkIdle once exposed
* @see https://github.com/GoogleChrome/puppeteer/issues/3083
*/
await Promise.all([
page.waitForNavigation({ waitUntil: 'networkidle0' }),
page.evaluate(() => history.pushState(undefined, '', '#')),
]);
let outputFileContent: string | Buffer = '';
if (config.devtools) {
await new Promise(resolve => page.on('close', resolve));
} else {
if (config.as_html) {
outputFileContent = await page.content();
} else {
await page.emulateMediaType('screen');
outputFileContent = await page.pdf(config.pdf_options);
}
}
await browser.close();
return config.devtools ? {} : { filename: config.dest, content: outputFileContent };
};