【问题标题】:Convert php file to pdf file by using mPDF使用 mPDF 将 php 文件转换为 pdf 文件
【发布时间】:2014-10-19 03:27:03
【问题描述】:

我刚刚开始使用 mPDF。我一开始就卡住了。我正在尝试包含我的动态 php 文件并使用 mPDF 将其转换为 pdf 文件。这是我的方法:这是我将文件转换为pdf的功能

<?php 

include('MPDF57/mpdf.php');
include('template1.php');
$html= "template1.php";
$mpdf=new mPDF(); 
$mpdf->SetDisplayMode('fullpage');
$mpdf->WriteHTML(file_get_contents($html));
$mpdf->Output('result.pdf','F');
exit;

?>

我的 template.php 文件只是一个 html 发票表布局,其中几个内容来自数据库,例如:用户地址、发票表等...我确实想从 template.php 转换 html 布局和内容文件转成pdf

但它不会将文件输出为 pdf 文件。我在这里错过了什么?

【问题讨论】:

  • 是转换.php文件的来源还是.php文件生成的内容?
  • 我的 template.php 文件只是一个 html 发票表格布局,其中有几个内容来自数据库,如:用户地址、发票表格等...我确实想转换 html 布局和内容将 template.php 文件转换为 pdf
  • where several content come from databas as 所以,它有一个应该执行的 php 代码? file_get_contents($html) 按“原样”读取文件,而不在其中运行 .php 代码。在include('template1.php');之前使用'ob_start(),在之后取缓冲区的内容,输出,如果需要,转换成pdf。
  • 你可以添加代码吗?
  • ob_start(); include('template1.php'); $content = ob_get_clean(); ... your code up to .. $mpdf-&gt;WriteHTML($content);

标签: php mpdf


【解决方案1】:

如果您的template1.php 中有php 代码,那么file_get_contents 函数将不会执行它,因为它会将文件的内容作为常规文本读取。您需要在include 之前打开输出缓冲区,获取缓冲区的内容并将其用于生成pdf。像这样的:

<?php 

include 'MPDF57/mpdf.php';
ob_start();  // start output buffering
include 'template1.php';
$content = ob_get_clean(); // get content of the buffer and clean the buffer
$mpdf = new mPDF(); 
$mpdf->SetDisplayMode('fullpage');
$mpdf->WriteHTML($content);
$mpdf->Output('result.pdf'); // output as inline content

【讨论】:

  • ob_get_clean() 似乎失败了,但ob_getContents() 工作,但清除功能失败?
  • @BarclayVision 在ob_get_contents() 之后尝试ob_end_clean()
  • 这就是我在新问题中尝试提出的问题 - 类似的代码但未能返回 PDF。 stackoverflow.com/questions/33292242/…
  • @BarclayVision 检查ob_get_level() 为您提供的内容 - 可能包含添加额外缓冲级别的文件。还要禁用缓冲,检查您将从包含进入浏览器的输出。
  • ob_get_level() 给出:HTML 包含无效的 UTF-8 字符 2mPDF 错误:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 2012-05-05
  • 1970-01-01
  • 2021-04-23
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多