-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgatsby-node.js
103 lines (86 loc) · 3.68 KB
/
gatsby-node.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
"use strict";
var _puppeteer = _interopRequireDefault(require("puppeteer"));
var _fsExtra = _interopRequireDefault(require("fs-extra"));
var _path = _interopRequireDefault(require("path"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const DEV_PAGE = '/dev-404-page/';
const fileRegexp = RegExp('.*.(html|htm)');
const normalizePageName = (pagePath = '') => {
const normalizedFront = pagePath.startsWith('/') ? pagePath.slice(1) : pagePath;
const normalizedEnd = normalizedFront.endsWith('/') ? normalizedFront.slice(0, -1) : normalizedFront;
const pageName = normalizedEnd == '' ? 'index' : normalizedEnd.replace(/\//g, '-');
return pageName;
};
const generatePdf = async ({
pagePath,
outputPath = 'public/exports',
filePrefix,
pdfOptions = {},
styleTagOptions
}) => {
const currentDir = process.cwd();
const browser = await _puppeteer.default.launch({
headless: true
});
const page = await browser.newPage();
const htmlPath = _path.default.join(currentDir, 'public', pagePath, 'index.html');
const downloadDir = _path.default.join(currentDir, outputPath);
if (!_fsExtra.default.existsSync(downloadDir)) {
_fsExtra.default.mkdirSync(downloadDir);
}
const contentHtml = _fsExtra.default.readFileSync(htmlPath, 'utf8');
await page.setContent(contentHtml);
if (styleTagOptions) {
await page.addStyleTag(styleTagOptions);
}
await page.pdf({
format: 'A4',
path: _path.default.join(downloadDir, `${filePrefix ? filePrefix : ''}${normalizePageName(pagePath)}.pdf`),
...pdfOptions
});
await browser.close();
};
exports.onPostBuild = async (options, {
allPages = false,
paths = [],
...restProps
}) => {
const pageNodes = options.getNodes().map(({
path
}) => path).filter(path => path !== undefined && path !== DEV_PAGE && !fileRegexp.test(path));
if (allPages) {
const promisses = pageNodes.map(pagePath => generatePdf({
pagePath,
...restProps
}));
await Promise.all(promisses);
} else {
const promisses = paths.map(pagePath => {
if (pageNodes.includes(pagePath)) {
return generatePdf({
pagePath,
...restProps
});
} else {
console.warn(`Page path ${pagePath} for which you want generate PDF does not exist. Check gatsby-plugin-pdf configuration in your gatsby-config.js.`);
}
});
await Promise.all(promisses);
}
};
exports.pluginOptionsSchema = ({
Joi
}) => {
return Joi.object({
allPages: Joi.boolean().default(`false`).description(`When true all pages will be converted to PDF files.`),
filePrefix: Joi.string().description(`Optional prefix for exported PDF file`),
outputPath: Joi.string().default(`/public/exports`).description(`Optional path where to store generated PDFs. Relative to current project dir.`),
paths: Joi.array().items(Joi.string()).min(1).description(`Array of page paths to convert to PDF. Path have to start with a leading /. You can pass nested paths like '/path/subpath'. For the root path use just single '/'.`),
pdfOptions: Joi.object().description(`See pdf puppeteer options: https://github.com/puppeteer/puppeteer/blob/v5.5.0/docs/api.md#pagepdfoptions.`),
styleTagOptions: Joi.object({
url: Joi.string().description(`URL of the <link> tag`),
path: Joi.string().description(`Path to the CSS file to be injected into frame. If path is a relative path, then it is resolved relative to current working directory.`),
content: Joi.string().description(`Raw CSS content to be injected into frame.`)
}).description(`See addStyleTag puppeteer options: https://github.com/puppeteer/puppeteer/blob/v5.5.0/docs/api.md#pageaddstyletagoptions.`)
});
};