如何创建受密码保护的pdf文件

时间:2010-03-30 14:05:20

标签: php pdf-generation password-protection fpdf

我正在使用html2fpdf来创建PDF文档。现在,一旦我创建了它,我想确保PDF文件受密码保护。如何在PHP中完成?

2 个答案:

答案 0 :(得分:5)

a blog post on the ID Security Suite site下载我正在使用的库:

<?php
    function pdfEncrypt ($origFile, $password, $destFile){
        require_once('FPDI_Protection.php');
        $pdf =& new FPDI_Protection();
        $pdf->FPDF('P', 'in');
        //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 (I suggest using the email adress of the purchaser).
    $password = "testpassword";
    //Name of the original file (unprotected).
    $origFile = "sample.pdf";
    //Name of the destination file (password protected and printing rights removed).
    $destFile ="sample_protected.pdf";
    //Encrypt the book and create the protected file.
    pdfEncrypt($origFile, $password, $destFile );
?>

答案 1 :(得分:0)

我永远无法找到这个问题的直接php解决方案。我最终使用pdftk并在生成/上传pdf文件后使用shell_exec()来调用二进制文件。

它接受如下语法:

pdftk 'inputfile.pdf' output 'outputfile.pdf' user_pw pass1234 owner_pw pass4321