-
Notifications
You must be signed in to change notification settings - Fork 21
/
pdf.js
43 lines (38 loc) · 1.39 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
const fs = require('fs').promises;
const path = require('path');
const { v4: uuid } = require('uuid');
const { PDFDocument } = require('pdf-lib');
const staticPath = 'static/forms';
async function isDirectoryExists(directory) {
try {
await fs.stat(directory);
return true;
} catch (e) {
return false;
}
}
module.exports.fillPdf = async (filePath, template, body) => {
const sourcePDF = await fs.readFile(path.resolve(__dirname, '..', staticPath, filePath));
// Load a PDF with form fields
const pdfDoc = await PDFDocument.load(sourcePDF);
// Get the form containing all the fields
const form = pdfDoc.getForm();
const fields = form.getFields();
fields.forEach((field) => {
const type = field.constructor.name;
const name = field.getName();
if (type === 'PDFTextField' && template.PDFTextField[name]) {
field.setText(body[template.PDFTextField[name]]);
}
console.log(`${type}: ${name}`);
});
const pdfBytes = await pdfDoc.save();
const pdfPath = path.resolve(__dirname, '..', staticPath, './generated');
if (!await isDirectoryExists(pdfPath)) {
await fs.mkdir(pdfPath);
}
const pdfName = uuid();
const generatedPdf = path.resolve(pdfPath, `./${pdfName}.pdf`);
await fs.writeFile(generatedPdf, pdfBytes);
return `/${staticPath}/generated/${pdfName}.pdf`;
};