Created
August 8, 2012 14:11
-
-
Save iamnodev/3295336 to your computer and use it in GitHub Desktop.
Simple Object for HTML to PDF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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