-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
91 lines (73 loc) · 2.18 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
const express = require("express");
const puppeteer = require("puppeteer");
const fs = require("fs/promises");
const cors = require("cors");
const bodyParser = require("body-parser");
// mock
const data = require("./mock/GraphGet.json");
const app = express();
const port = 3002;
app.use(cors());
// Parse application/json
app.use(bodyParser.json());
// Define routes
app.get("/", (req, res) => {
res.send("Hello, World!");
});
app.post("/GraphGet", async (req, res) => {
try {
res.status(200).send(data);
} catch (error) {
console.error("Error:", error);
res.status(500).send("Internal Server Error");
}
});
app.post("/convertHtmlToImg", async (req, res) => {
try {
const browser = await puppeteer.launch({
headless: true,
});
const page = await browser.newPage();
// Set viewport width and height
await page.setViewport({ width: 1280, height: 720 });
let type = req.body.type;
async function findTemplate() {
switch (type) {
case "average":
return await fs.readFile("./templates/average.html", {
encoding: "utf8",
});
case "regulatory":
return await fs.readFile("./templates/regulatory.html", {
encoding: "utf8",
});
default:
return await fs.readFile("index.html", { encoding: "utf8" });
}
}
// Read the HTML content from the input HTML file
const htmlContent = await findTemplate();
await page.setContent(htmlContent);
// Navigate to a data URL with the HTML content
await page.goto(`data:text/html,${htmlContent}`, {
waitUntil: "networkidle0",
});
// const imageBuffer = await page.screenshot();
// Capture screenshot
const imageBuffer = await page.screenshot({
path: `images/chart${new Date().getTime()}.png`,
type: "png",
fullPage: true,
});
await browser.close();
res.set("Content-Type", "image/png");
// res.send(imageBuffer);
res.status(200).send(imageBuffer);
} catch (error) {
console.error("Error:", error);
res.status(500).send("Internal Server Error");
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});