Creating an add-on called Open PDF

AndyB

Well-known member
Description:

When a PDF file is attached to a post, clicking the attachment link will open a dialog box asking where to save the file. This Add-on changes this behavior so the PDF is opened in the browser.

Requirements:

This add-on only works on Xenforo v1.2 and above.
 
Create the add-on directories and files:

library
--Andy
----OpenPDF
------Lisener.php
------ViewPublic
--------Attachment
----------View.php
 
The Listener.php file:

Create the /library/Andy/OpenPDF/Listener.php file.

PHP:
<?php

class Andy_OpenPDF_Listener
{
   public static function View($class, array &$extend)
   {
     $extend[] = 'Andy_OpenPDF_ViewPublic_Attachment_View';
   }
}

?>
 
The View.php file:

Create the /library/Andy/OpenPDF/ViewPublic/Attachment/View.php file.

PHP:
<?php

class Andy_OpenPDF_ViewPublic_Attachment_View extends XFCP_Andy_OpenPDF_ViewPublic_Attachment_View
{
   //######################################## 
   // the original renderRaw() function is located in library/Xenforo/ViewPublic/Attachment/View.php
   // this renderRaw() will run instead of the original unless we the return parent::renderRaw()
   //########################################

   public function renderRaw()
   { 
     $attachment = $this->_params['attachment'];
     $extension = XenForo_Helper_File::getFileExtension($attachment['filename']);
 
     if ($extension === 'pdf')
     {
       $this->_response->setHeader('Content-type', 'application/pdf', true);
       $this->setDownloadFileName($attachment['filename'], true);
   
       $this->_response->setHeader('ETag', $attachment['attach_date'], true);
       $this->_response->setHeader('Content-Length', $attachment['file_size'], true);
       $this->_response->setHeader('X-Content-Type-Options', 'nosniff');     
   
       return new XenForo_FileOutput($this->_params['attachmentFile']);
     } else {
       // run the original renderRaw() function
       return parent::renderRaw();
     }
   }
}
?>
 
Have you considered using a more advanced PDF viewer? I find that browsers like Firefox display PDF's really bad.
Plus nowadays there are various very nice document viewers (jQuery, flash or HTM5) with flipbook effect, full screen view and other options. FlexPaper is a free solution.
 
Last edited:
Hi Alfa1,

I agree, the PDF reader that now ships with Firefox is terrible. Thankfully Mac's come with Preview and it works very well to read PDF files. I have set the preference in Firefox to use Preview.
 
Top Bottom