Your Location is: Home > Php

html : open pdf files in the browser instead of downloading? [duplicate]

From: Tonga View: 1740 nomela 


I have tried this code. but it is asking for is not getting opened.

<a href="pdffileurl" target="_blank" class="nav-link">product</a>

I have also tried this js code. but didn't work."pdffileurl","_blank")

I have tried this php code as well. but didn't work.

$file = 'filename.pdf'; 
$filename = 'filename.pdf'; 
header('Content-type: application/pdf'); 
header('Content-Disposition: inline; filename="' . $filename . '"'); 
header('Content-Transfer-Encoding: binary'); 
header('Accept-Ranges: bytes'); 

inshort i have tried all the possible ways from my side. but every time when i click on link it is redirecting me in new tab but pdf is not getting opened instead it is asking for download.

Best answer

If your link is triggering a download then either:

  1. The server is sending the PDF without the correct Content-Type header (application/pdf) so the browser doesn't know how render it inline.
  2. The server is sending a Content-Disposition header to recommend that the browser download it instead of rendering it inline.
  3. The browser doesn't have any support for rendering PDFs inline.

The first two of these can only be solved by changing the response headers from the server.

The last can only be solved by changing the browser or installing a plugin that supports PDFs.

Re edit: Assuming you are linking to that PHP program (and not just having it exist while still linking to the PDF) then that suggests the problem is number 3.

Another answer

Your code is correct, it's your webserver handling it as you don't expect it to be for this mime type.

For apache you can force an inline viewing and configure it with VirtualHost.

<LocationMatch "\.(?i:pdf)$">
    ForceType application/pdf
    Header set Content-Disposition inline

Have a look at this;