0

as mentioned in the title I am trying to pass pdf from backend php to frontend using jquery.

Sample php code.

public function printPdf(){
    header('Content-Disposition: attachment; filename="kainos.pdf"');
    $html = $this->request->post['pdf'];
    $mpdf = new \Mpdf\Mpdf();
    $mpdf->WriteHTML('<div>Section 1 text</div>');
    return $mpdf->Output();
}
function(response){
    var blob=new Blob([response], { type: 'application/pdf' });
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="Kainos.pdf";
    link.click();
}

What i get is empty pdf.

What i know :

Data is being transfered correctly, since plain html can be transfered and seen using javascript console.log

Pdf is being generated, since i can just move the contents of the function to other function and get the pdf in other page, but i don't need it there.

I suspect that pdf is getting destroyed while being transfered, but can't seem to find any information on how to fix it. Any help is appreciated

EDIT

Problem was not in the method I am sending but in jquery, it handles blobs wierd, so I am in the middle of rewriting everything in vanila js.

var xhr = new XMLHttpRequest();
xhr.open('POST', document.location.origin + '/somelocation.php', true);
    //Send data to server
    xhr.send({$("#pdf").html()});
    //Set response type to file
    xhr.responseType = "blob";
    
    //On response do...
    xhr.onload = () => {
        //Create file in client side from xhr response
        var blob=new Blob([xhr.response], { type: 'application/pdf' });
        //create clickable element to download file and click it.
        var link=document.createElement('a');
        link.href=window.URL.createObjectURL(blob);
        link.download="kainos.pdf";
        link.click();
    }
});
Community
  • 1
  • 1
Nikas Nikis
  • 45
  • 1
  • 9
  • 1
    Does this answer your question? [Download a file by jQuery.Ajax](https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax) – Laurent S. Nov 18 '19 at 10:59

1 Answers1

0

Try sending some more headers with your php script (And modifying your current one):

public function printPdf(){
    ob_clean();
    header('Content-type: application/pdf');
    header('Content-Disposition: inline; filename="kainos.pdf"');
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    $html = $this->request->post['pdf'];
    $mpdf = new \Mpdf\Mpdf();
    $mpdf->WriteHTML('<div>Section 1 text</div>');
    return $mpdf->Output();
}
Henry Howeson
  • 677
  • 8
  • 18