I created the password protection using the following code,
$dompdf = new Dompdf(array('enable_remote' => true)); $dompdf->loadHtml($html_print); #(Optional) Setup the paper size and orientation $dompdf->setPaper('A4', 'landscape'); #Render the HTML as PDF $dompdf->render(); #PASSWORD PROTECTION $dompdf->getCanvas() ->get_cpdf() ->setEncryption(1234, 5678, ['print', 'modify', 'copy', 'add']); #Output the generated PDF to Browser $dompdf->stream($filename); #SAVE THE FILE TO SERVER $output = $dompdf->output(); $filename = $filename.'-'.time().'.pdf'; file_put_contents('../documents/'.$filename, $output);
It works fine when I download the file.
I also save this file in the server before downloading. But when I try to download the file later, it cannot be opened with the correct password. If I don't set password protection it works smoothly
Can anyone help me?
P粉4289867442024-03-27 10:44:35
Found the problem. There is a key named "p" on the encrypted information array, which they call the "p-value". When the PDF is streamed, the p-value changes from 252 to -4. The part of the code that does this is commented:
Since the p value changes during the first output, the second time you output the pdf, it writes the file with the wrong value.
It seems to me that you have two solutions. The first approach is to output the PDF to a file first and then write your own code to echo that file to the browser, or you can reset the p-value between the stream and the output like this:
#PASSWORD PROTECTION $cpdf = $dompdf->getCanvas() ->get_cpdf(); $cpdf->setEncryption(1234, 5678, ['print', 'modify', 'copy', 'add']); #Output the generated PDF to Browser $infoB4 = $cpdf->objects[$cpdf->arc4_objnum]['info']; $dompdf->stream($filename); #SAVE THE FILE TO SERVER $cpdf->objects[$cpdf->arc4_objnum]['info'] = $infoB4; $output = $dompdf->output();
Hope this helps.