无法打开使用dompdf生成的pdf文件

sar*_*m99 2 php pdf-generation smarty dompdf

我正在尝试使用dompdf从smarty模板生成pdf文件:代码如下: -

require_once('dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF();
$dompdf->load_html($smarty->fetch(CURRENT_TEMPLATE.'/module/shopping_cart.html'));
$dompdf->render();
$dompdf->stream("sample.pdf");
Run Code Online (Sandbox Code Playgroud)

生成pdf文件,但是当我尝试打开pdf文件时,显示如下错误消息"Acrobat无法打开'sample.pdf',因为它不支持文件类型或因为文件已损坏"HTML页面是当我尝试时正确地浸渍

echo $smarty->fetch(CURRENT_TEMPLATE.'/module/shopping_cart.html')
Run Code Online (Sandbox Code Playgroud)

所以请帮我解决这个错误...提前谢谢

Ant*_*nAL 11

ob_end_clean();在致电前使用$dompdf->stream();.

  • 应该选择作为答案。 (2认同)
  • 像你这样的人才是堆栈溢出的真正英雄。 (2认同)

Rip*_*aha 5

是的,这是dompdf的问题.但我能够克服这个问题.我创建了一个pdf创建函数.检查以下功能: -

function pdf_create($html, $filename='', $stream=TRUE) 
{
    require_once("dompdf/dompdf_config.inc.php");
    $savein = 'uploads/policy_doc/';
    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    $canvas = $dompdf->get_canvas();
    $font = Font_Metrics::get_font("arial", "normal","12px");

    // the same call as in my previous example
    $canvas->page_text(540, 773, "Page {PAGE_NUM} of {PAGE_COUNT}",
                   $font, 6, array(0,0,0));

    $pdf = $dompdf->output();      // gets the PDF as a string

    file_put_contents($savein.str_replace("/","-",$filename), $pdf);    // save the pdf file on server
    unset($html);
    unset($dompdf); 

}
Run Code Online (Sandbox Code Playgroud)

注意: - 您需要将生成的pdf作为字符串,然后将其保存为pdf文件.

编辑: - 您可以从上面的功能删除以下部分: -

    $canvas = $dompdf->get_canvas();
    $font = Font_Metrics::get_font("arial", "normal","12px");

    // the same call as in my previous example
    $canvas->page_text(540, 773, "Page {PAGE_NUM} of {PAGE_COUNT}",
                   $font, 6, array(0,0,0));
Run Code Online (Sandbox Code Playgroud)

以上代码用于处理多个页面标题.


小智 5

我也遇到了同样的错误,但是当我使用它ob_end_clean()之前$dompdf->stream(),对我却没有帮助。

下面是我的代码。

$dompdf = new DOMPDF();
$dompdf->load_html($html); 
$dompdf->render();    
$pdf = $dompdf->output();
$invnoabc = 'Bokkinglist.pdf';
ob_end_clean();
$dompdf->stream($invnoabc);
exit;
Run Code Online (Sandbox Code Playgroud)