How to create a password protected pdf file

北战南征 提交于 2019-11-27 15:23:57

问题


I'm using html2fpdf for creating PDF documents. Now once I have created that, I want to make sure that the PDF file is password protected. How can this be done in PHP?


回答1:


Download the library I am using from 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 );
?>



回答2:


I was never able to find a direct php solution to this problem. I ended up using pdftk and using shell_exec() to call the binary once the pdf file was generated/uploaded.

It accepts a syntax like this:

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


来源:https://stackoverflow.com/questions/2545804/how-to-create-a-password-protected-pdf-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!