Error – Failed to load PDF document when implementing FPDF_protection.php

  fpdf, javascript, php

I am trying to download an password protected PDF using my php script. My code is as follows:

JS

                  $.ajax({
                        url: 'backend.php',
                        type: 'POST',
                        data:   {"input": "generate_pdf",
                                "password": document.getElementById("password").value},
                        success:function(response){
                            
                                var blob = new Blob([response]);
                                var link = document.createElement('a');
                                link.href = window.URL.createObjectURL(blob);
                                link.download = "Myfile.pdf";
                                link.click();
                            
                        },  
                        complete:function(){

                        }
                    });

PHP

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    require('FPDF_protection.php');

    if(isset($_POST["input"])){
        if($_POST["input"] == "generate_pdf"){
              ob_start();
              $pdf = new FPDF_Protection();
              $pdf->SetProtection(array($_POST["password"]));
              $pdf->AddPage();
              $pdf->SetFont('Arial');
              $pdf->Write(10,"Hello there");
              $pdf->Output();
              ob_end_flush();       
        }
    }
?>

After executing the code, a pdf is downloaded, which upon opening shows

Error Failed to load PDF document.

Why is this happening? Please help me.

Source: Ask PHP

LEAVE A COMMENT