如何将DOMPDF生成的内容保存到文件?

78

我正在使用Dompdf创建PDF文件,但不知道为什么它不能将创建的PDF保存到服务器。

有任何想法吗?

require_once("./pdf/dompdf_config.inc.php");
    $html =
      '<html><body>'.
      '<p>Put your html here, or generate it with your favourite '.
      'templating system.</p>'.
      '</body></html>';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    file_put_contents('Brochure.pdf', $dompdf->output());

dompdf的版本是多少?有PHP错误吗? - BrianS
dompdf 0.5.2,php 5.2.13 - TomTom
2
我没有看到任何阻止您保存的东西,所以我猜测是服务器配置错误。也许PHP无法写入那个目录?如果是这种情况,PHP将报告一个错误。检查您的PHP错误日志或启用错误显示。 - BrianS
3个回答

135
我刚刚使用了dompdf,代码有点不同但是它起作用了。
这是代码:
require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);

$html =
      '<html><body>'.
      '<p>Put your html here, or generate it with your favourite '.
      'templating system.</p>'.
      '</body></html>';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $output = $dompdf->output();
    file_put_contents('Brochure.pdf', $output);

唯一的区别在于包含目录中的所有文件都会被包含。

除此之外,我的建议是指定完整的目录路径来写入文件,而不仅仅是文件名。


2
我测试了你的代码,唯一的问题是你试图写入文件的目录缺少权限。
给需要放置文件的目录赋予“写”权限。在你的情况下,这是当前目录。
在Linux中使用“chmod”。
如果你在Windows系统中,则将“Everyone”添加到该目录的安全选项卡,并启用“写”权限。

-5
<?php
$content='<table width="100%" border="1">';
$content.='<tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>';
for ($index = 0; $index < 10; $index++) { 
$content.='<tr><td>nadim</td><td>nadim.sheikh.07@gmail.com</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>';
}
$content.='</table>';
//$html = file_get_contents('pdf.php');
if(isset($_POST['pdf'])){
    require_once('./dompdf/dompdf_config.inc.php');
    $dompdf = new DOMPDF;                        
    $dompdf->load_html($content);
    $dompdf->render();
    $dompdf->stream("hello.pdf");
}
?>
<html>
    <body>
        <form action="#" method="post">        
            <button name="pdf" type="submit">export</button>
        <table width="100%" border="1">
           <tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>         
            <?php for ($index = 0; $index < 10; $index++) { ?>
            <tr><td>nadim</td><td>nadim.sheikh.07@gmail.com</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>
            <?php } ?>            
        </table>        
        </form>        
    </body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接