I had a problem earlier in the week where I needed to merge multiple PDF files together so they could be printed in one long run. I thought it was going to be one of those tasks that caused me to have a serious headache, but to my surprise it was rather easy.
Lets say you have 5 PDF files named “doc_1.pdf, doc_2.pdf, doc_3.pdf, doc_4.pdf and doc_5.pdf” and you need them to be merged into one file called “docs_joined.pdf”. All you have to do is use the following function:
shell_exec();
This function executes a command via shell and in this case the Linux command you want to call is ‘gs’, which is Ghostscript, a PostScript and PDF language interpreter and previewer.
So using both shell_exec() and ‘gs’ we would do the following to join the PDFs together:
$output = shell_exec(‘gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=docs_joined.pdf doc_1.pdf doc_2.pdf doc_3.pdf doc_4.pdf doc_5.pdf);
And you’re done. Simple!


Thank you for the post, this works great than the PHP scripts I am currently using!
-nert
Comment by Nert — March 5, 2010 @ 2:42 am
Thanks this is great i was looking for solution to merge multiple pdfs and seen many tools and integrated some tools but they are all having some problems but this is really simple and fast.
Cheers ,
Moneesh
Comment by Moneesh — March 23, 2010 @ 8:22 am
Hi,
It looks like a great script to me but it won’t work for me.
Does it need specific things on the server?
Thanks in advance
Niels
Comment by Niels — March 23, 2010 @ 4:01 pm