如何为wkhtmltopdf获取phalcon视图渲染?

时间:2018-04-03 09:14:16

标签: php pdf view wkhtmltopdf phalcon

我在我的项目中使用Phalcon Framework。我已生成报告页面,我想将其转换为pdf并下载。经过大量的谷歌搜索,我得到wkhtmltopdf,但它只将html文件转换为pdf。我有phtml文件。 Phalcon可以将视图渲染为html字符串或我可以转换的任何其他方式吗?

这是我的代码:

$pdf = new mikehaertl\wkhtmlto\Pdf(APP_PATH . '\\views\\views\\sales\\salesreports.phtml');
if (!$pdf->send()) {
   throw new Exception('Could not create PDF: ' . $pdf->getError());
}

2 个答案:

答案 0 :(得分:2)

Phalcon将模板渲染为变量为html string:

$view = new \Phalcon\Mvc\View\Simple();
$view->setViewsDir(APP_PATH . '\app\views\views\sales\');
$optionalParams = [
    'var1' => 123,
    'var2' => 345,
];
// DO NOT put .phtml extension in the template name
$html = $view->render('salesreports', $optionalParams); 

我不熟悉wkhtmlto\Pdf库,但从文档判断应该看起来像这样:

use mikehaertl\wkhtmlto\Pdf;

$pdf = new Pdf;
$pdf->addPage($html);
$pdf->send();

答案 1 :(得分:1)

我认为Mpdf是一个不错的选择。生成发票要容易得多。我在我的一个项目中使用了它。在phalcon项目中安装它非常容易。

步骤1:通过cd ..命令转到项目文件夹。

我希望您已经在项目中安装了composer。

第2步:运行此命令“ composer require mpdf / mpdf”,并等待安装完成。

第3步:转到供应商饲料。您将看到已添加“ mpdf”。忽略其他文件夹。

步骤4:转到您的控制器。复制以下行。因为您需要在运行时将外部模块加载到自动加载器中。我希望您的供应商文件夹位于根目录中。

第5步:复制require_once DIR 。 '../../../vendor/autoload.php'; 全部设置。

第6步:转到您的函数,例如公共函数pdfgenerateAction(){}

Step7:

public function pdfgenerateAction()
{
    $email = $this->request->getPost("email");

    $mpdf = new \Mpdf\Mpdf();



    $mpdf->WriteHTML("<hr>");
     //Dont bother about this query.You can use Model as well.Just pass the array value to you foreach loop.
     $sheet = $this->modelsManager->createBuilder()
          ->columns("comment.comment, comment.username, comment.email, comment.postedat,item.name,item.photo,item.view,item.categoryid,item.id")
          ->From('comment')
          ->innerjoin('item', 'comment.productid = item.id')
          ->where("comment.email = '$email' ")
          ->getQuery()
          ->execute();        

    $table = "<table>
    <tr>
    <td >Given Name</td>
    <td >Email</td>
    <td >Bird Name</td>
    <td >Posted Time</td>
    <td >Your comment</td>
    <td >Total view by all </td>
    </tr>";
    foreach ($sheet as $row) {
        $table.= "<tr>
        <td >$row->username</td>
        <td >$row->email</td>
        <td >$row->name</td>
        <td >$row->postedat</td>
        <td >$row->comment</td>
        <td >$row->view</td>
        </tr>";
    }
    $table.= '</table>';

    $mpdf->WriteHTML($table);
    $mpdf->WriteHTML("<hr>");
    $mpdf->WriteHTML("<div style='display:block;position:fixed;bottom:0px;height:30px;width:100%' align='center'><strong>Your Footer of PDF</strong></div>");

    //$filename = $info->id;
    $filename = "Put your file name";
    //Crete folder inside your public folder
    $mpdf->Output("Foldername/$filename.pdf", 'F');




   $this->view->pick('pdf/response');
   // $this->flashSession->success("success :: PDF generated");
   // $this->response->redirect('user-home');



}