<?php
/**
* Copyright (C) 2011 Kai Dorschner
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @author Kai Dorschner <the-hide@address.com>
* @copyright Copyright 2011, Kai Dorschner
* @license http://www.gnu.org/licenses/gpl.html GPLv3
* @package mocovi
*/
class_exists('Renderer') or require $GLOBALS['library'].'Renderer.php';
class pdfRenderer extends Renderer
{
protected $fo, $pdf, $tmp;
public function render($string)
{
$this->createFOFile($string);
$this->createPDFFile();
$this->renderPDF();
$pdfContents = file_get_contents($this->pdf);
$this->cleanup();
$GLOBALS['header']->contentType('application/pdf');
$GLOBALS['header']->contentDisposition(basename($GLOBALS['path']), 'inline');
//$GLOBALS['header']->contentLength(strlen($pdfContents)); // @todo Can't use this line, it produces not the correct contentLength!
return $pdfContents;
}
protected function createFOFile($content)
{
$this->fo = $this->createTempFile('.mocovi.fo', $content);
if(!is_file($this->fo) || !is_readable($this->fo))
$this->error('File '.$this->fo.' not found or not readable.');
}
protected function createPDFFile()
{
$this->pdf = $this->tmp.'.mocovi.pdf';
}
protected function createTempName()
{
if(strlen($this->tmp) <= 0)
$this->tmp = tempnam(sys_get_temp_dir(), '');
}
protected function createTempFile($suffix, $content = '')
{
$this->createTempName();
$path = $this->tmp.$suffix;
//file_put_contents($path, $content); // short variant
if($handle = fopen($path, 'w'))
{
fwrite($handle, $content);
fclose($handle);
}
else
$this->error($path. ' cannot be created.');
chmod($path, 0777);
return $path;
}
protected function renderPDF()
{
exec('fop -fo '.$this->fo.' -pdf '.$this->pdf, $exec);
if(!is_file($this->pdf))
$this->error('An error occured in Apache FOP while rendering the PDF.');
}
protected function error($string)
{
$this->cleanup();
throw new MvcException($string);
}
protected function cleanup()
{
if(is_file($this->fo))
unlink($this->fo);
if(is_file($this->pdf))
unlink($this->pdf);
}
}