- 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:
================================== Start index.php file ==============================
<?php
require_once ("class.pdf.php");
//example A: insert javascript and save as new file
$obj = new pdfFile("example.pdf");
$obj->insertPrintCode();
$obj->saveAs("example-print.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 ========================
<?php
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(){
if(!$this->insertedPrintCode){
$insertion="";
$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);
$this->insertedPrintCode=true;
}
}
public function saveAs($filename){
@unlink($filename);
$h=fopen($filename, "w+");
fwrite($h, $this->fcontents);
fclose($h);
}
public function getFileContents(){
return $this->fcontents;
}
public function __toString(){
header("Content-type: application/pdf");
$this->insertPrintCode();
return $this->getFileContents();
}
}
?>
================================== End class.pdf.php file ==========================