LLION/ PDF, print & document engineering

PDF MIME type and HTTP headers

LLION Editorial · Updated

MIME type
application/pdf
Defined by
RFC 8118 (2017), which obsoleted RFC 3778; registered with IANA
File extension
.pdf
Charset parameter
none; PDF is a binary format and charset= is meaningless on it
First bytes
%PDF- (hex 25 50 44 46 2D), see file signatures
Seen in the wild
application/x-pdf, application/acrobat, text/pdf, application/octet-stream; none is registered and all should be replaced on the server

The type has been application/pdf since the original 2004 registration, and RFC 8118 re-registered it against ISO 32000-1 and ISO 32000-2 without adding aliases. Every mismatch you meet in practice is a misconfigured server or an old upload-handling library, not an alternative standard.

Content-Type#

The response header is simply:

HTTP
Content-Type: application/pdf

Browsers decide whether to render a PDF inline from this header, so a wrong type is the most common reason a PDF downloads instead of opening. application/octet-stream always downloads. text/plain or text/html shows the raw bytes as garbage. With X-Content-Type-Options: nosniff set, which it should be, the browser will not correct a wrong type by sniffing the %PDF- signature.

Content-Disposition: inline or attachment#

The second header decides what the browser does with a correctly typed PDF (RFC 6266):

HTTP
Content-Disposition: inline; filename="invoice-2026-001.pdf"
Content-Disposition: attachment; filename="invoice-2026-001.pdf"

inline is the default when the header is absent: the browser's PDF viewer displays the file, and filename sets the name offered if the user saves it. attachment forces a download dialog or a direct save. Non-ASCII file names need the filename* form from RFC 8187, percent-encoded UTF-8; send both for compatibility, because a browser that understands filename* prefers it and one that does not falls back:

HTTP
Content-Disposition: attachment; filename="resume.pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9.pdf

Keep filename to ASCII without percent-escapes. Firefox and Chrome decode escapes in the plain parameter and Safari does not, so the result differs by browser. Path separators are replaced by underscores. An <a download="name.pdf"> attribute on the link overrides inline, but a filename in the header overrides the attribute's name.

Why a PDF downloads instead of displaying#

Work through these in order.

  1. Content-Disposition: attachment is set, often by a global rule meant for a downloads directory.
  2. Wrong Content-Type, usually application/octet-stream from a storage service that was never told the type, or from a framework default for unknown extensions.
  3. The browser has no viewer, because the user disabled the built-in PDF viewer or an extension handles PDFs. Nothing on the server fixes this.
  4. A <a download> attribute on the link.
  5. The response is a redirect to a URL with different headers, so the headers you set on the original route are never seen.

The reverse problem, a PDF that should download but opens in a tab, is solved by attachment, not by changing the type to octet-stream. Keep the type honest and let the disposition do the work.

Range requests and large files#

A PDF viewer can start rendering before the whole file has arrived if the file is linearized and the server supports HTTP range requests. Two headers make that possible:

HTTP
Accept-Ranges: bytes
Content-Length: 4827193

With them, Acrobat and PDF.js request the first few kilobytes, then the pages the user is looking at, through Range: bytes=… requests that the server answers with 206 Partial Content. Static file handlers in Apache, nginx, Go's http.ServeFile and ASP.NET Core support ranges automatically; a handler that streams a generated PDF through a buffer usually does not, and the viewer waits for the full download. Compressing PDFs with gzip or Brotli at the HTTP layer defeats ranges and rarely saves more than a few percent, because the streams inside are already Flate-compressed.

Caching and embedding#

Generated documents should carry Cache-Control: private, no-store if they are personal, and an ETag or Last-Modified otherwise, so that revisits hit the cache. Static documents can be cached like any asset.

To show a PDF inside a page, <iframe src="file.pdf">, <embed src="file.pdf" type="application/pdf"> and <object data="file.pdf" type="application/pdf"> all hand the file to the browser's viewer, with <object> allowing fallback content. Mozilla's PDF.js renders the file with JavaScript instead, which gives the same result on every browser at the cost of shipping the library.

Server and framework snippets#

Each snippet sends a stored file inline with a file name. Swap inline for attachment to force a download.

.htaccess or httpd.confApache
AddType application/pdf .pdf
<FilesMatch "\.pdf$">
  Header set Content-Disposition "inline"
</FilesMatch>
# Force downloads in one directory only
<Directory "/var/www/site/downloads">
  Header set Content-Disposition "attachment"
</Directory>
nginx.confnginx
# application/pdf pdf; is already in the default mime.types
location /downloads/ {
  add_header Content-Disposition "attachment";
}
Express 5 (Node.js)JavaScript
import path from 'node:path';

app.get('/invoice.pdf', (req, res) => {
  res.type('application/pdf');
  res.setHeader('Content-Disposition', 'inline; filename="invoice.pdf"');
  res.sendFile(path.join(import.meta.dirname, 'files', 'invoice.pdf'));
});

// For a Buffer produced in memory, as a download:
app.get('/report.pdf', (req, res) => {
  res.attachment('report.pdf');      // sets Content-Disposition and the type from the extension
  res.send(pdfBuffer);
});
Django 5.2Python
from django.http import FileResponse

def invoice(request):
    return FileResponse(
        open("files/invoice.pdf", "rb"),
        as_attachment=False,            # True forces a download
        filename="invoice.pdf",
        content_type="application/pdf",
    )
Flask 3Python
from flask import send_file

@app.get("/invoice.pdf")
def invoice():
    return send_file("files/invoice.pdf", mimetype="application/pdf",
                     as_attachment=False, download_name="invoice.pdf")
PHP 8PHP
<?php
$path = __DIR__ . '/files/invoice.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="invoice.pdf"');
header('Content-Length: ' . filesize($path));
readfile($path);
ASP.NET Core 8 (controller and minimal API)C#
[HttpGet("invoice.pdf")]
public IActionResult Invoice()
{
    var bytes = System.IO.File.ReadAllBytes("files/invoice.pdf");
    return File(bytes, "application/pdf");                   // inline
    // return File(bytes, "application/pdf", "invoice.pdf"); // attachment with a name
}

// Minimal API
app.MapGet("/invoice.pdf", () => Results.File("files/invoice.pdf", "application/pdf"));
Go 1.22 net/httpGo
http.HandleFunc("/invoice.pdf", func(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/pdf")
	w.Header().Set("Content-Disposition", `inline; filename="invoice.pdf"`)
	http.ServeFile(w, r, "files/invoice.pdf") // sets Content-Length and answers Range requests
})

Storage, uploads and data URLs#

Object stores keep the type you set at upload time and serve it back unchanged, so an untyped upload is served as application/octet-stream forever. With the AWS CLI: aws s3 cp invoice.pdf s3://bucket/invoice.pdf --content-type application/pdf --content-disposition 'inline; filename="invoice.pdf"'. The same applies to Cloud Storage and Azure Blob metadata.

In a multipart form upload, the part's own Content-Type is whatever the client chose, which is often the operating system's guess. Validate uploaded PDFs by their first bytes, not by the declared type or the extension; the file signatures reference shows how.

A PDF can be embedded in a URL or an HTML attribute as base64 (RFC 2397). The first characters are always the same, because they encode %PDF-:

Text
data:application/pdf;base64,JVBERi0xLjcK...

Browsers limit the length of data URLs and treat top-level navigation to them as suspicious, so this is for small, embedded documents rather than delivery.

Sources