如何在 PHP 中对上传的 PDF 文件进行密码保护

3

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


6
你希望为文件设置密码保护,是只在从网络应用程序中打开时需要输入密码,还是对文件本身进行保护? - Justin Wood
1个回答

8

下载用于保护PHP中的PDF文件所使用的库:

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

编辑 使用的库的原始来源。请注意,我上面的答案没有使用来自原始来源的脚本进行测试。我从上面的第三方链接下载,并且我没有检查它们是否完全相同。


1
请指定您下载该库的来源。该页面将比直接链接到库更有帮助。 - mccbala
1
@mccbala请看我的修改。如果您觉得有用,请给问题和答案点赞。 - Favourite Onwuemene
当我尝试使用任何现有的PDF文件时,会出现错误提示:“此文档可能使用了FPDI免费解析器不支持的压缩技术。(请参阅https://www.setasign.com/fpdi-pdf-parser了解更多详细信息)” - Anakbhai Gida
1
在使用命名空间和引导程序的Laravel或任何其他应用程序中,可以选择使用FPDI与TCPDF。文档位于https://github.com/Setasign/FPDI。它允许您使用TCPDF的SetProtection()方法。 - XaviQV

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接