2

I'd like to generate and open PDF when user clicks on a button. Here is my code so far:

index.php:

</html>
<head>
<script>
$('.cmd_butt').click(function() {
    $.ajax({
    url: 'create_pdf.php',
    data: {id: $(this).attr('order_id'), name: $(this).attr('name')},
    type: 'post'
    });
}
</script>
</head>
<body>
<button class="cmd_butt" order_id="250" name="pdf_but">Download PDF</button>
</body>
</html>

create_pdf.php:

<?php

//header('Content-type: application/pdf')
header("Content-type: application-download");
//header("Content-Length: $size");
header("Content-Disposition: attachment; filename=MyPDF.pdf");
header("Content-Transfer-Encoding: binary");

require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');

// create new PDF document
// some code
// some code

//$pdf->Output('test.pdf', 'I');
//$pdf->Output('test.pdf', 'FD');
$pdf->Output();

?>

How can I open a new window with generated PDF? Or notify user with "save as" dialog to download this PDF? I've tried different Output() combinations but none of them worked.

Alex
  • 4,083
  • 7
  • 54
  • 84

3 Answers3

4

Have you tried this

$pdf->Output('yourfilename.pdf','D');

This will prompt the user to choose where to save the PDF file.

Rohan Kumar
  • 39,838
  • 11
  • 73
  • 103
Webgrity
  • 99
  • 1
  • 9
  • Thank you SO much! I didn't want to have to save to server. I already had a page generating a pdf using TCPDF...but at the end of my script I was using 'I' instead of 'D'. The simple change to 'D' worked! – Kirt Sep 18 '13 at 15:17
  • @Webgrity This throws error `TCPDF ERROR: Unable to create output file: ../invoice_job_6.pdf` – RN Kushwaha Jan 09 '15 at 12:19
  • @RNKushwaha try using an absolute path for the file. – Dan Jun 04 '19 at 14:59
3

Ajax can only fetch textual data, it can't show the PDF directly or in a new window (from response).

You need to either submit form instead of AJAX, or create a file from ajax call and in response, gets a response about creation of file. e.g. created file name, and than open a new window based on that.

Adeel
  • 18,827
  • 4
  • 42
  • 60
  • In that case, how do I dispose of PDF file after user has downloaded it? – Alex Feb 20 '13 at 11:29
  • Just submit form and use the method mentioned by Basant. in this case the file is not created on File system, so no need to worry about dispose. – Adeel Feb 20 '13 at 12:09
0

Change

<button class="cmd_butt" order_id="250" name="pdf_but">Download PDF</button>

to

<a href="create_pdf.php?order_id=250" target="_blank">Download PDF</a>

Remove the java in index.php
Remove the headers in create_pdf.php

Misho
  • 2,783
  • 2
  • 13
  • 9