Live Demo
You can see the live demo of the below project here
Get Started
In order to get started you need to install the library
npm i easy-pdf-merge
npm i express
npm i multer
npm i nodemon
Source Code
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 |
<!DOCTYPE html> <html> <head> <title>Merge Multiple PDF Files in Node and Express</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" /> </head> <body> <div class="container"> <h1 class="text-center"> Merge PDF Files </h1> <form action="/mergepdffilesdemo" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="files">Upload Single or Multiple PDF Files:</label> <input type="file" multiple name="files" class="form-control" required id=""> </div> <div class="form-group"> <button class="btn btn-danger btn-block"> Merge PDF </button> </div> </form> </div> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </html> |
index.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 |
const express = require("express"); const bodyParser = require("body-parser"); const fs = require("fs"); const pdfMerge = require('easy-pdf-merge'); const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); const PORT = process.env.PORT || 5000; app.use(express.static("public")); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "public/uploads"); }, filename: function (req, file, cb) { cb( null, file.fieldname + "-" + Date.now() + path.extname(file.originalname) ); }, }); var dir = "public"; var subDirectory = "public/uploads"; if (!fs.existsSync(dir)) { fs.mkdirSync(dir); fs.mkdirSync(subDirectory); } app.get('/mergepdf',(req,res) => { res.render('mergepdf',{title:"Concatenate or Merge Multiple PDF Files Online - Free Media Tools"}) }) var mergepdffilesupload = multer({storage:storage,fileFilter:mergepdffilter}) app.post('/mergepdf',mergepdffilesupload.array('file',100),(req,res) => { const files = [] outputFilePath = Date.now() + "output.pdf" if(req.files){ req.files.forEach(file => { console.log(file.path) files.push(file.path) }); pdfMerge(files,{output:outputFilePath}) .then((buffer) => { res.download(outputFilePath,(err) => { if(err){ fs.unlinkSync(outputFilePath) res.send("Some error takes place in downloading the file") } fs.unlinkSync(outputFilePath) }) }) .catch((err) => { if(err){ fs.unlinkSync(outputFilePath) res.send("Some error takes place in merging the pdf file") } }) } }) |
1 2 3 4 5 6 7 8 |
<div class="col-md-4 col-sm-6 col-xs-12"> <div class="content colour-6"> <h3 class="text-center">Merge PDF</h3> <div class="text-center"> <a class="btn btn-danger" href="/mergepdf">Convert Now</a> </div> </div> </div> |