我有一个使用DOMPDF生成.pdf的函数,无论我为$ html参数设置了什么。
function generate_pdf($html){
//DOMPDF stuff
}
这样可行,但我遇到的问题是,当我从已经有HTML内容的页面调用此函数时,它会失败。
...失败
<?php
require_once '../header.php'; //This has HTML content in it.
$html = '<h1>stuff</h1>';
generate_pdf($html);
?>
这也失败了......
<?php
echo 'stuff';
$html = '<h1>stuff</h1>';
generate_pdf($html);
?>
作品...
<?php
$html = '<h1>stuff</h1>';
generate_pdf($html);
?>
有什么方法吗?
function generate_pdf($html)
function generate_pdf($html){
//Get the necessary dompdf files
include_once DOMPDF_PATH . '/autoload.inc.php';
// instantiate and use the dompdf class
$dompdf = new \Dompdf\Dompdf();
$dompdf->loadHtml($html);
// Render the HTML as PDF
$dompdf->render();
//Output the PDF
$dompdf->stream();
}
请注意,此函数所在的文件具有命名空间,因此$dompdf = new \Dompdf\Dompdf();
可能显示错误,但该行正常工作。
答案 0 :(得分:1)
在将完整代码添加到问题后改变了答案:
我在一个包含的文件中有完整的 HTML内容,在它之前或之后没有额外的HTML(也没有php回显)。
之前我犯了一个错误 - 我混淆了包含dompdf自动加载和内容 - 但是请看下面它在我的情况下是如何工作的。这是一个php文件的内容,没有功能:
<?php
require_once '../../dompdf/autoload.inc.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$dompdf->set_option('isPhpEnabled', true);
ob_start();
//Here I am getting a few variables (from the URL via GET) which I use in the included php file
include_once "your_content_in_one_file.php";
$html = ob_get_contents();
ob_end_clean();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream($pdf_name);
?>
答案 1 :(得分:0)
最终与ob_start();
已在系统中的其他位置被调用的事实有关。使用...
if (ob_get_level()){
ob_end_clean();
}
解决了我的问题。希望它可以帮助别人。