Tagging & Protecting PDF Files using PHP
I recently had to run some tests on tagging/watermarking an existing PDF file, and then protecting it using php. First, you’ll need to download the proper libraries.
- http://fpdf.org/ – You must download the most recent version, as the following files work only with 1.53 or later.
- http://www.setasign.de/products/pdf-php-solutions/fpdi/downloads/ – Then download the primary FPDI class. Be sure to also download the FPDI_TPL class as it’s not included with the first package.
- http://www.setasign.de/products/pdf-php-solutions/fpdi-protection-128/downloads/ – Download this class so that we have access to the protection methods.
Extract all of those packages, get rid of non-essential files and place most everything in the same folder… “font” and “decoders” will likely be the only folders remaining.
Then, place your existing pdf in the same folder.
Then, create a new php file with the following code. You can modify the message or its position, or you can ready the manuals for the above packages for more options. To set a user/owner password, just add them as the second and third arguments for the SetProtection method (outside the array, which is the first argument).
[PHP]
define(‘FPDF_FONTPATH’,'font/’);
require(‘FPDI_Protection.php’);
class PDF extends FPDI_Protection
{
function Footer()
{
//Position at 1.5 cm from bottom
$this->SetY(-15);
//Arial italic 8
$this->SetFont(‘Arial’,'I’,8);
//Page number
$msg = “If you’re not ” . $_SERVER['REMOTE_ADDR'] . “, then you’ve stolen our stuff.”;
$this->Cell(0,10,$msg,0,0,’C');
}
}
$pdf= new PDF();
$pagecount = $pdf->setSourceFile(“document.pdf”);
for ($i=1; $i < = $pagecount; $i++) {
$tplidx = $pdf->ImportPage(1);
$pdf->addPage();
$pdf->useTemplate($tplidx,0,0,0);
}
$pdf->SetProtection(array(‘print’));
$pdf->Output(“newpdf.pdf”,”I”);
[/PHP]