Creating a PDF Merger using Javascript and Express Js
Last Updated :
13 Mar, 2024
Certain forms require us to upload multiple documents as a single PDF file. We merge those files using any online PDF merger in such cases. This article focuses on creating our own PDF merger using Javascript and Express JS.
Prerequisites:
Syntax:
import PDFMerger from 'pdf-merger-js';
const merger = new PDFMerger();
Steps to Create the Application:
Step 1: Create a folder called "PDFTools" using the following command:
mkdir PDFTools
cd PDFTools
Step 2: Assuming Node.js has been installed in the device, set an npm package inside the above directory created using the below command.
npm init
Step 3: Make the following installations:
npm i nodemon –save-dev multer pdf-merger-js
Step 4: Add "type": "module" inside package.json, since all modules are ECMAScript modules.
Step 5: Inside package.json, under “scripts", add “start": "nodemon server.js”.
The updated dependencies in package.json:
"dependencies": {
"express": "^4.18.3",
"multer": "^1.4.5-lts.1",
"pdf-merger-js": "^5.1.1"
}
Folder Structure:
Folder StructureThe updated dependencies in package.json:
"dependencies": {
"express": "^4.18.3",
"multer": "^1.4.5-lts.1",
"pdf-merger-js": "^5.1.1"
}
Approach to Create a PDF Merger:
Explanation:
- For serving all static files which are inside the "public" folder:
app.use('/static', express.static('public'));
- For uploading the pdfs using the "name" attribute of the HTML input tag and allowing the upload of a maximum of 10 pdfs:
upload.array('pdfs', 10)
- For fetching the file objects:
req.files
- For sending the path of the files where they have been uploaded as arguments for the merge operation
for (let file of req.files) {
mergedFilePaths.push(path.join(__dirname, file.path));
}
merger.add(pdfFile);
- For saving the final merged PDF inside the public folder:
merger.save(`public/${mergedFileName}`);
Example: Below is the code exampple
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDF Merger</title>
</head>
<body>
<div>
<h2>PDFMerger - The Best Tool for Merging PDFs</h2>
<form method="post" action="/https/www.geeksforgeeks.org/merge" enctype="multipart/form-data">
<input type="file" id="myFile" name="pdfs" multiple accept=".pdf">
<br><br>
<input type="submit" value="Merge">
</form>
</div>
</body>
</html>
JavaScript
//mergePDF.js:
import PDFMerger from 'pdf-merger-js';
const merger = new PDFMerger();
const mergePDFs = async (pdfFiles) => {
for (const pdfFile of pdfFiles) {
await merger.add(pdfFile);
}
let d = new Date().getTime();
let mergedFileName = `merged_${d}.pdf`;
await merger.save(`public/${mergedFileName}`);
return mergedFileName;
}
export default mergePDFs;
JavaScript
//server.js
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import multer from 'multer';
import mergePDFs from './mergePDF.js';
const upload = multer({ dest: 'uploads/' });
const app = express();
const port = 3000;
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
app.use('/static', express.static('public'));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, "index.html"));
})
app.post('/merge', upload.array('pdfs', 10), async (req, res, next) => {
if (!req.files || req.files.length < 2) {
return res.status(400).send('Please upload at least 2 PDF files');
}
let mergedFilePaths = [];
for (let file of req.files) {
mergedFilePaths.push(path.join(__dirname, file.path));
}
let mergedFileName = await mergePDFs(mergedFilePaths);
res.redirect(`http://localhost:${port}/static/${mergedFileName}`);
})
app.listen(port, () => {
console.log(`Example app listening on port http://localhost:${port}`);
})
Step to Run the App:
npm start
Output:
Execution of the application
Similar Reads
How to Merge/Combine Arrays using JavaScript?
Given two or more arrays, the task is to merge (or combine) arrays to make a single array in JavaScript. The simplest method to merge two or more arrays is by using array.concat() method.Using Array concat() MethodThe contact() method concatenates (joins) two or more arrays. It creates a new array a
2 min read
Explain about Read and Write of a file using JavaScript
Handling file operations such as reading and writing is a common requirement in many JavaScript applications, especially on the server side using Node.js. This article explains how to perform these operations using Node.js's built-in fs (File System) module. The fs ModuleThe fs module provides an AP
3 min read
How to Use Embedded JavaScript (EJS) as a Template Engine in Express JS ?
Embedded JavaScript (EJS) is a simple templating language that helps us to generate HTML markup with plain JavaScript. It's commonly used with Node.js to create dynamic web pages. It also helps to incorporate JavaScript into HTML pages. Approach to use EJS as Template Engine in Express JS:Install EJ
2 min read
How to upload an image using HTML and JavaScript in firebase ?
Firebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides cloud st
3 min read
Server Side Rendering using Express.js And EJS Template Engine
Server-side rendering involves generating HTML on the server and sending it to the client, as opposed to generating it on the client side using JavaScript. This improves initial load time, and SEO, and enables dynamic content generation. Express is a popular web application framework for NodeJS, and
3 min read
Create an Express server with EJS Templating Engine
EJS (Embedded JavaScript) is a simple and popular templating engine for JavaScript. it is designed to generate HTML markup with plain JavaScript. EJS is commonly used in server-side web applications built with Node.js. It allows you to generate dynamic HTML pages. In this article, we will create stu
3 min read
How to insert request body into a MySQL database using Express js
If you trying to make an API with MySQL and Express JS to insert some data into the database, your search comes to an end. In this article, you are going to explore - how you can insert the request data into MySQL database with a simple Express JS app.Table of Content What is Express JS?What is MySQ
3 min read
How to Send Response From Server to Client using Node.js and Express.js ?
In web development, sending responses from the server to the client is a fundamental aspect of building interactive and dynamic applications. Express.js, a popular framework for Node.js, simplifies this process, making it easy to send various types of responses such as HTML, JSON, files, and more. T
4 min read
How to Merge/Flatten an array of arrays in JavaScript ?
Merging or flattening an array of arrays in JavaScript involves combining multiple nested arrays into a single-level array. This process involves iterating through each nested array and appending its elements to a new array, resulting in a flattened structure.To Merge or flatten array we can use arr
3 min read
How to render JSON in EJS using Express.js ?
EJS (Embedded JavaScript) is a templating language that allows dynamic content generation in NodeJS applications. It allows us to embed JavaScript code directly into Our HTML code, and with the help of that we can generate the dynamic content on the server side. So with the help of ejs, we can perfo
4 min read