Merge Multiple PDF's in PHP using shell_exec()

I had a bunch of PDF's that needed to be merged into one PDF file and present it as a file download to the user.  To do this I first installed Pdftk (the pdf tookit) on the server then ran the command via shell_exec().  Steps with code below.

  • SSH into the server and run apt-get install pdftk.
  • The command line to merge is pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf where 1.pdf, 2.pdf and 3.pdf are the files to merge and 123.pdf is the merged file.
  • PHP Code:
  $command = 'pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf';
  $result = shell_exec($command);
  header('Content-disposition: attachment; filename=123.pdf');
  header('Content-type: application/pdf');