Search code examples
phpmpdf

Can i set password for already generated pdf file using mpdf or any other php pdf libraries


I need to set password for my already generated pdf file using mpdf in php.


Solution

    1. I convert my already generated pdf to jpeg using imagick() extention in php.
    2. Again i convert the jpeg to pdf using TCPDF.
    3. I set the password while i am converting jpeg to pdf using TCPDF.

    sry for the worst english.

    Below is my code:

    //Convert pdf to jpg $imagick = new imagick();

                $imagick->readImage(base_url().'pdffiles/'.$faxid.'.pdf');
    
                foreach($imagick as $i => $imagick) {
    
                    $imagick->setImageFormat('jpeg');
    
                    $imagick->setResolution(300,300);
    
                    header('Content-Type: image/jpeg');
    
                    $path1 = './pdffiles/'.$faxid.'_'.$i.'.jpg';
    
                    file_put_contents($path1, $imagick ); 
                }
    
                // Convert jpg to pdf with password protection
                $this->load->library('Tc_pdf');
                $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT,  true, 'UTF-8', false);
    
                $pdf->SetProtection(array('print', 'copy','modify'), $loggedInUser, "ourcodeworld-master", 0, null);
    
                $pdf->SetCreator(PDF_CREATOR);
    
                $pdf->SetFont('courier', '', 20);
                $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    
                //$dir = base_url()."/pdffiles/";
                $map = directory_map('./pdffiles/');
                foreach ($map as $key => $value) {
                    $extention = explode('.', $value);
                    if($extention[1] == 'jpg') {
                      $pdf->AddPage();
                      $img = file_get_contents('./pdffiles/'.$value);
                      $pdf->Image('@' . $img, 20, 20, '', '', 'JPG', '', 'T', false, 100, '', false, false, 0, false, false, false);
    
                    }
    
                }
    
                foreach ($map as $key => $value) {
                    @unlink('./pdffiles/'.$value);
                }   
    
                $pdf->Output('example.pdf', 'I');