2

I am using ajax to post to a function that creates a PDF document through TCPDF.

Normally, I would just do a normal post to the function, and that would output the PDF, allowing the user to download teh pdf file. My understanding, however, is that this doesnt work with ajax, and that I instead need to save the pdf file on the server, and then return the url of the file to the ajax call.

Once I have the url, then I can do something like

window.location.assign(url/to/my.pdf);

Ok, so this all works fine, but its not great. Firstly, the pdf doesnt open in a new window (i.e. it currently opens in the same window), and secondly, I'd prefer to force the user to download the file rather than it opening in the browser.

Are there any other alternatives?

Charles Boyung
  • 2,464
  • 1
  • 21
  • 31
JonoB
  • 5,801
  • 17
  • 55
  • 77

2 Answers2

1

If you're using Apache for your web server, then you can add the following to an .htaccess file in the folder where your PDF files are generated to force a download.

<Files *.pdf>
  ForceType application/pdf
  Header set Content-Disposition attachment
</Files>
Michael Mior
  • 28,107
  • 9
  • 89
  • 113
  • This looked promising, but nothing happens unfortunately. I am running a xampp stack on Windows7, and ensured that mod_headers is running. – JonoB Jul 07 '11 at 15:33
  • Here's a few suggestions. First, confirm that `.htaccess` works in this directory (the quickest way is to put garbage in the file and see if you get an error message). If it is working, try visiting the URL manually to see if it triggers a download, if not, try fetching the PDF with `cURL` or some other tool which will allow you to view the response headers and ensure the correct headers are being added. – Michael Mior Jul 07 '11 at 16:56
  • I've decided to use use a 'normal' post instead of ajax. Simplifies things greatly. – JonoB Jul 13 '11 at 21:38
0

You could pass the generated PDF through PHP and set additional headers to force browser to download the document. See php force download extension.

I guess you can make these headers to be set by Apache automatically as well (e.g. for PDFs in particular folder).

Community
  • 1
  • 1
Gedrox
  • 3,592
  • 1
  • 21
  • 29