-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathnode.js
115 lines (104 loc) · 2.48 KB
/
node.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
// Example: Create a PDF invoice and save it to a file called invoice_from_node.pdf
//
// This example requires InvoicePrinter Server to be running.
//
// You can run the server as:
// $ invoice_printer_server
//
// And run this example as:
// $ node node.js
const invoice = {
"number": "NO. 198900000001",
"provider_name": "John White",
"provider_tax_id": "",
"provider_tax_id2": "",
"provider_lines": "79 Stonybrook St.\nBronx, NY 10457",
"purchaser_name": "Will Black",
"purchaser_tax_id": "",
"purchaser_tax_id2": "",
"purchaser_lines": "8648 Acacia Rd.\nBrooklyn, NY 11203",
"issue_date": "05/03/2016",
"due_date": "19/03/2016",
"subtotal": "$ 1,000",
"tax": "$ 100",
"tax2": "",
"tax3": "",
"total": "$ 1,100",
"bank_account_number": "156546546465",
"account_iban": "",
"account_swift": "",
"items": [
{
"name": "Programming",
"quantity": "10",
"unit": "hr",
"price": "$ 60",
"tax": "$ 60",
"tax2": "",
"tax3": "",
"amount": "$ 600"
},
{
"name": "Consulting",
"quantity": "10",
"unit": "hr",
"price": "$ 30",
"tax": "$ 30",
"tax2": "",
"tax3": "",
"amount": "$ 300"
},
{
"name": "Support",
"quantity": "20",
"unit": "hr",
"price": "$ 15",
"tax": "$ 30",
"tax2": "",
"tax3": "",
"amount": "$ 330"
}
],
"note": "This is a note at the end."
}
const http = require('http');
const fs = require('fs');
// Prepare the JSON in the expected format
const postData = JSON.stringify({
"document" : invoice
});
// Prepare POST options such as correct headers
const postOptions = {
host: 'localhost',
port: '9393',
path: '/render',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
const postRequest = http.request(postOptions, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
// Save the PDF if everything went okay
resp.on('end', () => {
response = JSON.parse(data);
if (response["data"]) {
const pdf = Buffer.from(response["data"], 'base64');
fs.writeFile("invoice_from_node.pdf", pdf, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
} else {
console.log("Error: " + response["error"])
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
postRequest.write(postData);
postRequest.end();