Ask Anvil

Answers to questions about automating PDFs, e-signatures, Webforms, and other paperwork problems.
PDFs
Categories

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

To force PDF files to open in a browser rather than download, you need to set specific HTTP headers or embed the PDF directly into your webpage. This approach is beneficial for applications where users need to view files without leaving the web environment.

The most reliable way to ensure that a PDF opens in the browser is to set the HTTP header Content-Disposition to inline. This tells the browser to open the PDF directly within the browser window instead of prompting a download. Here’s a practical example for various environments:

1. JavaScript (Express.js): This setup instructs Express to open the file directly in the browser.

app.get('/file', (req, res) => {
    res.setHeader('Content-Disposition', 'inline; filename="file.pdf"');
    res.setHeader('Content-Type', 'application/pdf');
    res.sendFile('/path/to/file.pdf');
});

2. PHP: The PHP example also ensures that the file opens in the browser.

3. Python (Flask): Flask uses the as_attachment=False parameter to open the file in the browser.

4. Django:

Server Configuration for PDF Files

If you can modify server settings, you can ensure PDFs are always opened in the browser by setting the Content-Disposition header.

Apache

Add the following to your .htaccess or Apache configuration file:

<FilesMatch "\.(?i:pdf)$">
    Header set Content-Disposition inline
</FilesMatch>
Nginx

For Nginx, add this configuration to your site’s configuration file:

IIS

Add the following to the web.config file:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Content-Disposition" value="inline" />
        </customHeaders>
    </httpProtocol>
</system.webServer>
Using an <iframe> to Embed PDF

If you control the HTML page where the PDF should open, embedding it in an <iframe> is an effective method:

<iframe src="/path/to/file.pdf" width="100%" height="600px"></iframe>

Summary Table

Here’s a comparison of methods for forcing PDFs to open in the browser:

table_for_forcing_pdf_opens_1.webp

By using the Content-Disposition: inline header or embedding directly with an <iframe>, you ensure that PDF files are opened in the browser rather than downloaded.

Back to All Questions
Anvil Logo

The fastest way to build software for documents

Anvil Document SDK is a comprehensive toolbox for product teams launching document flows where PDF filling, signing, and complex conditional scenarios are necessary.
Explore Anvil
Anvil Webforms