Selectively forcing PDF downloads for Firefox

The built-in PDF.js viewer in Firefox is nice, but it still has quite a few bugs. Most of the rendering issues are caused by it not supporting certain PDF features yet.

Sometimes one needs to make a PDF with fancy features (e.g. color gradients) available for online viewing. In Firefox, a click on the link to the PDF will open it in PDF.js, which will warn you if it has features it can’t quite deal with. PDF.js will still try to render it. That can lead to visual artefacts and/or be very slow, neither of which are desirable and can be confusing for users.

There is a way to disable PDF.js server-side, and force Firefox to open a download popup box when user clicks on a PDF:

AddType application/octet-stream .pdf

Unfortunately, that makes Chrome (on Windows only, for some reason) really unhappy: it will open a blank new tab and not download the PDF file.

So, here’s how you tell Apache 2.2 to only change the Content-type header for PDF files when the User Agent says ‘Firefox’:

  <IfModule mod_setenvif.c>
    BrowserMatchNoCase firefox pdf=stream
  </IfModule>

  <IfModule mod_rewrite.c>
    RewriteCond %{ENV:pdf} stream
    RewriteRule .pdf$ - [T=application/octet-stream]
  </IfModule>

The BrowserMatchNoCase sets an environment variable called ‘pdf’ to the value ‘stream’ (which is an arbitrary choice). That environment variable is checked by the RewriteCond line; if it matches ‘stream’, the RewriteRule on the next line changes the Content-type header.

This can be done in a less convoluted way on Apache 2.4 with the <If> directive.

This entry was posted in Sysadmin. Bookmark the permalink.
Add Comment Register

Leave a Reply