Home » Php » php – using AJAX and Jquery to create pdf using FPDF

php – using AJAX and Jquery to create pdf using FPDF

Posted by: admin July 12, 2020 Leave a comment


I am trying to create pdf file using FPDF.

What I right now have is an HTML page with various lines of data and a print button next to it. When someone clicks Print, I am sending corresponding data using Jquery by making AJAX call..

This is my JQUERY code:

$('.printbtn').live('click', function(){
    var printdata = 'name=' + name_t + '&address=' + address_t;        
    $.post('print.php', printdata, function(){
    return false;

this is print.php

 $name = $_POST['name'];
 $address = $_POST['address'];

 require ("fpdf17/fpdf.php");

 $pdf = new FPDF('P','mm',array(90,100));



 $pdf->Cell(0,10,'name: '.$name);
 $pdf->Cell(0,10,'address: '.$address);



But I am not getting PDF in return. Whats wrong?? In fact, nothings happening..
I want to retreive the pdf file and send it to print

How to&Answers:

To load a PDF via ajax you could try:

  • Use some of the PDF javascript libraries to render PDF directly from
    javascript without plugins, like mozilla pdf.js or jspdf .
    And try to see if those libraries let you set the pdf directly from
    binary data (what you receive in ajax).

  • Another option is receive the pdf data as base64 encoded and the use
    a Data URI to set window.location.href to that data uri,
    although in that case it’s possible the PDF is offered as a dowload
    dialog instead of loading directly in the page, you have to test
    that. Also data uri support is very limited for pdf in IE 8 and
    older, see the wikipedia data uri page for more details.

  • Also see this answer about how it’s not possible to load pdf
    directly from ajax and what other options you have to try to do what
    you want (mainly saving pdf as temporary file on server and use it
    with window.location.href or <iframe> or window.open )


You should open a new page using <a> tag with your PHP page print.php with your variables.

<a href="print.php?data" target="_blank">click me to download the file</a>

In the PHP page, add headers

// Send Headers
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="myPDF.pdf');

// Send Headers: Prevent Caching of File
header('Cache-Control: private');
header('Pragma: private');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

Try to play with header header('Content-type: application/force-download'); to download automatically your file.

You could also display your PDF data like if the file has been saved readfile('original.pdf');