Search code examples
phpyii2pdf-generationpassword-protectionmpdf

How to make pdf password protected in yii2 php


I want to make my pdf password protected.

I am using kartik\mpdf\Pdf extension for generating pdf.

             $pdf = new Pdf([
                // set to use core fonts only
                'mode' => Pdf::MODE_CORE,
                // A4 paper format
                'format' => Pdf::FORMAT_A4,
                // portrait orientation
                'orientation' => Pdf::ORIENT_PORTRAIT,
                // stream to browser inline
                'destination' => Pdf::DEST_FILE,
                // your html content input
                'content' => $html,
                // any css to be embedded if required
                'cssFile' => '@api/web/css/notes.css',
                // set mPDF properties on the fly
                'options' => ['title' => $note['title']],
                // call mPDF methods on the fly
                'methods' => [
                    'SetHeader' => [''],
                    'SetFooter' => [''],
                ],
            ]);
            $pdf->content = $html;
            $file_name = "test" . rand(7, 100).pdf";
            $password = "122":
            $pdf->setProtection(array(),$password); 
            $pdf->filename = "uploads/" . $file_name;

            echo $pdf->render();

But it gives me error like : Calling unknown method: kartik\mpdf\Pdf::setProtection();

I have also tried following code that is putting method after filename :

$pdf->filename->setProtection(array(), $password);

but it's also give me error like : Call to a member function setProtection() on string.

I know the setProtection method is available in vendor's kartik library but i am not sure of how to use it.

Please assist me if anyone has idea.


Solution

  • Try

    $pdf->getApi()->setProtection();
    

    Method getApi() is to directly call MPDF object and that is where SetProtection() method is.