-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpdf.js
69 lines (61 loc) · 1.83 KB
/
pdf.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
'use strict'
const chromium = require('chrome-aws-lambda')
const pug = require('pug')
const fs = require('fs')
const path = require('path')
const knex = require('./src/db')
module.exports.pdf = async (event, context) => {
const yearMonth = ((event || {}).pathParameters || {}).yearMonth || ''
const year = yearMonth.length == 7 && yearMonth.substring(0, 4)
const month = yearMonth.length == 7 && yearMonth.substring(5, 6)
// Select a date
const selDate = new Date(year, month)
const filter = {
month: selDate.toLocaleString('en', { month: 'long' }),
year: selDate.getFullYear(),
}
// Fetch data with knex
const result = await knex
.select()
.from('sales')
.where({
year: filter.year,
month: selDate.getMonth() + 1,
})
const template = pug.compileFile('./src/template.pug')
const html = template({ ...filter, result })
let browser = null
try {
browser = await chromium.puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath,
headless: chromium.headless,
})
const page = await browser.newPage()
page.setContent(html)
const pdf = await page.pdf({
format: 'A4',
printBackground: true,
displayHeaderFooter: true,
margin: { top: '1.8cm', right: '1cm', bottom: '1cm', left: '1cm' },
})
// TODO: Response with PDF (or error if something went wrong )
const response = {
headers: {
'Content-type': 'application/pdf',
'content-disposition': 'attachment; filename=test.pdf',
},
statusCode: 200,
body: pdf.toString('base64'),
isBase64Encoded: true,
}
context.succeed(response)
} catch (error) {
return context.fail(error)
} finally {
if (browser !== null) {
await browser.close()
}
}
}