I am using the below files in my directory
index.html The form is as below
<div class="container">
<h1 class="text-center my-3">Lazy PDF Merger</h1>
<hr>
<form class="my-2" method="post" action="/merge" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleFormControlFile1">Select the PDF files you like to merge.</label>
<input type="file" name="pdfs" class="form-control-file" id="exampleFormControlFile1" multiple accept=".pdf">
<!-- multiple ==> allows multiple files selection and accept does validation for pdf files,name="pdfs" is used with multer -->
<input type="submit" value="Merge" class="btn btn-primary my-4">
<!-- <button class="btn btn-primary my-2">Merge</button> -->
</div>
</form>
</div>
server.js
const express = require('express')
const app = express()
// Always place above two lines at top of codes
const path = require('path')
const multer = require('multer')
const {mergePdfs} = require('./pdfmerger') // mergePdfs is destructured here
const upload = multer({ dest: 'uploads/' })
// const mergePdfs = require('mergePdfs') // for this to work
app.use('/static', express.static('public'))
const port = 3000
app.get('/', (req, res) => {
// res.send('Hello Rameez Ahmad sir Welcome to the server!')
// res.sendFile("templates/index.html") ===> won't work a absolute path is required
res.sendFile(path.join(__dirname,"templates/index.html"))
})
// below folder is made async to wait till pdfs get merged
app.post('/merge',upload.array('pdfs',2), async (req, res) => {
console.log(req.files) // see the details of pdfs in terminal
let d=await mergePdfs(path.join(__dirname,req.files[0].path),path.join(__dirname,req.files[1].path))
// res.redirect(`http://localhost:3000/static/${d}.pdf`) // This line directly opens pdfs
res.send({data:req.files})
})
app.listen(port, () => {
console.log(`Example app listening on port http://localhost:${port}`)
})
pdfmerger.js
const PDFMerger = require('pdf-merger-js');
let mergePdfs= async (p1,p2) => {
var merger = new PDFMerger();
await merger.add(p1); //merge all pages. parameter is the path to file and filename.
await merger.add(p2); //merge all pages. parameter is the path to file and filename.
// await merger.save('merged.pdf'); //save under given name and reset the internal document
let d=new Date().getTime() // gives milliseconds till 1971
await merger.save(`public/${d}.pdf`) // This is done to differentiate pdfs merged by clients
return d
// await merger.save('public/merged.pdf'); //save under given name and reset the internal document
};
module.exports ={mergePdfs}
I tried a lot to fix this but i don't know why the order of pdf is not considered whenever i select pdf1 and pdf2 from my file location i am getting a merged pdf and i am getting the same merged pdf as previous if i reverse the order of selection pdf2 and pdf1.How to maintain the order ?My Directory Structure