【问题标题】:Using html2pdf to generate a report using php and mvc pattern使用 html2pdf 使用 php 和 mvc 模式生成报告
【发布时间】:2013-03-22 17:32:01
【问题描述】:

我设置了一个以某种方式使用前端控制器的应用程序。我遇到了一个名为 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');
?>

如您所见,该库可以将该 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);
    }
}

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

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

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

谢谢。

【问题讨论】:

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


    【解决方案1】:

    在 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 框架?

    【讨论】:

    • 我创建了一个 mini-mvc 框架,是的,我认为 prolly 不适用于我的框架,但我可以看看 zend 是如何做到的。
    • 嗯 .. 将这样的东西放在控制器中将违反 MVC 和受 MVC 启发的设计模式的基本原则。仅仅因为 Zend 这样做,并不意味着它是一个好的实践。
    • @tereško,是的,它肯定会打破“良好做法”。我想知道我该怎么做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 2023-03-08
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多