如何用PHP密码保护上传的PDF

时间:2012-10-03 02:00:09

标签: php security passwords

我有一个用户可以上传PDF文档的Web应用程序。是否有可用于密码保护PDF文件的PHP库?我需要库来保留原始PDF的所有方面(即大小,字体,分辨率等)。

1 个答案:

答案 0 :(得分:6)

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'));

//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);
    $pdf->addPage();
    $pdf->useTemplate($tplidx);
}

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

return $destFile;
}

//password for the pdf file
$password = 'info@domain.com';

//name of the original file (unprotected)
$origFile = 'book.pdf';

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

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

修改 Original source of library used。请注意,上面的答案未使用原始来源的脚本进行测试。我从上面的第三方链接下载,但我没有检查它们是否完全一样。