Merge Multiple PDF Files with PHP
This tutorial explains how to successfully merge multiple PDF files using pdftk and PHP. A recent project of ours required this functionality, and we hope this tutorial saves you some time.
Here are some initial tips:
- Don't try to use ImageMagick and/or GhostScript to merge the files.
- Use passthru() instead of exec() or system() to run the pdftk command.
Step One: Install pdftk on your server (CentOS)
You must have pdftk running on your server in order for any of this to work. You also must have root access to your server. If not, see if your hosting provider can install this for you. If you're not running CentOS, you may be able to find your RPM here.
- Login to SSH
- cd /usr/src
- wget http://chrisschuld.com/wp-content/uploads/2008/05/pdftk-112-1i386.rpm
- rpm -i pdftk-112-1i386.rpm
- You're done installing pdftk (if everything goes well).
Step Two: Build the form to upload your PDF files
In our project we actually worked with PDF files that were uploaded by the client in an administrative area, which could then be selected in a list before submitting the form to merge the files. In this tutorial, we're going to do everything at once.
Here's what happens when this form is submitted:
- Files are uploaded the server
- An array is built containing the names of the uploaded files
- The merged file is created using the pdftk
- The merged PDF opens in the browser
Demo | Source Code
This is the most basic example of how to merge PDF files with PHP. There are many other possibilities, but this should help get you started.
pdftk for CentOS5 (AccessPDF for CentOS 5)