-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
213 lines (189 loc) · 6.49 KB
/
index.js
File metadata and controls
213 lines (189 loc) · 6.49 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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
const express = require("express");
const fs = require("fs");
const app = express();
const multer = require("multer");
const path = require("path");
const { exec } = require("child_process");
const port = process.env.PORT || 3200;
// app.set('views', path.join(__dirname, 'views'));
app.set("view engine", "ejs");
app.set("views", path.resolve("./views"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.get("/", (req, res) => {
return res.render("index");
});
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads");
},
filename: function (req, file, cb) {
cb(
null,
`${path.basename(
file.originalname,
path.extname(file.originalname)
)}_${Date.now()}.pdf`
);
},
});
const upload = multer({ storage: storage });
const compressPDF = async (inputPaths, outputPaths) => {
try {
console.log("Input Paths:", await inputPaths);
console.log("Output Paths:", await outputPaths);
return new Promise(async (resolve, reject) => {
for (let i = 0; i < inputPaths.length; i++) {
// Read file
// const filename = path.basename(outputPaths[i]);
// const filepath = outputPaths[i];
// const docxBuf = await fs.readFile(inputPaths[i]);
const inputPath = inputPaths[i];
const outputPath = outputPaths[i];
// const quality = "/screen";
const cmd = `gs -sDEVICE=pdfwrite \
-dCompatibilityLevel=1.4 \
-dNOPAUSE -dQUIET -dBATCH \
-dColorImageDownsampleType=/Average \
-dColorImageResolution=72 \
-dGrayImageDownsampleType=/Average \
-dGrayImageResolution=72 \
-dMonoImageDownsampleType=/Average \
-dMonoImageResolution=72 \
-dColorImageFilter=/DCTEncode \
-dGrayImageFilter=/DCTEncode \
-dAutoFilterColorImages=false \
-dAutoFilterGrayImages=false \
-dEncodeColorImages=true \
-dEncodeGrayImages=true \
-dDownsampleColorImages=true \
-dDownsampleGrayImages=true \
-dDownsampleMonoImages=true \
-dPDFSETTINGS=/screen \ -sOutputFile="${outputPath}" "${inputPath}"`;
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.error(`Compression failed: ${error.message}`);
reject(error);
} else {
console.log("PDF compression successful:", outputPath);
// resolve(outputPath);
resolve({
message: "File compression successfully",
files: outputPaths,
});
}
});
}
});
} catch (error) {
console.error("Error writing file:", error);
reject({
message: "File compression failed",
filename,
});
}
};
app.post("/upload", upload.array("files"), async (req, res) => {
console.log("Files uploaded:", await req.files);
try {
const files = await req.files;
const inputPaths = [];
const outputPaths = [];
if (!files || files.length === 0) {
return res.status(400).json({ message: "No files uploaded" });
}
for (const file of files) {
const inputPath = path.join(__dirname, "uploads", file.filename);
const outputPath = path.join(
__dirname,
"downloads",
`${path.basename(file.filename, path.extname(file.filename))}.pdf`
);
inputPaths.push(inputPath);
outputPaths.push(outputPath);
}
console.log("Input Paths:", inputPaths);
console.log("Output Paths:", outputPaths);
const response = await compressPDF(inputPaths, outputPaths);
if (response) {
console.log("Conversion successful:", response);
setTimeout(() => {
// Delete input files after conversion
outputPaths?.forEach((outputPath) => {
fs.unlink(outputPath, (err) => {
if (err) {
console.error("Error deleting input file:", err);
} else {
console.log("Input file deleted:", outputPath);
}
});
});
}, 120000);
return res.status(200).json({
message:await response.message,
filepaths:await response.files, // return absolute paths if you use them in download
});
}
else {
return res.status(500).json({ message: "File conversion failed" });
}
} catch (error) {
console.error("Upload error:", error);
return res.status(500).json({
message: "File conversion failed",
error: error.message,
});
}
});
app.post("/download_single_file", async (req, res) => {
try {
console.log(req.body);
const filepath = req.body.filepath;
console.log("Filepath received for download:", filepath);
if (!filepath || typeof filepath !== "string") {
return res.status(400).json({ error: "Invalid or missing filepath" });
}
const absolutePath = filepath;
const filename = filepath.split("/").pop();
// const absolutePath = path.join(__dirname, filepath);
// const filename = path.basename(filepath);
res.setHeader("Content-Disposition", `attachment; filename=${filename}`);
res.setHeader("Content-Type", "application/pdf");
res.download(absolutePath, filename, (err) => {
if (err) {
console.error("Error downloading file:", err);
res.status(500).send("Failed to download file");
} else {
fs.unlink(absolutePath, (err) => {
if (err) {
console.error("Error deleting file:", err);
} else {
console.log("File deleted successfully");
}
});
}
});
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal server error" });
}
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
module.exports = app;
// Ghost Script
// const compressPDF = (inputPath, outputPath) => {
// Command to run Ghostscript for PDF compression
// const command = `"C:\\Program Files\\gs\\gs10.02.1\\bin\\gswin64c.exe" -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dBATCH -sOutputFile=${outputPath} ${inputPath}`;
// const command = `"C:\\Program Files\\gs\\gs10.02.1\\bin\\gswin64c.exe" -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=${outputPath} ${inputPath}`;
// Execute the command using exec
// exec(command, (error, stdout, stderr) => {
// // Handle the result of the command execution
// if (error) {
// console.error(`Error compressing PDF: ${stderr}`);
// } else {
// console.log(`PDF compressed successfully: ${outputPath}`);
// }
// });
// };