0

I am creating a page where a user can customize a PDF, after generating the PDF I want to display a preview of the generated PDF and allow the user to download or print it. I have the PHP working correctly for generating the PDF and now I am moving on to using an AJAX call to accept form inputs for the dynamically generated text. On submit I would like the PDF to be displayed in a div so the user can preview the PDF before printing/saving it.

Here's my PHP(generate_pdf.php) for the PDF generation:

<?php

use setasign\Fpdi\Fpdi;

require_once('fpdf.php');
require_once('autoload.php');

// initiate FPDI
$pdf = new Fpdi();
// add a page
$pdf->AddPage();
// set the source file
$pdf->setSourceFile('template.pdf');
// import page 1
$tplIdx = $pdf->importPage(1);
$size = $pdf->getTemplateSize($tplIdx);
$orientation = $size['width'] > $size['height'] ? 'L' : 'P';
$mid_x = $size['width']/2;

$company = $_POST['company'];
$pdf->useTemplate($tplIdx, null, null, $size['width'], $size['height'],FALSE);

// now write some text above the imported page
$pdf->SetFont('Helvetica');
$pdf->SetTextColor(0, 0, 0);
$pdf->SetXY($mid_x - ($pdf->GetStringWidth($company) / 2), 110);
$pdf->Write(0, $company);

$pdf->Output();

and here's my HTML/JavaScript for the AJAX call:

<form method="post">
    <input name="company" type="text" />
    <input type="submit" />
</form>

<div id="pdf"></div>

<script>
    var $form = $('form'),
        form_data;

    $form.submit(function(e) {
        e.preventDefault();
        form_data = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: 'generate_pdf.php',
            data: form_data
        }).done(function(response) {
            $('#pdf').append(response);
        });
    });
</script>

Unfortunately this just generates a bunch of gibberish, I am assuming it has something to do with the content-type header?

Rinzler786
  • 109
  • 1
  • 11
user13286
  • 3,027
  • 9
  • 45
  • 100
  • Look here https://stackoverflow.com/questions/14559060/display-pdf-using-an-ajax-call – Vincent Decaux Jan 03 '19 at 18:45
  • @VincentDecaux I saw that question, but that appears to address displaying an existing PDF file that exists physically on a server, rather than one that is being dynamically generated with PHP. – user13286 Jan 03 '19 at 18:49
  • Adapt the answer to your problem. Store a your pdf on your disk in your php, then return the URL. And use a iFrame to display it. – Vincent Decaux Jan 03 '19 at 18:57

0 Answers0