DOMPDF - PHP 页到 PDF

DOMPDF - PHP Page to PDF

我有一个 PHP 页面,它在 Table 中显示一堆 MongoDB 文档信息。 我想要做的是制作一个按钮,将当前 PHP 页面(基本上所有 Table 与 CSS 样式和数据库变量)打印成 PDF。 但是在尝试了很多代码之后,我似乎仍然无法让它工作。

这是我现在的代码

<?php
require 'vendor/autoload.php';
use Dompdf\Dompdf;

>>Here I have my code related to the MongoDB query

ob_start();
?>



<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Registre</title>
  </head>
<body>
<form method="post" action="">
   <input type="submit" name="pdf" id="pdf" value="PRINT">
</form>
<table class="tftable">
    <thead>    
        <tr>
            <th>1</th>
            <th>2</th>
            <th>3</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($r as $document): 
        $bson = MongoDB\BSON\fromPHP($document);
        $json = json_decode(MongoDB\BSON\toJSON($bson));
        ?>
            <tr>
                <td><?php echo $var1 ?></td> 
                <td><?php echo $var2 ?></td>
                <td><?php echo $var3 ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
    <tr>
        <td>
            <form action="" method="POST">
            <label for="var1">var1</label><br>
            <input type="date" id="var1" name="var1">
        </td>
        <td>
        <label for="var2">var2</label><br>
            <input type="text" id="var2" name="var2">
        </td>
        <td>
        <label for="var3">var3</label><br>
            <input type="text" id="var3" name="var3">
        </td>
    </tr>
    <tr>
        <td>
            <input type="submit" value="Add Data"></form>
        </td>
    </tr>
</table>
</body></html>



<?php 
if(isset($_POST["pdf"])) {
    $html = ob_get_contents(); 
    ob_end_flush();
    $dompdf = new DOMPDF();
    $dompdf->loadHtml($html);
    $dompdf->render();
    $dompdf->stream('registre.pdf',array('Attachment'=>1));
}
?>

现在,当我点击打印时,我的 PHP 页面看起来正在快速自行重新加载,但没有其他任何反应,也没有显示 PDF。 如果将 $dompdf 的 PHP 部分放在 HTML 部分之前,我会得到一个空白的 PDF 文件。

PHP v8.0.5

dompdf v1.0.2

谢谢。

“headers 已发送”错误是由对 ob_end_flush 的调用引起的。这告诉服务器将当前缓冲区内容发送到浏览器。当您之后调用 $dompdf->stream() 时,Dompdf 会尝试设置 headers,但它无法做到。您应该改为调用 ob_end_clean() 以确保缓冲区中没有剩余内容。