通过AJAX生成PDF预览

I have a form in index.php for creating PDF using TCPDF library. What I'm trying to do is show PDF preview before submitting the form when text fields or selects are loosing focus.

3 PHP files:

  1. the 1st one contains TCPDF functions to create PDF (there is the PDF output setting $pdf->Output('file_name.pdf', I);. "I" indicates here rendering PDF to the browser ("F" is for saving the file).
  2. the 2nd one(create_pdf_preview.php) contains including the 1st file and some other stuff
  3. the 3rd one(create_pdf.php) contains including the 1st file and collecting data to DB

HTML - index.php

<div id="insertingData">
  <form id="form" action="create_pdf.php" method="POST">
     // some input, textarea and select tags for PDF content with 'c' class
  </form>
</div>
<div id="pdfPreview"></div>

AJAX

$('.c').on('blur', function(){
    $.ajax({
        type: 'POST',
        url: 'create_pdf_preview.php',
        data: $('#form').serialize(),
        success: function(data){
            $('#pdfPreview').html(data); // this should be PDF
        },
        dataType: 'html' // PDF
    });
});

So - does anybody know, how to change AJAX to be working? If I would hand more details, please just tell me.

Thank you for any suggestion.

Even if it works, how are you expecting it to .html() the pdf into the page?

What I suggest you do ( being inspired by Preview pdf file created with TCPDF in embed tag after Ajax call ) is add a embed tag which has src of the newly created pdf. By that I mean, refresh the source of the embed with the newly created pdf.

Instead of outputting the pdf like that in create_pdf_preview.php you could use a second file which gets rewritten and when the ajax call ends just change the src of the embed to something like path/to/file.pdf?g=45 and use a random number there which will fool the browser into thinking the src has changed and refresh the file.

Now, as in the question I got my inspiration from, you will have a problem if you use the same file for multiple users, just create temporary files based on timestamp or ip or both and delete them when they finish editing.