Skip to content

Instantly share code, notes, and snippets.

@iamnodev
Created August 8, 2012 14:11
Show Gist options
  • Save iamnodev/3295336 to your computer and use it in GitHub Desktop.
Save iamnodev/3295336 to your computer and use it in GitHub Desktop.
Simple Object for HTML to PDF
<?php
// binary source: http://code.google.com/p/wkhtmltopdf/
class HtmlToPdf {
// generator setup
private $converter = 'wkhtmltopdf';
private $command;
// files
public $html;
public $destinationPath;
public $output;
// parameters
public $parameters = array();
public function render() {
$this->destinationPath = pathinfo($this->output, PATHINFO_DIRNAME);
if (!is_dir($this->destinationPath)) {
if (!mkdir($this->destinationPath, 0755)) {
echo 'could not create destination folder';
return false;
}
}
$this->buildCommand();
exec($this->command . ' 2>&1', $debug, $state);
return ($state == 0);
}
private function buildCommand() {
$this->command = $this->converter;
foreach ($this->parameters as $key => $value) {
$this->command .= ' ' . $key . ' ' . $value;
}
$this->command .= ' ' . $this->html . ' ' . $this->output;
}
public function filetodata() {
$handle = fopen($this->output, "r");
;
return fread($handle, filesize($this->output));
}
public function direct($data, $contentDisposition = 'inline', $filename = null) {
if (!isset($filename))
$filename = uniqid();
$this->getResponse()->setHeader('Content-Type', 'application/force-download; name="' . $filename . '"');
switch ($contentDisposition) {
case 'inline':
$this->getResponse()->setHeader('Content-Disposition', 'inline; filename="' . $filename . '"');
break;
case 'attachment':
$this->getResponse()->setHeader('Content-Disposition', "attachment; filename=\"$filename.pdf\"");
break;
default:
throw new Exception("Unknown Content-Disposition ($contentDisposition)");
}
$this->getResponse()->setHeader('Content-Length', strlen($data))
->setHeader('Content-Transfer-Encoding', 'binary')
->setHeader('Expires', 0)
->setHeader('Cache-Control', 'private, max-age=0, must-revalidate')
->setHeader('Pragma', 'public')
->setBody($data);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment