-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
216 lines (171 loc) · 5.58 KB
/
app.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
const express = require('express');
const cors = require('cors');
// Pdf lib
const { PDFDocument, rgb, StandardFonts } = require('pdf-lib');
const fontkit = require('@pdf-lib/fontkit');
// Fs
const fs = require('fs').promises;
const { connectToDatabase } = require('./database/mongodb');
const Certificate = require('./models/certificates');
// Express Js
const app = express();
const port = 3000; // or any port of your choice
app.use(express.json());
app.use(express.urlencoded({ extended: true })) // for form data
app.use(cors());
// Connect Database
connectToDatabase();
// Create certificates folder if not exists
const certificatesDir = './certificates'; // Directory path
async function createCertificatesDir() {
try {
// Check if the directory exists
await fs.access(certificatesDir);
console.log(`${certificatesDir} already exists.`);
} catch (error) {
// Create the directory if it doesn't exist
await fs.mkdir(certificatesDir);
console.log(`${certificatesDir} created successfully.`);
}
}
createCertificatesDir().catch(error => {
console.error('Error:', error);
});
app.get('/prunedb', async (req, res)=>{
try {
// Delete all documents (certificates) from the collection
var result = await Certificate.deleteMany();
} catch (error) {
console.error('Error:', error);
}
return res.status(200).json({ status: `${result.deletedCount} certificates deleted.` })
})
// Download File Route
app.get('/download/:id', (req, res) => {
const fileid = req.params.id;
const file = `${__dirname}/certificates/${fileid}`;
res.download(file);
});
// Generate Route
app.post('/generate', async (req, res) => {
const { fullName, phoneNo, email } = req.body;
var duplicateKey = null;
var pdf = null;
if (!fullName || !phoneNo || !email)
return res.status(200).json({ status: "error", message: "Bad Request Check all required fields!" })
// Save in Database
try {
var Cert = new Certificate({
fullName: fullName,
phoneNo: phoneNo,
email: email
})
// Generate Certificate File and Save
pdf = await createCertficatePdf(Cert._id, fullName);
var Cert = await Cert.save();
} catch (error) {
if (error.code === 11000 || error.code === 11001) {
console.error('Duplicate Data');
const duplicateKey = Object.keys(error.keyValue)[0];
const existingDocument = await Certificate.findOne({ [duplicateKey]: error.keyValue[duplicateKey] });
try{
var existingPdf = await fs.readFile("certificates/"+existingDocument._id.toString()+".pdf")
}
catch(e)
{
return res.status(200).json({ error: e});
}
const base64String = existingPdf.toString('base64');
const fileName = `${existingDocument._id.toString()}.pdf`
// Duplicate Data
return res.status(200).json(
{
status: "success", CertificateDetails: existingDocument,
file: { fileName: fileName, contentType: 'application/pdf', data: base64String }
});
} else {
console.error('Error saving document:', error);
}
return;
}
res.status(201).json(
{
status: "success", CertificateDetails: Cert,
file: { pdf }
});
});
async function createCertficatePdf(certificate_id, certificate_name)
{
try {
const url = __dirname + '/certificate.pdf';
const existingPdfBytes = await fs.readFile(url);
const pdfDoc = await PDFDocument.load(existingPdfBytes)
const courierBoldText = await pdfDoc.embedFont(StandardFonts.CourierBold)
const TimesRoman = await pdfDoc.embedFont(StandardFonts.TimesRomanBold)
const fontSize = 30;
const pages = pdfDoc.getPages()
const firstPage = pages[0]
const { width, height } = firstPage.getSize()
// Calculate the width of the text
const textWidth = courierBoldText.widthOfTextAtSize(certificate_name, fontSize);
// Calculate the horizontal center position
const centerX = (firstPage.getWidth() - textWidth) / 2;
var date = new Date();
//const currentTimestamp = Math.floor(new Date().getTime() / 1000);
// Print Date Id
firstPage.drawText(date.toISOString().slice(0, 10), {
x: width - 140,
y: 80,
size: fontSize - 16,
font: courierBoldText,
color: rgb(0, 0, 0),
})
// Print Certificate ID
firstPage.drawText(certificate_id.toString(), {
x: 80,
y: height / 2 + 106,
size: fontSize - 16,
font: courierBoldText,
color: rgb(0, 0, 0),
})
// Print Name
firstPage.drawText(certificate_name, {
x: centerX,
y: height / 2 - 14,
size: fontSize,
font: TimesRoman,
color: rgb(0.95, 0.1, 0.1),
})
var pdfBytes = await pdfDoc.save()
// Bytes to Base64
var base64String = Buffer.from(pdfBytes).toString('base64');
var fileName = `${certificate_id.toString()}.pdf`
// Save Pdf File Locally
try{
await fs.writeFile('certificates/' + fileName, pdfBytes);
}
catch(error)
{
console.log(error);
}
// developement mode
// await fs.writeFile(`certificates/generated-pdf.pdf`, pdfBytes);
return { fileName: fileName, contentType: 'application/pdf', data: base64String }
}
catch (error) {
console.log("Error in Creating Certificate: ", error);
return;
}
}
// Default Route
app.get('/', (req, res) => {
res.status(200).json(
{
apiName: "Certificate Generate API",
author: "https://github.com/sanjaysrocks",
Usage: "To Create Certificate Use /generate endpoint (post request)"
})
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});