简体   繁体   English

如何将刀片内容转换为 PDF?

[英]How I can convert a blade content into PDF?

In my laravel project I have the following myview.blade.php content:在我的 Laravel 项目中,我有以下 myview.blade.php 内容:

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
    <title>{{ __('menu.title') }}</title>
</head>
<body>
 {{__('content') }}
</body>

But instead of rendering it into a http response, I want to be able to generate a pdf file out of it.但不是将其呈现为 http 响应,而是希望能够从中生成 pdf 文件。 Do you know How I can do this?你知道我怎么做吗?

You will need to use a HTML to PDF library such as DOMPDF to do the actual conversion of HTML -> PDF您将需要使用 HTML 到 PDF 库(例如 DOMPDF)来进行 HTML -> PDF 的实际转换

https://github.com/dompdf/dompdf https://github.com/dompdf/dompdf

To get HTML from a blade view, you can do:要从刀片视图中获取 HTML,您可以执行以下操作:

$html = view('path/to/view', ['vars' => 'hello'])->render();

I used many solutions, including DOMPDF, but on average the output generated by WKHTMLTOPDF is far better than DOMPDF.我使用了许多解决方案,包括 DOMPDF,但平均而言,WKHTMLTOPDF 生成的输出比 DOMPDF 好得多。

WKHTMLTOPDF follow CSS rules more precisely. WKHTMLTOPDF 更精确地遵循 CSS 规则。

Well, wkhtmltopdf is a command line program that accepts an html file as parameter, so you just have to install it and you are ready to go.嗯,wkhtmltopdf 是一个命令行程序,它接受一个 html 文件作为参数,所以你只需要安装它就可以了。 It has package for Linux and Windows.它有适用于 Linux 和 Windows 的软件包。

To the code到代码

Generate the desired html from your view, like this:从您的视图中生成所需的 html,如下所示:

$html = view('my_view', $arr);

Write the HTML to a temporary file:将 HTML 写入临时文件:

$temp_file = tempnam(sys_get_temp_dir(), 'pdf_');
file_put_contents($temp_file, $html);

Run exec() on wkhtmltopdf:在 wkhtmltopdf 上运行 exec():

$pdf_file = $temp_file . '.pdf';
exec('wkhtmltopdf ' . $temp_file . ' ' . $pdf_file);

Download your $pdf_file .下载您的$pdf_file

Be happy.要开心。

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

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