You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

156 lines
4.8 KiB
JavaScript

const express = require("express");
const router = express.Router();
const fs = require("fs");
const path = require("path");
const lastFilesDir = "./public/upload/converted/";
const rawDir = "./public/upload/raw/";
const renderPageName = "invoice_sign";
const signDir = "./public/img/imza.png";
const stampDir = "./public/img/kase.png";
const orderReccentFiles = (dir) => {
return fs
.readdirSync(dir)
.filter((file) => fs.lstatSync(path.join(dir, file)).isFile())
.map((file) => ({ file, mtime: fs.lstatSync(path.join(dir, file)).mtime }))
.sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
};
const { PDFDocument } = require("pdf-lib");
const signPDF = async (sourceFile) => {
// Fetch PNG image
const pngUrl = signDir;
const pngSignBytes = fs.readFileSync(signDir);
const pngStampBytes = fs.readFileSync(stampDir);
const pBytes = fs.readFileSync(rawDir + sourceFile);
const pdfDoc = await PDFDocument.load(pBytes);
// Embed the JPG image bytes and PNG image bytes
const pngSign = await pdfDoc.embedPng(pngSignBytes);
const pngStamp = await pdfDoc.embedPng(pngStampBytes);
// Get the width/height of the PNG image scaled down to 50% of its original size
const pngSignDims = pngSign.scale(0.1);
const pngStampDims = pngStamp.scale(0.1);
// Add a blank page to the document
const pages = pdfDoc.getPages();
// Draw the PNG image near the lower right corner of the JPG image
page = pages[0];
page.drawImage(pngStamp, {
x: page.getWidth() / 2 - pngStampDims.width / 2 + 75,
y: page.getHeight() / 2 - pngStampDims.height,
width: pngStampDims.width,
height: pngStampDims.height,
});
page.drawImage(pngSign, {
x: page.getWidth() / 2 - pngSignDims.width / 2 + 75,
y: page.getHeight() / 2 - pngSignDims.height,
width: pngSignDims.width,
height: pngSignDims.height,
});
// Serialize the PDFDocument to bytes (a Uint8Array)
const pdfBytes = await pdfDoc.save();
if (!fs.existsSync(lastFilesDir)) {
fs.mkdirSync(lastFilesDir, { recursive: true });
}
fs.writeFileSync(lastFilesDir + sourceFile, await pdfDoc.save());
return pdfBytes;
};
// load the page
router.get("/", function (req, res) {
let lastFiles = [];
if (!fs.existsSync(lastFilesDir)) {
fs.mkdirSync(lastFilesDir, { recursive: true });
}
// const dir = fs.opendirSync(lastFilesDir);
let filesOrdered = orderReccentFiles(lastFilesDir);
if (filesOrdered.length > 5) {
for (let index = 5; index < filesOrdered.length; index++) {
filePath = lastFilesDir + filesOrdered[index].file;
fs.unlinkSync(filePath);
}
}
filesOrdered = orderReccentFiles(lastFilesDir);
for (file of filesOrdered) {
lastFiles.push({ type: "f", name: file.file });
}
// lastFiles.push({ type: "f", name: getMostRecentFile(lastFilesDir).file });
res.render(renderPageName, { lastFiles });
});
//Post the upload file
// For handling the upload request
router.post("/", function (req, res) {
// When a file has been uploaded
if (req.files && Object.keys(req.files).length !== 0) {
// Uploaded path
const uploadedFile = req.files.uploadFile;
// Logging uploading file
console.log(uploadedFile);
// Upload path
const uploadPath = rawDir;
if (!fs.existsSync(uploadPath)) {
fs.mkdirSync(uploadPath, { recursive: true });
}
// To save the file using mv() function
uploadedFile.mv(uploadPath + uploadedFile.name, function (err) {
if (err) {
console.log(err);
res.send("Failed !!");
}
// res.send("Successfully Uploaded !!");
else {
signPDF(uploadedFile.name);
res.redirect(renderPageName);
fs.unlinkSync(uploadPath + uploadedFile.name);
}
});
} else res.send("No file uploaded !!");
});
// To handle the download file request
router.get("/download", function (req, res) {
const downloadFile = lastFilesDir + req.query.downloadFile;
console.log(downloadFile);
res.setHeader(
"Content-Disposition",
"attachment; filename=" + req.query.downloadFile
);
res.download(downloadFile, function (err) {});
});
const multer = require("multer");
const fileStorageEngine = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./public/upload/raw");
},
filename: (req, file, cb) => {
console.log(req.files[0].buffer);
const fileName = decodeURI(file.originalname);
console.log(fileName);
cb(null, fileName);
},
});
const upload = multer({ storage: fileStorageEngine });
router.post("/upload_files", upload.array("files"), uploadFiles);
function uploadFiles(req, res) {
signPDF(req.files[0].originalname);
// console.log(req.files);
// console.log(req.files[0].toString("latin1"));
res.setHeader("content-type", "text/html; charset=utf-8");
res.setHeader("Access-Control-Allow-Origin", "*");
res.json({ message: "Successfully uploaded files" });
}
module.exports = router;