Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

Decrypt an encrypted pdf using MPDF

Is there any way to decrypt a pdf using MPDF library (PHP)?

I am receiving a pdf from 3rd party and they are using FPDI to encrypt it. I am using MPDF to make it password protected. It's easy to make a password protected pdf when it's not encrypted while on accessing the encrypted pdf I am getting this exception:

   This PDF document is encrypted and cannot be processed with FPDI

I believe this is not possible and this can be done once I have the key to decrypt the pdf, still want to double confirm if there is anyway to by-pass this?

Works all good for non encrypted pdfs.

    try{
        $mpdf = new \Mpdf\Mpdf();
        $filename = "pdfs/signed.pdf";
        password="Test";
        $pagecount = $mpdf->SetSourceFile($filename); //use any pdf you want
        for ($i= 1; $i<=$pagecount; $i++ ){
            $tplId = $mpdf->importPage($i);
            $mpdf->UseTemplate($tplId);
            $mpdf->AddPage();
        }

        echo "setting protection </br>";
        $mpdf->SetProtection(array(), $password, $password);
        echo "saving file: </br>";
        $mpdf->Output($filename, \Mpdf\Output\Destination::FILE);

        echo "done";

     } catch (Exception $ex) {
         echo "exception : ";
         echo $ex->getMessage();
     } 

Upvotes: 0

Views: 1768

Answers (1)

Jan Slabon
Jan Slabon

Reputation: 5058

FPDI cannot import pages of encrypted PDF documents.

If you know the owner password, you may decrypt it with the use of the SetaPDF-Core component (not free) before you pass it to FPDI:

$writer = new SetaPDF_Core_Writer_File('result.pdf');
$document = SetaPDF_Core_Document::loadByFilename('encrypted.pdf', $writer);

// get an instance of the security handler
$secHandler = $document->getSecHandler();
if ($secHandler) {
    // try to authenticate as the owner
    if (!$secHandler->authByOwnerPassword('OWNER PASSWORD')) {
        throw new Exception('Unable to authenticate as "owner".');
    }

    // remove security handler
    $document->setSecHandler(null);
}

$document->save()->finish();

Upvotes: 1

Related Questions