-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
119 lines (96 loc) · 3.06 KB
/
index.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
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
const express = require('express');
const bodyParser = require("body-parser");
const app = express();
var cors = require('cors');
var pdfFillForm = require('pdf-fill-form');
var AWS = require('aws-sdk');
var fs = require('fs');
var config = require('./config.dev.json');
AWS.config.loadFromPath('./credentials.json');
var s3 = new AWS.S3();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/test', (req, res) => {
res.send("Test success");
});
app.get('/fields', async (req, res) => {
try {
var name = req.query.name;
var params = {
Bucket: config.bucketName,
Key: "templates/"+ name + ".pdf"
};
var result = await s3.getObject(params).promise().then((response) => {
return response;
}).catch(error => {
return res.json(error);
});
fs.writeFileSync("tmp.pdf", result.Body);
var formFields = pdfFillForm.readSync('tmp.pdf');
fs.unlink('tmp.pdf', (response, error) => {
if(error) throw error;
return response;
});
res.json(formFields);
} catch (error) {
res.json(error);
}
});
app.post('/', async (req, res) => {
try {
var {
templateName,
fileName,
fields,
} = req.body;
var params = {
Bucket: config.bucketName,
Key: "templates/" + templateName +".pdf"
};
var result = await s3.getObject(params).promise().then((response) => {
return response;
}).catch(error => {
return res.json(error);
});
fs.writeFileSync("tmp.pdf", result.Body);
var formFields = pdfFillForm.readSync("tmp.pdf");
var newValues = {};
for(var field of fields) {
for(var formField of formFields) {
if(formField.name === field.name) {
newValues = {
...newValues,
[field.name]: field.value
}
}
}
}
var pdf = pdfFillForm.writeSync('tmp.pdf', newValues, { "save": "pdf" } );
console.log(newValues);
fs.unlink('tmp.pdf', (response, error) => {
if(error) throw error;
return response;
});
var currentTimeInMilliseconds = Date.now();
var outFileName = 'outputs/' + fileName + "_" + currentTimeInMilliseconds+'.pdf';
var newFileparams = {
Bucket: config.bucketName,
Key: outFileName,
Body: pdf,
ACL: 'public-read',
};
var newFileResult = await s3.upload(newFileparams).promise().then((response) => {
return response;
}).catch(error => {
return res.json(error);
});
res.json(newFileResult.Location);
} catch (error) {
console.log(error);
res.json(error);
}
});
app.listen(3000, () => {
console.log('3000 localhost listen...');
});