Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

Merging PDFs using PHP and ghostscript

In this post, We will show you how you can use Ghostscript with PHP 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 Ghostscript / PHP

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

function merge_pdfs($pdf_files,$output_file) {
  $pdf_files = implode(" ",$pdf_files);
  return shell_exec("gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=$output_file -dBATCH $pdf_files");
  1. Hello!
    To complete your article, please:

    1. Explain for Windows Server as well.
    2. What version of Ghostscript should we use (for windows server)? [Download link from Ghostscript site?]
    3. Can special pages be selected? For example: 1-2, 6, 9, 10-15, etc.

    Thank you.

Leave a Reply