forked from westmonroe/pdf-puppeteer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
208 lines (171 loc) · 5.29 KB
/
index.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
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import { getPaperSize } from '@cityssm/paper-sizes'
import launchPuppeteer, { type puppeteer } from '@cityssm/puppeteer-launch'
import Debug from 'debug'
import exitHook from 'exit-hook'
import { DEBUG_NAMESPACE } from './debug.config.js'
import {
type PDFPuppeteerOptions,
defaultPdfOptions,
defaultPdfPuppeteerOptions,
defaultPuppeteerOptions,
htmlNavigationTimeoutMillis,
urlNavigationTimeoutMillis
} from './defaultOptions.js'
const debug = Debug(`${DEBUG_NAMESPACE}:index`)
let cachedBrowser: puppeteer.Browser | undefined
/**
* Converts HTML or a webpage into HTML using Puppeteer.
* @param html - An HTML string, or a URL.
* @param instancePdfOptions - PDF options for Puppeteer.
* @param instancePdfPuppeteerOptions - pdf-puppeteer options.
* @returns A Buffer of PDF data.
*/
// eslint-disable-next-line complexity
export async function convertHTMLToPDF(
html: string,
instancePdfOptions: puppeteer.PDFOptions = {},
instancePdfPuppeteerOptions: Partial<PDFPuppeteerOptions> = {}
): Promise<Uint8Array> {
if (typeof html !== 'string') {
throw new TypeError(
'Invalid Argument: HTML expected as type of string and received a value of a different type. Check your request body and request headers.'
)
}
const pdfPuppeteerOptions = {
...defaultPdfPuppeteerOptions,
...instancePdfPuppeteerOptions
}
/*
* Initialize browser
*/
const puppeteerOptions = { ...defaultPuppeteerOptions }
if (pdfPuppeteerOptions.disableSandbox) {
puppeteerOptions.args = ['--no-sandbox', '--disable-setuid-sandbox']
}
let browser: puppeteer.Browser | undefined
let doCloseBrowser = false
let isRunningPdfGeneration = false
try {
if (pdfPuppeteerOptions.cacheBrowser) {
if (cachedBrowser === undefined) {
cachedBrowser = await launchPuppeteer(puppeteerOptions)
}
browser = cachedBrowser
} else {
doCloseBrowser = true
browser = await launchPuppeteer(puppeteerOptions)
}
const browserVersion = await browser.version()
debug(`Browser: ${browserVersion}`)
const browserIsFirefox = browserVersion.toLowerCase().includes('firefox')
/*
* Initialize page
*/
const page = await browser.newPage()
const remoteContent = pdfPuppeteerOptions.remoteContent
if (pdfPuppeteerOptions.htmlIsUrl) {
debug('Loading URL...')
await page.goto(html, {
waitUntil: browserIsFirefox ? 'domcontentloaded' : 'networkidle0',
timeout: urlNavigationTimeoutMillis
})
} else if (remoteContent) {
debug('Loading HTML with remote content...')
await page.goto(
`data:text/html;base64,${Buffer.from(html).toString('base64')}`,
{
waitUntil: browserIsFirefox ? 'domcontentloaded' : 'networkidle0',
timeout: urlNavigationTimeoutMillis
}
)
} else {
debug('Loading HTML...')
await page.setContent(html, {
timeout: htmlNavigationTimeoutMillis
})
}
debug('Content loaded.')
const pdfOptions = { ...defaultPdfOptions, ...instancePdfOptions }
// Fix "format" issue
if (pdfOptions.format !== undefined) {
const size = getPaperSize(pdfOptions.format)
// eslint-disable-next-line sonarjs/different-types-comparison, @typescript-eslint/no-unnecessary-condition
if (size !== undefined) {
delete pdfOptions.format
pdfOptions.width = `${size.width}${size.unit}`
pdfOptions.height = `${size.height}${size.unit}`
}
}
debug('Converting to PDF...')
// eslint-disable-next-line sonarjs/no-dead-store
isRunningPdfGeneration = true
const pdfBuffer = await page.pdf(pdfOptions)
// eslint-disable-next-line sonarjs/no-dead-store
isRunningPdfGeneration = false
debug('PDF conversion done.')
await page.close()
if (!pdfPuppeteerOptions.cacheBrowser || cachedBrowser !== browser) {
await browser.close()
}
return pdfBuffer
} catch (error) {
if (
isRunningPdfGeneration &&
defaultPuppeteerOptions.browser === 'chrome'
) {
if (!doCloseBrowser) {
await closeCachedBrowser()
}
defaultPuppeteerOptions.browser = 'firefox'
debug('Trying again with Firefox.')
return await convertHTMLToPDF(
html,
instancePdfOptions,
instancePdfPuppeteerOptions
)
} else {
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw error
}
} finally {
try {
if (doCloseBrowser && browser !== undefined) {
debug('Closing browser...')
await browser.close()
debug('Browser closed.')
}
} catch {
// ignore
}
}
}
export default convertHTMLToPDF
/**
* Closes the cached browser instance.
*/
export async function closeCachedBrowser(): Promise<void> {
if (cachedBrowser !== undefined) {
try {
await cachedBrowser.close()
} catch {
// ignore
}
cachedBrowser = undefined
}
}
/**
* Checks for any cached browser instance.
* @returns True is a cached browser instance exists.
*/
export function hasCachedBrowser(): boolean {
return cachedBrowser !== undefined
}
export {
type PDFPuppeteerOptions,
defaultPdfOptions,
defaultPdfPuppeteerOptions
} from './defaultOptions.js'
exitHook(() => {
debug('Running exit hook.')
void closeCachedBrowser()
})