Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class pdftkMerger {
- private $localPdftk;
- private $tmpDir;
- public function __construct($pdftk = '/usr/bin/pdftk', $tmp = '/tvitemp/tmp') {
- $this->localPdftk = $pdftk;
- $this->tmpDir = $tmp;
- }
- private function getFileData($file) {
- $downloadFile = fopen($file, 'r');
- if ($downloadFile) {
- $buf = "";
- while(!feof($downloadFile)) {
- $buf .= fread($downloadFile, 1024 * 8);
- }
- fclose($downloadFile);
- }
- return $buf;
- }
- private function getReportInfo($report) {
- $command = $this->localPdftk.' '.$report.' dump_data output '.$this->tmpDir.'/report.txt';
- exec($command);
- $info = $this->getFileData($this->tmpDir.'/report.txt');
- unlink($this->tmpDir.'/report.txt');
- return $info;
- }
- private function getPageAmount($pdfInfo) {
- preg_match('/NumberOfPages: ([0-9]{1,})/', $pdfInfo, $matches);
- return $matches[1];
- }
- public function getMergedPdf($original, $attachments) {
- if(count($attachments) > 0) {
- $originalInfo = $this->getReportInfo($original);
- $pageAmount = $this->getPageAmount($originalInfo);
- $pageAmount++;
- $mergedInfo = $originalInfo."\nBookmarkBegin\nBookmarkTitle: Verplichte bijlagen\nBookmarkLevel: 1\nBookmarkPageNumber: ".$pageAmount;
- $mergeCommand = $this->localPdftk.' '.$original;
- foreach($attachments AS $name => $path) {
- $mime_type = mime_content_type($path);
- switch ($mime_type) {
- case 'application/pdf':
- case 'application/octet-stream':
- $mergeCommand .= ' '.$path;
- $mergedInfo .= "\nBookmarkBegin\nBookmarkTitle: ".$name."\nBookmarkLevel: 2\nBookmarkPageNumber: ".$pageAmount;
- $pageAmount = $pageAmount + $this->getPageAmount($this->getReportInfo($path));
- break;
- default:
- continue;
- }
- }
- $mergeCommand .= ' cat output '.$this->tmpDir.'/_taxatierapportMerged.pdf';
- exec($mergeCommand);
- $fh = fopen($this->tmpDir.'/mergedInfo.txt', 'w');
- fwrite($fh,$mergedInfo);
- fclose($fh);
- $updateInfoCommand = $this->localPdftk.' '.$this->tmpDir.'/_taxatierapportMerged.pdf update_info '.$this->tmpDir.'/mergedInfo.txt output '.$this->tmpDir.'/complete.pdf';
- exec($updateInfoCommand);
- $pdf = $this->getFileData($this->tmpDir.'/complete.pdf');
- unlink($this->tmpDir.'/_taxatierapportMerged.pdf');
- unlink($this->tmpDir.'/mergedInfo.txt');
- unlink($this->tmpDir.'/complete.pdf');
- return $pdf;
- }
- }
- }
- $merger = new pdftkMerger();
- $tmpDir = "/tvitemp/tmp";
- $original = "_test.pdf";
- $attachments = array(
- 'opdrachtvoorwaarden' => $tmpDir.'/test.pdf',
- 'CRT' => $tmpDir.'/test.pdf',
- );
- header("Content-type:application/pdf");
- echo $merger->getMergedPdf($tmpDir.'/'.$original, $attachments);
- die();
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement