-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpdf-service.ts
50 lines (45 loc) · 1.41 KB
/
pdf-service.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
export interface PdfService {
getPdf(url: string): Promise<Buffer>;
}
import chromium = require('chrome-aws-lambda');
import puppeteer = require('puppeteer-core');
export class ChromePdfService implements PdfService {
public async getPdf(url: string): Promise<Buffer> {
console.log(`Generating PDF for ${url}`);
let browser = null;
try {
browser = await puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath,
headless: chromium.headless,
});
const page = await browser.newPage();
await page.goto(url, {
waitUntil: ['networkidle0', 'load', 'domcontentloaded'],
});
const result = await page.pdf({
printBackground: true,
format: 'A4',
displayHeaderFooter: true,
footerTemplate: `
<div style="font-size:10px; margin-left:20px;">Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>
`,
margin: {
top: '20px',
right: '20px',
bottom: '50px',
left: '20px',
},
});
console.log(`buffer size = ${result.length}`);
return result;
} catch (error) {
throw new Error(`Failed to PDF url ${url} Error: ${JSON.stringify(error)}`);
} finally {
if (browser !== null) {
await browser.close();
}
}
}
}