-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
104 lines (93 loc) · 2.82 KB
/
app.js
File metadata and controls
104 lines (93 loc) · 2.82 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
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
// Express
const express = require('express')
const app = express()
// pdfMake
const pdfPrinter = require('pdfmake')
// fileStream
const fs = require('fs')
// JSON Data
const jsonData = require('./basicData')
//Font Files
var fonts = {
Roboto: {
normal: 'fonts/Roboto-Regular.ttf',
bold: 'fonts/Roboto-Medium.ttf',
italics: 'fonts/Roboto-Italic.ttf',
bolditalics: 'fonts/Roboto-MediumItalic.ttf'
}
}
const printer = new pdfPrinter(fonts)
// Generate-Pdf EndPoint
app.get('/generate-pdf', (req, res) => {
var bodyData = []
jsonData.forEach(function (d) {
var dataRow = []
dataRow.push(d.id)
dataRow.push(d.name)
dataRow.push(d.age)
dataRow.push(d.gender)
bodyData.push(dataRow)
})
var tableLayout = {
// Page Orientation - You can Change to 'potrait' or 'landscape'.
pageOrientation: 'landscape',
// Content of the Data to Display
content: [{
// Text to Show
text: 'Data List',
// Styles
style: 'header'
},
{
text: 'List of JSON Data Convert to PDF',
style: 'subHeader',
// Line Height
lineHeight: 2
},
{
// Table Layout - You can Change to 'noBorders', 'headerLineOnly', or 'lightHorizontalLines'.
layout: 'headerLineOnly',
table: {
// Table Widths, which need to declare based on how many data you want to show.
// In my case, I just need to show: id, name, age and gender.
// Which is total of 4 Data.
widths: ['auto', 'auto', 'auto', 'auto'],
body: bodyData
}
}
],
// Styles
styles: {
// Style for header
header: {
fontSize: 25,
bold: true
},
// Style for subHeader
subHeader: {
fontSize: 20
}
}
}
generatePdf(tableLayout).then(res.redirect('/success-generate'))
})
// Function to Build and Write the PDF to Root Folder.
async function generatePdf(data) {
// Build the PDF
var pdfDoc = printer.createPdfKitDocument(data)
// Writing to Disk - dataPdf.pdf
pdfDoc.pipe(fs.createWriteStream('dataPdf.pdf'))
pdfDoc.end()
}
// Success Message - after Generate the PDF
app.get('/success-generate', (req, res) => {
res.send('Generate PDF Success!')
})
// Index
app.get('/', (req, res) => {
res.send('Hi - You can Change the EndPoint to /generate-pdf for generate the JSON Data to PDF.')
})
// Listening Port
app.listen(3000, () => {
console.log('Server running at port 3000: http://127.0.0.1:3000')
})