PHP – Class PDF Print

- This class can be used to alter a PDF document to make it print when opened.
- It can open a given PDF file and regenerate it inserting special  JavaScript code to make it open
  the print dialog when it is opened.
- The altered PDF file may be saved to a given file or displayed as the current script output.

Code Example: Download Example

================================== Start index.php file ==============================
require_once ("class.pdf.php");

//example A: insert javascript and save as new file
$obj = new pdfFile("example.pdf");

//example B: insert javascript and output the file
$obj = new pdfFile("example.pdf");
//sets the header information, automatically inserts print code
//and echos the pdf contents (cfr. __toString method)
echo $obj;

================================== End index.php file ==============================

================================== Start class.pdf.php file ========================
 class pdfFile{
 private $filename;
 private $fcontents;
 private $lastObjectEnd;
 private $newObjectNr;
 private $insertedPrintCode=false;

 private function pdf_getHighestObjNr($pdfContents){
 preg_match_all('[\d+\s0\s(obj)]', $pdfContents, $matches);

 for($i=0; $i<=count($matches[0])-1; $i++){
 $matches[0][$i] = str_replace(" 0 obj", "", $matches[0][$i]);
 return max($matches[0]);

 private function pdf_getLastObjEnd($pdfContents){
 return strripos($pdfContents, "endobj" . chr(13) . "xref" . chr(13) . "0")+strlen("endobj" . chr(13));

 public function __construct($filename)
 $this->filename = $filename;
 $this->fcontents = file_get_contents($filename) or die("Incorrect filename");

 $this->lastObjectEnd =    $this->pdf_getLastObjEnd($this->fcontents);
 $this->newObjectNr =    $this->pdf_getHighestObjNr($this->fcontents)+1;

 public function insertPrintCode(){
 $insertion .= ($this->newObjectNr) . " 0 obj" . chr(13);
 $insertion .= "<</S/JavaScript/JS(this.print\({bUI:true,bSilent:false,bShrinkToFit:true}\);)>>";
 $insertion .= chr(13) . "endobj";
 $this->fcontents = substr_replace($this->fcontents, $insertion . chr(13),$this->lastObjectEnd,0);
 $this->fcontents = str_replace("/Type /Catalog ", "/Type /Catalog " . chr(13) . "/OpenAction " .
                                $this->newObjectNr . " 0 R", $this->fcontents);

 public function saveAs($filename){
 $h=fopen($filename, "w+");
 fwrite($h, $this->fcontents);

 public function getFileContents(){
 return $this->fcontents;

 public function __toString(){
 header("Content-type: application/pdf");
 return $this->getFileContents();
================================== End class.pdf.php file ==========================

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

Leave a Comment

Your email address will not be published. Required fields are marked *