How To Merge PDF Files In Node.js Application

Pankaj Kumar - Jul 6 '23 - - Dev Community

In this article, I will show you how to merge pdf files in Node.js application for linux system. Since many times we need to play with pdf files while web app development. With nodejs this task can easily be performed. With Node.js we will use Ghostscript, multiple PDF files can be merged into single PDF files.

Install dependencies

type below command over terminal to install Ghostscript


sudo apt-get install Ghostscript

Enter fullscreen mode Exit fullscreen mode

After running the above command Ghostscript will be installed in your system. Now with below Ghostscript command multiple PDF files can be merged into single PDF file.


gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=new-merged.pdf -dBATCH first.pdf second.pdf

Enter fullscreen mode Exit fullscreen mode

In the above command, we are merging a new file from two different file named first.pdf and second.pdf

Nodejs with Ghostscript

Let's have a look how we will use Ghostscript in our nodejs code. See the nodejs code below:


const util = require('util')
const exec = util.promisify(require('child_process').exec)

async function merge_pdfs(pdfFiles,outputFile) {
const { stdout, stderr } = await exec("gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=outputFile -dBATCH pdfFiles")
console.log('stdout:', stdout)
console.log('stderr:', stderr)
}

const pdfFiles = ['first.pdf','second.pdf']
const outputFile = 'new_merged.pdf'

merge_pdfs(pdfFiles,outputFile)

Enter fullscreen mode Exit fullscreen mode

Conclusion

So in this article, We learn how to merge pdf files in nodejs application.

That’s all for now. Thank you for reading and I hope this artible will be very helpful to understand how to merge pdf files in nodejs application .

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

This article is originally posted over jsonworld

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player