Click here to Skip to main content
15,889,116 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. I have a PDF file made by using tFPDF class. I would like to know how can I manage it to show in a new browser window and make it downloadable to client's PC. As said in the title, PDF file is made in PHP. In order to deal with the problem, do I need to pass the PDF file or its server location to javascript and then show it in a new window OR is it possible to show it and make it downloadable in PHP.

What I have tried:

So far I tried using json_encode() in order to pass the pdf location from PHP to javascript and then showing it in new window. In this case javascript code won't run.

JAVASCRIPT:
JavaScript
var pdfFileLocation = <?php echo json_encode($pdfLocation); ?>;
window.open(pdfFileLocation);


PHP:
PHP
$pdfLocation = $_SERVER['DOCUMENT_ROOT']."/File.pdf";
Posted
Updated 7-May-16 5:00am

1 solution

This is how: create HTML code:
HTML
<a href="createdFile.pdf">This is your PDF document</a>

It sounds like a joke, but I'm serious. The user clicks on this anchor's text and uses the option the browser offers.

There is the thing: PDF is not a part of W3 standards and is quite foreign to Web. Don't be confused by the fact that many browsers actually show PDF files directly. Even though this feature is popular, it is totally optional, often implemented as a 3rd-party plug-in. You should never assume that the user has anything at all to view PDF. This is not a problem at all, because the user always is given an option to save the file and view it later.

Now, as you dynamically generate PDF file, you may want to avoid saving the file in the file system of your server's host. Then the solution is: your URL should be some PHP file "createPDF.php", instead "createdFile.pdf". This PHP script can generate PDF context directly to the output stream of the current HTTP response. Before you output a single byte, you need to generate appropriate content type header. The content type string should be "application/pdf".

Content types are standardized by IANA and can be found here: Media Types[^].

This is how you output an HTTP header via PHP: PHP: header — Manual[^].

Pay attention for the headers "content-type" and "content-disposition" in the code samples. See also: RFC 2183 — Communicating Presentation Information in Internet Me (RFC2183)[^].

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900