如何将包含动态数据的html刀片从laravel转换为PDF?

如何将包含动态数据的html刀片从laravel转换为PDF?

问题描述:

I'm trying to write code that converts html blade to PDF using tcpdf in laravel.

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:

                        <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:

 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.

我正在尝试编写使用lacvel中的tcpdf将html刀片转换为PDF的代码。 p>

这是我用来转换的控制器代码: p>

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

当我 把静态数据放在我的视图上(PdfDemo)一切都运行成功,但问题是当我在刀片中放入带有一些变量的动态数据时,如下所示: p>

 &lt; table&gt;  
&lt;?php $ i = 0?&gt; 
 @if(count($ names))
 @foreach($ names as $ n)
&lt; tr&gt;&lt; td&gt; 
&lt; label&gt  ;姓名{{$ i}}:&lt; / label&gt; {{$ n}}&lt; / td&gt; 
&lt; tr&gt;&lt; td&gt;&lt; hr&gt;&lt; / td&gt;&lt; / tr&gt; \  ñ  &lt;?php $ index = $ index + 1;  ?&gt; 
 @endforeach 
 @endif 
&lt; / table&gt; 
  code>  pre> 
 
 

这里$ names是控制器其他功能中select语句的结果, 然后我将它传递给刀片: p>

 返回视图('PdfDemo',compact('names')); 
  code>  pre> \  n 
 

在这种情况下,刀片看起来完全符合我的要求,但当我尝试转换为PDF时,它显示错误,$ name未定义。 p> div>

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.

You are not passing the data to the view in the htmlToPDF function.

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');
}