-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
102 lines (84 loc) · 2.8 KB
/
server.js
File metadata and controls
102 lines (84 loc) · 2.8 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
const express = require("express");
const app = express();
const puppeteer = require("puppeteer");
const path = require("path");
const fs = require("fs");
const port = 3000;
app.use(express.json());
app.get("/health", (req, res) => {
res.status(200).json({ status: "ok" });
});
/**
* Default font family for PDF generation
* You can customize this to use different fonts or styles
* Make sure to include the font files in your project and load them in the HTML template
*/
const fontFilePath = path.join(__dirname, "fonts", "Atma-Bold.ttf");
const fontBase64 = fs.readFileSync(fontFilePath).toString("base64");
/**
* Endpoint to generate PDF from HTML template
* Expects JSON body with "name" and "message" fields
* Example request body:
* {
* "name": "মাহমুদ হাসান রামীম",
* "message": "আসসালামু আলাইকুম, এই একটি উদাহরণ পিডিএফ যা বাংলা ফন্ট ব্যবহার করে তৈরি করা হয়েছে।"
* }
*/
app.post("/generate-html-to-pdf", async (req, res) => {
try {
const { name, message } = req.body;
const timeStamp = Date.now(); // Unique timestamp for file naming
console.log("Font path:", fontFilePath); // Log the font path to verify it's correct
// Load HTML template
let html = fs.readFileSync(
path.join(__dirname, "templates", "invoice.html"),
"utf8",
);
// Replace dynamic values
html = html
.replace("{{name}}", name)
.replace("{{message}}", message)
.replace(
"{{FONT_PATH}}",
`data:font/truetype;charset=utf-8;base64,${fontBase64}`,
); // Embed the font as a base64 data URI
const browser = await puppeteer.launch({
headless: "new",
args: [
"--no-sandbox",
"--disable-setuid-sandbox",
"--allow-file-access-from-files",
],
});
const page = await browser.newPage();
await page.setContent(html, {
waitUntil: "networkidle0",
});
await page.evaluateHandle("document.fonts.ready");
const pdfBuffer = await page.pdf({
format: "A4",
printBackground: true,
});
await browser.close();
// Save the PDF to the server folder (Output folder)
fs.writeFileSync(
path.join(__dirname, "outputs", `${timeStamp}.pdf`),
pdfBuffer,
);
// res.send({
// success: true,
// message: "PDF generated successfully",
// });
res.set({
"Content-Type": "application/pdf",
"Content-Disposition": `attachment; filename=${timeStamp}.pdf`,
});
res.send(pdfBuffer);
} catch (error) {
console.error(error);
res.status(500).send("PDF generation failed");
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});