Posted by Arjun on Wednesday 26th September 2018

Merging PDFs using Nodejs and ghostscript

In this tutorial, We will show you how you can use Ghostscript with NodeJs to merge multiple PDF files into single file. Using Ghostscript, it is possible to merge multiple PDF files into a single PDF file with a single command from your terminal or command line.

Install Ghostscript

Type the command sudo apt-get install Ghostscript to download and install the Ghostscript package and all of the packages it depends on.

Merging PDFs with Ghostscript

Here is the Ghostscript command to merge two are more PDFs in a single file:

$ gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=merged_file.pdf -dBATCH file_1.pdf file_2.pdf

In the above command, we are merging two Pdf files called file_1.pdf and file_2.pdf files into single Pdf file called merged_file.pdf.

NOTE: The order of the input files matters and determines the merging order in the final PDF.

Merging PDFs with NodeJs using Ghostscript

We can run the preceding gs command with NodeJs's exec() function and we can also pass the filenames to it. Below is the sample php script:

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 = ['file_1.pdf','file_2.pdf']
const outputFile = 'merged_file.pdf'