Protect PDF using php



Protect PDF using PHP.

Download the library used: Protect PDF in PHP

<?php

function pdfEncrypt ($origFile, $password, $destFile){

    //include the FPDI protection http://www.setasign.de/products/pdf-php-solutions/fpdi-protection-128/
 require_once('fpdi/FPDI_Protection.php');

$pdf =& new FPDI_Protection();
// set the format of the destinaton file, in our case 6×9 inch
// $pdf->FPDF('P', 'in', array('6','9'));
$pdf->FPDF("P");

//calculate the number of pages from the original document
$pagecount = $pdf->setSourceFile($origFile);

// copy all pages from the old unprotected pdf in the new one
for ($loop = 1; $loop <= $pagecount; $loop++) {
 
    $tplidx = $pdf->importPage($loop);
    $size = $pdf->getTemplateSize($tplidx);
    $pdf->w; // Width of Current Page
    $pdf->h; // Height of Current Page
    $pdf->AddPage();
    $pdf->useTemplate($tplidx, 0, 0, 0, 0, true);
}

// protect the new pdf file, and allow no printing, copy etc and leave only reading allowed
$pdf->SetProtection(array("annot-forms"),$password);
$pdf->Output($destFile, 'F');
// $pdf->Output();
return $destFile;
}


?>


Now Call the function



//password for the pdf file
$password = '';

//name of the original file (unprotected)
$origFile = '26568_Online-Radio-With-Material-Design.pdf';

//name of the destination file (password protected and printing rights removed)
$destFile ="upload/hello.pdf";

//encrypt the book and create the protected file
pdfEncrypt($origFile, $password, $destFile );