简体   繁体   English

如何在Laravel中将包含动态数据的HTML刀片从数据库转换为PDF?

[英]How to convert html blade that contains dynamic data from database to PDF in laravel?

I'm trying to write code that converts html blade to PDF using tcpdf in laravel. 我正在尝试编写在laravel中使用tcpdf将html刀片转换为PDF的代码。

This is the controller code which i use to convert: 这是我用来转换的控制器代码:

public function htmlToPDF()
{  
    $view=view('PdfDemo');
    $html_content =$view->render();
    PDF::SetTitle('Sample PDF');
    PDF::AddPage();
    PDF::writeHTML($html_content, true, false, true, false, '');
    PDF::Output('SamplePDF.pdf');
}

When I put static data on my view(PdfDemo) everything runs successfully, but the problem is when I put dynamic data with some variables in the blade as the following: 当我在视图(PdfDemo)上放置静态数据时,一切都成功运行,但是问题是当我将动态数据和一些变量放入刀片时,如下所示:

                        <table>
                          <?php $i=0?>
                            @if(count($names))
                                @foreach($names as $n)
                                    <tr><td>
                                    <label>Name{{$i}}:</label>{{$n}}</td>
                                    <tr><td><hr></td></tr>
                                    <?php $index = $index+1; ?>
                                @endforeach
                            @endif
                        </table>

Here $names is the result of select statement in other function of controller, then I pass it to the blade like this: $ names是控制器其他功能中的select语句的结果,然后将其传递给刀片,如下所示:

 return view('PdfDemo',compact('names'));

In this case the blade appear exactly as I want, but when I try to convert to PDF it shows error, $name not defined. 在这种情况下,刀片将完全按照我的意愿显示,但是当我尝试转换为PDF时会显示错误,未定义$ name。

Do like this: 这样做:

$view = View::make('PdfDemo',compact('names'));
$contents = (string) $view;
// or
$contents = $view->render();

When you use View::make() it gets the HTML code of blade file as HTML content after adding dynamic variable's values. 当您使用View::make()它会在添加动态变量的值后获取刀片文件的HTML代码作为HTML内容。

You are not passing the data to the view in the htmlToPDF function. 您没有将数据传递到htmlToPDF函数中的视图。

try to change it to: 尝试将其更改为:

public function htmlToPDF($names)
{  
    $view=view('PdfDemo', compact('names');
    $html_content =$view->render();
    PDF::SetTitle('Sample PDF');
    PDF::AddPage();
    PDF::writeHTML($html_content, true, false, true, false, '');
    PDF::Output('SamplePDF.pdf');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM