-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
183 lines (155 loc) · 4.63 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import fs from 'node:fs'
import path from 'node:path'
import url from 'node:url'
import ow from 'ow'
import puppeteer from 'puppeteer'
import { cssifyObject } from 'css-in-js-utils'
const dirname = path.dirname(url.fileURLToPath(import.meta.url))
const observerScript = fs.readFileSync(
path.join(dirname, 'lib', 'fontfaceobserver.standalone.js'),
'utf8'
)
const observer = `
<script>
${observerScript}
</script>
`
/**
* Renders the given text / html via puppeteer.
*
* Asynchronously returns the generated html page as a string for debugging purposes.
*
* If you want to load multiple google fonts, juse specify their font-families in `opts.style.fontFamily`
* separated by commas as you normally would for CSS fonts.
*
* @name renderText
* @function
*
* @param {object} opts - Configuration options
* @param {string} opts.text - HTML content to render
* @param {string} opts.output - Path of image file to store result
* @param {number} [opts.width] - Optional max width for word-wrap
* @param {number} [opts.height] - Optional max height to clip overflow
* @param {string} [opts.loadFontFamily] - Optional font family to load with fontfaceobserver
* @param {boolean} [opts.loadGoogleFont=false] - Whether or not to load and wait for `opts.style.fontFamily` as one or more google fonts
* @param {boolean} [opts.verbose=false] - Optional whether to log browser console messages
* @param {object} [opts.style={}] - JS [CSS styles](https://www.w3schools.com/jsref/dom_obj_style.asp) to apply to the text's container div
* @param {object} [opts.inject={}] - Optionally injects arbitrary string content into the head, style, or body elements.
* @param {string} [opts.inject.head] - Optionally injected into the document <head>
* @param {string} [opts.inject.style] - Optionally injected into a <style> tag within the document <head>
* @param {string} [opts.inject.body] - Optionally injected into the document <body>
*
* @return {Promise}
*/
export async function renderText(opts) {
const {
text,
output,
width = undefined,
height = undefined,
loadFontFamily = undefined,
loadGoogleFont = false,
verbose = false,
style = {},
inject = {}
} = opts
ow(output, 'output', ow.string.nonEmpty)
ow(text, 'text', ow.string)
ow(style, 'style', ow.object.plain)
const { fontFamily = '' } = style
if (loadGoogleFont && !fontFamily) {
throw new Error('valid style.fontFamily required when loading google font')
}
const fonts = loadFontFamily
? [loadFontFamily]
: loadGoogleFont
? fontFamily.split(',').map((font) => font.trim())
: []
const fontHeader = loadFontFamily
? observer
: loadGoogleFont
? `
${observer}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=${fonts
.map((font) => font.replace(/ /g, '+'))
.join('|')}">
`
: ''
const fontsToLoad = fonts.map((font) => `new FontFaceObserver('${font}')`)
const fontLoader = fontsToLoad.length
? `Promise.all([ ${fontsToLoad.join(
', '
)} ].map((f) => f.load())).then(ready);`
: 'ready();'
const html = `
<html>
<head>
<meta charset="UTF-8">
${inject.head || ''}
${fontHeader}
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background: transparent;
${width ? 'max-width: ' + width + 'px;' : ''}
${height ? 'max-height: ' + height + 'px;' : ''}
overflow: hidden;
}
.text {
display: inline-block;
${width ? '' : 'white-space: nowrap;'}
${cssifyObject(style)}
}
${inject.style || ''}
</style>
</head>
<body>
${inject.body || ''}
<div class="text">${text}</div>
<script>
function ready () {
var div = document.createElement('div');
div.className = 'ready';
document.body.appendChild(div);
}
${fontLoader}
</script>
</body>
</html>
`
// testing
// fs.writeFileSync('test.html', html)
const browser =
opts.browser ||
(await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox']
}))
const page = await browser.newPage()
if (verbose) {
page.on('console', console.log)
page.on('error', console.error)
}
await page.setViewport({
deviceScaleFactor: 1,
width: width || 640,
height: height || 480,
deviceScaleFactor: 1
})
await page.setContent(html)
await page.waitForSelector('.ready')
const frame = page.mainFrame()
const textHandle = await frame.$('.text')
const isPng = output.toLowerCase().endsWith('png')
await textHandle.screenshot({
path: output,
type: isPng ? 'png' : 'jpeg',
omitBackground: opts.omitBackground ?? (isPng ? true : false)
})
await textHandle.dispose()
await browser.close()
return html
}