This repository has been archived by the owner on Jan 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
index.js
116 lines (102 loc) · 2.35 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
require('@babel/register')({
plugins: [
].map(require.resolve),
presets: [
'@babel/preset-env',
'@babel/preset-react'
].map(require.resolve)
})
const fs = require('fs')
const puppeteer = require('puppeteer')
const { Readable } = require('stream')
const path = require('path')
const { createElement: h } = require('react')
const { renderToStaticMarkup } = require('react-dom/server')
const Datauri = require('datauri')
const resolveCWD = require('resolve-cwd')
const baseCSS = `*{box-sizing:border-box}body{margin:0;font-family:system-ui,sans-serif}`
const getHtmlData = ({
body,
baseCSS,
css,
styles,
webfont
}) => {
const fontCSS = webfont ? getWebfontCSS(webfont) : ''
const html = `<!DOCTYPE html>
<head>
<meta charset="utf-8"><style>${baseCSS}${fontCSS}${css}</style>
${styles}
</head>
<body style="display:inline-block">
${body}`
return html
}
const getWebfontCSS = (fontpath) => {
const { content } = new Datauri(fontpath)
const [ name, ext ] = fontpath.split('/').slice(-1)[0].split('.')
const css = (`@font-face {
font-family: '${name}';
font-style: normal;
font-weight: 400;
src: url(${content});
}`)
return css
}
module.exports = async (Component, opts = {}) => {
const {
css = '',
filename,
outDir,
webfont,
type = 'png', // jpeg, png and pdf are allowed
} = opts
const props = Object.assign({
width: opts.width,
height: opts.height,
}, opts.props)
let styles = ''
const el = h(Component, props)
const body = renderToStaticMarkup(el)
const html = getHtmlData({
body,
baseCSS,
css,
styles,
webfont
})
const browser = await puppeteer.launch(opts.puppeteer)
const page = await browser.newPage()
await page.setContent(html)
let rect = {}
if (!opts.width && !opts.height) {
const bodyEl = await page.$('body')
rect = await bodyEl.boxModel()
}
const width = parseInt(opts.width || rect.width)
const height = parseInt(opts.height || rect.height)
await page.setViewport({
width,
height,
})
let result
if (type === 'pdf') {
result = await page.pdf({
width,
height,
})
} else {
result = await page.screenshot({
type: type,
clip: {
x: 0,
y: 0,
width,
height,
},
omitBackground: true
})
}
await browser.close()
return result
}