-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
154 lines (126 loc) · 5.02 KB
/
Copy pathserver.js
File metadata and controls
154 lines (126 loc) · 5.02 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
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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const puppeteer = require('puppeteer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const app = express();
async function launchBrowser() {
console.log("Attempting to launch browser...");
return puppeteer.launch({
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH,
headless: true,
args: [
'--disable-gpu',
'--no-sandbox',
'--disable-setuid-sandbox',
'--no-zygote',
'--single-process',
// This will write shared memory files into /tmp instead of /dev/shm,
// because Docker’s default for /dev/shm is 64MB
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--disable-dev-profile',
// Additional flags to ignore unnecessary loggings and errors
'--disable-scheduler'
],
dumpio: true
});
}
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/services/pdf-engine/', (req, res) => {
const exampleBody = {
"url": "https://finmars.com",
"bearer_token": "token"
};
res.send(`PDF Engine is Running. Use POST request on /print/ endpoint with body similar to this example: ${JSON.stringify(exampleBody, null, 2)}`);
});
app.post('/services/pdf-engine/print/', async (req, res) => {
const url = req.body.url;
console.log('Received URL:', url);
const isLandscape = req.body.landscape || false;
const bearer_token = req.body.bearer_token || null;
const access_token = req.body.access_token || null;
if (!url) {
console.log('No URL provided');
return res.status(400).send('No URL provided');
}
try {
console.log('Launching browser...');
const browser = await launchBrowser();
console.log('Creating New Page...');
const page = await browser.newPage();
page.on('console', msg => console.log('PAGE LOG:', msg.text()));
if (bearer_token) {
const cookies = [{
'name': 'bearer_token',
'value': bearer_token,
'domain': process.env.DOMAIN || 'finmars.com',
'path': '/',
'secure': true,
'httpOnly': true
}];
console.log('Setting cookies...');
await page.setCookie(...cookies);
}
if (access_token) {
const cookies = [{
'name': 'access_token',
'value': access_token,
'domain': process.env.DOMAIN || 'finmars.com',
'path': '/',
'secure': true,
'httpOnly': true
}];
console.log('Setting cookies...');
await page.setCookie(...cookies);
}
console.log('Navigating to page...');
await page.goto(url, { waitUntil: 'networkidle0', timeout: 0 });
// await page.screenshot({path: 'debug_screenshot.png'});
// var html = "<html><body><h1>Hello, World!</h1></body></html>"
console.log('Generating PDF...');
await page.emulateMediaType('screen');
const uniqueFilename = `output-${uuidv4()}.pdf`;
const filePath = path.join(__dirname, uniqueFilename);
// console.log('html', html);
let pdfBuffer = await page.pdf({
format: 'A4',
margin: { // Control the margins
top: '0cm', // Top margin set to 0
right: '0cm', // Right margin set to 0
bottom: '0cm', // Bottom margin set to 0
left: '0cm' // Left margin set to 0
},
landscape: isLandscape, // Print in portrait mode
printBackground: true, // Include background graphics
scale: 1, // Default scale (1 means 100%)
preferCSSPageSize: true // Use the @page size in CSS rather than the `format` option
});
console.log('Got PDF Buffer')
fs.writeFileSync(filePath, pdfBuffer);
await browser.close();
res.sendFile(filePath, function (err) {
if (err) {
console.error('Error sending file:', err);
} else {
try {
fs.unlinkSync(filePath); // Delete the file after sending it
console.log('File sent and deleted successfully.');
} catch (deleteError) {
console.error('Error deleting file:', deleteError);
}
}
});
} catch (error) {
console.error('Error during PDF generation:', error);
res.status(500).send('Failed to generate PDF');
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});