forked from sunbird-cb/pdf-generator
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.ts
More file actions
55 lines (49 loc) · 1.89 KB
/
app.ts
File metadata and controls
55 lines (49 loc) · 1.89 KB
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
import express from 'express';
import { v4 as uuidv4 } from 'uuid'
import { logError, logInfo } from './utils/logger'
import * as fs from 'fs'
const app = express();
const port = 3000;
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));
const puppeteer = require('puppeteer');
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
return console.log(`Express is listening at http://localhost:${port}`);
});
app.post('/public/v8/course/batch/cert/download/mobile', async (req, res) => {
try {
const svgContent = req.body.printUri
if (req.body.outputFormat === 'svg') {
const _decodedSvg = decodeURIComponent(svgContent.replace(/data:image\/svg\+xml,/, '')).replace(/\<!--\s*[a-zA-Z0-9\-]*\s*--\>/g, '')
res.type('html')
res.status(200).send(_decodedSvg)
} else if (req.body.outputFormat === 'pdf') {
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] })
const page = await browser.newPage()
await page.goto(svgContent, { waitUntil: 'networkidle2' })
const uuid = uuidv4()
const buffer = await page.pdf({ path: `certificates/certificate-${uuid}.pdf`, printBackground: true, width: '1204px', height: '662px' })
res.set({ 'Content-Type': 'application/pdf', 'Content-Length': buffer.length })
res.send(buffer)
browser.close()
fs.unlink(`certificates/certificate-${uuid}.pdf`, function(){
logInfo('Deleted file : ', `certificates/certificate-${uuid}.pdf`)
});
} else {
res.status(400).json({
error: 'Unsupported output format',
msg: 'Output format should be svg or pdf',
})
}
} catch (err) {
logError(err)
res.status((err && err.response && err.response.status) || 500).send(
(err && err.response && err.response.data) || {
error: 'Failed due to unknown reason',
}
)
}
})