[pdf] How do I force files to open in the browser instead of downloading (PDF)?

Is there a way to force PDF files to open in the browser when the option "Display PDF in browser" is unchecked?

I tried using the embed tag and an iframe, but it only works when that option is checked.

What can I do?

This question is related to pdf http-headers browser embed embedding

The answer is


Oops, there were typing errors in my previous post.

    header("Content-Type: application/force-download");
    header("Content-type: application/pdf");
    header("Content-Disposition: inline; filename=\"".$name."\";");

If you don't want the browser to prompt the user then use "inline" for the third string instead of "attachment". Inline works very well. The PDF display immediately without asking the user to click on Open. I've used "attachment" and this will prompt the user for Open, Save. I've tried to change the browser setting nut it doesn't prevent the prompt.


Open downloads.php from rootfile.

Then go to line 186 and change it to the following:

        if(preg_match("/\.jpg|\.gif|\.png|\.jpeg/i", $name)){
            $mime = getimagesize($download_location);
            if(!empty($mime)) {
                header("Content-Type: {$mime['mime']}");
            }
        }
        elseif(preg_match("/\.pdf/i", $name)){
            header("Content-Type: application/force-download");
            header("Content-type: application/pdf");
            header("Content-Disposition: inline; filename=\"".$name."\";");
        }

        else{
            header("Content-Type: application/force-download");
            header("Content-type: application/octet-stream");
            header("Content-Disposition: attachment; filename=\"".$name."\";");
        }

If you are using HTML5 (and I guess nowadays everyone uses that), there is an attribute called download.

For example,

<a href="somepathto.pdf" download="filename">

Here filename is optional, but if provided, it will take this name for the downloaded file.


Here is another method of forcing a file to view in the browser in PHP:

$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$url = 'uploads/'.$file_name;
        echo '<html>'
                .header('Content-Type: application/'.$extension).'<br>'
                .header('Content-Disposition: inline; filename="'.$file_name.'"').'<br>'
                .'<body>'
                .'<object   style="overflow: hidden; height: 100%;
             width: 100%; position: absolute;" height="100%" width="100%" data="'.$url.'" type="application/'.$extension.'">
                    <embed src="'.$url.'" type="application/'.$extension.'" />
             </object>'
            .'</body>'
            . '</html>';

To indicate to the browser that the file should be viewed in the browser, the HTTP response should include these headers:

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

To have the file downloaded rather than viewed:

Content-Type: application/pdf
Content-Disposition: attachment; filename="filename.pdf"

The quotes around the filename are required if the filename contains special characters such as filename[1].pdf which may otherwise break the browser's ability to handle the response.

How you set the HTTP response headers will depend on your HTTP server (or, if you are generating the PDF response from server-side code: your server-side programming language).


The correct type is application/pdf for PDF, not application/force-download. This looks like a hack for some legacy browsers. Always use the correct mimetype if you can.

If you have control over the server code:

  • Forced download/prompt: use header("Content-Disposition", "attachment; filename=myfilename.myextension");
  • Browser tries to open it: use header("Content-Disposition", "inline; filename=myfilename.myextension");

No control over the server code:

NOTE: I prefer setting the filename on the server side as you may have more information and can use common code.


If you link to a .PDF it will open in the browser.
If the box is unchecked it should link to a .zip to force the download.

If a .zip is not an option, then use headers in PHP to force the download

header('Content-Type: application/force-download'); 
header('Content-Description: File Transfer'); 

This is for ASP.NET MVC

In your cshtml page:

<section>
    <h4><a href="@Url.Action("Download", "Document", new { id = @Model.GUID })"><i class="fa fa-download"></i> @Model.Name</a></h4>
    <object data="@Url.Action("View", "Document", new { id = @Model.GUID })" type="application/pdf" width="100%" height="800" class="col-md-12">
        <h2>Your browser does not support viewing PDFs, click on the link above to download the document.</h2>
    </object>
</section>

In your controller:

public ActionResult Download(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        return File(model.FilePath, "application/pdf", model.FileName);
    }

public FileStreamResult View(Guid id)
    {
        if (id == Guid.Empty)
            return null;

        var model = GetModel(id);

        FileStream fs = new FileStream(model.FilePath, FileMode.Open, FileAccess.Read);

        return File(fs, "application/pdf");
    }

If you have Apache add this to the .htaccess file:

<FilesMatch "\.(?i:pdf)$">
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</FilesMatch>

While the following works well on firefox, it DOES NOT work on chrome and mobile browsers.

Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"

To fix the chrome & mobile browsers error, do the following:

  • Store your files on a directory in your project
  • Use the google PDF Viewer

Google PDF Viewer can be used as so:

<iframe src="http://docs.google.com/gview?url=http://example.com/path/to/my/directory/pdffile.pdf&embedded=true" frameborder="0"></iframe>

Either use

<embed src="file.pdf" />

if embedding is an option or my new plugin, PIFF: https://github.com/terrasoftlabs/piff


Just open Adobe Reader, menu ? Edit ? Preferences ? Internet, then change to browser mode or for detailed instructions on different browsers try Display PDF in browser | Acrobat, Acrobat Reader.


You can do this in the following way:

<a href="path to PDF file">Open PDF</a>

If the PDF file is inside some folder and that folder doesn't have permission to access files in that folder directly then you have to bypass some file access restrictions using .htaccess file setting by this way:

<FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF|pdf|PDF)$" >
    Order Allow,Deny
    Allow from all
</FilesMatch>

But now allow just certain necessary files.

I have used this code and it worked perfectly.


Examples related to pdf

ImageMagick security policy 'PDF' blocking conversion How to extract table as text from the PDF using Python? Extract a page from a pdf as a jpeg How can I read pdf in python? Generating a PDF file from React Components Extract Data from PDF and Add to Worksheet How to extract text from a PDF file? How to download PDF automatically using js? Download pdf file using jquery ajax Generate PDF from HTML using pdfMake in Angularjs

Examples related to http-headers

Set cookies for cross origin requests Adding a HTTP header to the Angular HttpClient doesn't send the header, why? Passing headers with axios POST request What is HTTP "Host" header? CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response Using Axios GET with Authorization Header in React-Native App Axios get access to response header fields Custom header to HttpClient request Send multipart/form-data files with angular using $http Best HTTP Authorization header type for JWT

Examples related to browser

How to force reloading a page when using browser back button? How do we download a blob url video How to prevent a browser from storing passwords How to Identify Microsoft Edge browser via CSS? Edit and replay XHR chrome/firefox etc? Communication between tabs or windows How do I render a Word document (.doc, .docx) in the browser using JavaScript? "Proxy server connection failed" in google chrome Chrome - ERR_CACHE_MISS How to check View Source in Mobile Browsers (Both Android && Feature Phone)

Examples related to embed

How to embed new Youtube's live video permanent URL? Properly embedding Youtube video into bootstrap 3.0 page How to embed a Google Drive folder in a website How to hide the bar at the top of "youtube" even when mouse hovers over it? How to embed PDF file with responsive width Shrink a YouTube video to responsive width How can I embed a YouTube video on GitHub wiki pages? Embedding a media player in a website using HTML How to embed a YouTube channel into a webpage Embed an External Page Without an Iframe?

Examples related to embedding

How do I force files to open in the browser instead of downloading (PDF)? How do I embed a mp4 movie into my html? Preloading @font-face fonts?