使用html2pdf使用php和mvc模式生成报告

时间:2013-04-01 16:03:08

标签: php model-view-controller pdf-generation fpdf

我已经设置了一个以某种方式使用前端控制器的应用程序。我遇到了一个名为 html2pdf 的库。该库将html转换为pdf。

像这样:

<?php
    $content = "
     <page>
      <h1>Exemple d'utilisation</h1>
      <br>
      Ceci est un <b>exemple d'utilisation</b>
      de <a href='http://html2pdf.fr/'>HTML2PDF</a>.<br>
     </page>";

   require_once(dirname(__FILE__).'/html2pdf/html2pdf.class.php');
   $html2pdf = new HTML2PDF('P','A4','fr');
   $html2pdf->WriteHTML($content);
   $html2pdf->Output('exemple.pdf');
?>

如您所见,libary可以将该html转换为pdf。它甚至可以读取html文件并将其转换为pdf。

好的,这是我的控制器的设置。

class TestController extends Controller {
    private $template;

    public function __construct(View $view = null) {
        parent::__construct($view);
        $this->template = 'test'; // replace this
    }

    public function index() {
        $this->view->data['someinfo'] = 'information about me';
        $this->view->render($this->template);
    }
}

我的想法是,不是将模板渲染出来,而是将$someinfo变量替换为information about me,因为我使用了php的extract函数。

我可以直接替换变量,然后将输出保存为html,以便我可以使用html2pdf将其转换为pdf?

是否已经实施了这个?或者是否有更有效的解决方案,而不是创建和html文件并转换它?

谢谢。

1 个答案:

答案 0 :(得分:0)

在ZendFramework MVC中,您可以在控制器中执行以下操作:

function toPdfAction()  { 
   // I need a different layout 
   $this->getHelper('layout')->setLayout('pdf-layout'); 
   $this->_helper->layout->disableLayout(); 

   // we need to do renderering ourselves.   
   $this->getHelper('viewRenderer')->setNoRender(); 

   /* @var $layout Zend_Layout */ 
   $layout = $this->_helper->layout->getLayoutInstance(); 
   $layout->assign('content', $this->view->render('mycontroller/myaction.tpl')); 

   $output = $layout->render(); 

   // now we still need to ensure that the rendering is not sent to the browser 
   $this->getResponse()->clearBody(); 

   // now do something with $ouput like convert it to PDF and stream it back
} 

但是,答案是针对具体的MVC实现。如果您不使用Zend,那可能不适合您。您使用的是什么MVC框架?