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

PdfHttp HeadersBrowserEmbedEmbedding

Pdf Problem Overview


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?

Pdf Solutions


Solution 1 - Pdf

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).

Solution 2 - Pdf

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.

Solution 3 - Pdf

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.

Solution 4 - Pdf

I had the same issue and most of the above answers should resolve your issue. Unfortunately, even if i was receiving the content-type & content-disposition headers in the response but still my pdf was being downloaded rather than viewed. After brainstorming and trying for many hours.

> The Culprit was firefox, well in a way it was me. Nervous Laughter

By default, when you open a pdf file in firefox, it will provide you with a popup to either save the pdf file or to open it directly and there is also a check box which says do this action automatically from now on and guess who selected it.

Due to this mistake, my pdf was being downloaded rather than viewed, even if had all the required headers in response. This is a simple mistake but cost me a good amount of time.

To resolve this, just go to settings and search for applications and change pdf setting to whatever you need.

Solution 5 - Pdf

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");
    }

Solution 6 - Pdf

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.

Solution 7 - Pdf

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

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

Solution 8 - Pdf

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>

Solution 9 - Pdf

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.

Solution 10 - Pdf

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."\";");
		}

Solution 11 - Pdf

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>';

Solution 12 - Pdf

Either use

<embed src="file.pdf" />

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

Solution 13 - Pdf

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

Solution 14 - Pdf

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'); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionelloalisboaView Question on Stackoverflow
Solution 1 - PdfColinMView Answer on Stackoverflow
Solution 2 - PdfChristophe RoussyView Answer on Stackoverflow
Solution 3 - PdfAkshayView Answer on Stackoverflow
Solution 4 - PdfAshfaq nisarView Answer on Stackoverflow
Solution 5 - PdfLeon van WykView Answer on Stackoverflow
Solution 6 - Pdftrangsinh1952View Answer on Stackoverflow
Solution 7 - PdfAlexanderView Answer on Stackoverflow
Solution 8 - PdfNick ArnieView Answer on Stackoverflow
Solution 9 - PdfMohsinView Answer on Stackoverflow
Solution 10 - PdfChristian Felix KazuyaView Answer on Stackoverflow
Solution 11 - Pdfuser28864View Answer on Stackoverflow
Solution 12 - PdfGabriel Ryan NahmiasView Answer on Stackoverflow
Solution 13 - PdflawlView Answer on Stackoverflow
Solution 14 - PdfKirk StrobeckView Answer on Stackoverflow