John Davidson

javascript - FPDF - password protected pdf not downloading

0 comments
Message:


I am trying to generate a password protected pdf using my php script. This is my code:


JS:


 $.ajax({
url: 'backend.php',
type: 'POST',
data: {"input": "generate_pdf",
"password": document.getElementById("password").value},
success:function(response){
alert(response);
},
complete:function(){

}
});

PHP:


<?php
if(isset($_POST["input"])){
if($_POST["input"] == "sign in"){
ob_start();
require('FPDF_protection.php');
$pdf = new FPDF_Protection();
$pdf->SetProtection(array('print'), $_POST["password"]);
$pdf->AddPage();
$pdf->SetFont('Arial');
$pdf->Write(10,"Hello");
$pdf->Output('D',"Recovery_code.pdf");
ob_end_flush();
}
}
?>

But, when I run the code an alert pops up showing showing this:



%PDF-1.3 3 0 obj <</Type /Page /Parent 1 0 R /Resources 2 0 R
/Contents 4 0 R>> endobj 4 0 obj <</Filter /FlateDecode /Length 90>>
stream
Fҧ�J�1�v"I�E���2��vE�*��q�6/~=�Y�d@ྒྷ����-�����̾�M>~u�<�� �b} �f}-��b�
endstream endobj 1 0 obj <</Type /Pages /Kids [3 0 R ] /Count 1
/MediaBox [0 0 595.28 841.89]




endobj 5 0 obj <</Filter /FlateDecode /Length 364>> stream �r⹧����[�gFE��5'��Ά'oYt5��5hb%a�������Fc�2�g����d���u��Ɉ[��u�^$,���x�<FN�%jAKz}��8���I���_3m��
u!��}~@�y�<?>����|��ḣ���n0X�9X�0J8OG���6(���c[��E�#�R�m�ۮ��8w�-��~��n�
��ؿ��XϻG��^��t�8BF����������E�����֖�H
�7T^�~u�A�{:�y>�csG?�xo�;��q��[J�_W)�"j� �,O�7n\9�olN�8n





I don't understand, why the pdf isn't downloading. Please help me.



My Answer:
action: 'generate_pdf',_ password: 'mypassword'_ },_ success: function(response) {_ console.log(response);_ window.location.href = 'download.php';_ }_ });_PHP (backend.php):_ if ($_POST['action'] == 'generate_pdf') {_ require('fpdf.php');_ $pdf = new FPDF();_ $pdf->SetProtection(array('print', 'copy'), $_POST['password']);_ $pdf->AddPage();_ $pdf->SetFont('Arial','B',16);_ $pdf->Cell(40,10,'Hello World!');_ $pdf->Output('F', 'mypdf.pdf');_ echo 'PDF generated successfully';_ }_download.php:_ $file = 'mypdf.pdf';_ header('Content-Description: File Transfer');_ header('Content-Type: application/pdf');_ header('Content-Disposition: attachment; filename="'.basename($file).'"');_ header('Content-Transfer-Encoding: binary');_ header('Expires: 0');_ header('Cache-Control: must-revalidate');_ header('Pragma: public');_ header('Content-Length: ' . filesize($file));_ ob_clean();_ flush();_ readfile($file);_When I run this code, the pdf is generated successfully with the password protection. But when I try to download the pdf using the download.php script, the pdf is not downloaded. Instead, the content of the pdf is displayed on the browser. How can I make the pdf download with the password protection intact?

Rate this post

3 of 5 based on 6295 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us