Reputation: 417
I'm trying to merge multiple PDF files on my server using Ghostscript with the following code :
$files = array(
'1.pdf',
'2.pdf',
'3.pdf'
);
$output = 'single.pdf';
$cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=$output ";
foreach($files as $file)
$cmd .= "pdfs/$file ";
var_dump(shell_exec($cmd));
The script that I use is in the root folder and the PDF files are in a folder named pdfs :
/[pdfs]
|__ 1.pdf
|__ 2.pdf
|__ 3.pdf
script.php
The permissions for the folders and files are all 777
.
But despite all this, nothing is happening and the returned value is NULL
.
So what am I doing wrong ? What is the exact way to merge multiple PDF files into one using Ghostscript ?
Upvotes: 1
Views: 4035
Reputation: 31141
Just a side comment; Ghostscript does not 'merge' PDF files, it can take multiple PDF files as an input and create a brand new PDF file whose visual appearance should be the same as the inputs, but it isn't merging the PDF files, the input is fully interpreted and the new file has nothing other than appearance in common with the input files.
So, are you certain Ghostscript is working properly ? Have you tried processing a single PDF file ? Does it work ?
If not then the most likely problem is that you don't have the directory containing the Ghostscript executable in your $PATH environment variable (this is a common problem). You can test this by supplying a fully qualified path to the Ghostscript executable in your command line, so instead of:
$cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=$output ";
Try something like :
$cmd = "/usr/local/bin/gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=$output ";
Obviously you will have to modify the path to match your setup. If that works, then the problem is likely to be that the directory isn't in $PATH, you can either add it or just use the full path.
There is also a logical error I can't help you with;
It looks to me like your 'foreach' is going to invoke cmd once for each of the files in the array. That means each file is going to be processed by a call to Ghostscript. So each file will produce a separate PDF file. Since they are all using the same OutputFile, they will overwrite each other.
If you want a single output to be created using the input of all the files, you need to call Ghostscript exactly once, not once per input file, and the command line needs to include all of the input files.
In essence what you have now is:
gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=single.pdf 1.pdf
gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=single.pdf 2.pdf
gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=single.pdf 3.pdf
What you want is:
gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=single.pdf 1.pdf 2.pdf 3.pdf
Since I know nothing about PHP I can't tell you how to correct that.
Upvotes: 3