Tuesday, July 21, 2009

Error: There was a problem reading this document (109)

Usually browsers armed with Acrobat Reader plugin can open .pdf files directly. Unfortunately sometimes it so happens that a user gets the 109 error and is unable to open the document before they save it locally.

There are a couple of solutions suggested all around the Web, one of them being to give a user choice between saving file locally or open it in Adobe Reader window. One of the ways to do it is changing MIME type of the .pdf file and Content-Disposition header. Instead of default application/pdf we would be serving more generic application/octet-stream. Content-Disposition header has to be set as attachment. Here is an example PHP script which sends any existing .pdf file from the script's directory:
$file = $_GET['file'] . '.pdf';

if (preg_match('/^[a-zA-Z0-9_\-]+\.pdf$/', $file)
&& file_exists($file)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $file);
readfile($file);
} else {
header("HTTP/1.0 404 Not Found");
}
Even though it works, it is not very elegant. We might want to link directly to .pdf documents instead of pdf.php?file=document.pdf and serve the files transparently through the php script.
For Apache users it is quite easy to achieve. An example .htaccess file:
RewriteEngine On
RewriteBase /your.directory.with.documents/pdf
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+)\.pdf$ ./pdf.php?file=$1 [L,NC,QSA]
A few words of explanation:
  • Third line says to redirect to pdf.php script only valid requests for existing files.
  • Fourth line rewrites requests for .pdf files only as this is all we are interested in. The script gets filename without extension, eg. "document.pdf" is passed to the script as "document".
  • More about rewrite_mod for apache you can find in the documentation.

2 comments:

  1. I keep getting an error message while trying to convert document to a PDF.?

    ReplyDelete
  2. I'm getting an error while opening the pdf file. The error is "Invalid plugin detected Adobe reader will quit"?

    ReplyDelete