【问题标题】:save multiple pdf files using dompdf in loop not working在循环中使用 dompdf 保存多个 pdf 文件不起作用
【发布时间】:2015-12-28 11:33:38
【问题描述】:

我正在使用 dompdf。我想将多个 pdf 文件保存到服务器。下面是我试图完成此任务的代码。但是我将所有订单都放在一个 pdf 文件中。这意味着尽管循环多次执行,但只生成一个 pdf 文件。并且数据附加在同一个pdf文件中,并且数据是正确的。

$sel_orders = "SELECT * FROM tbl_orders WHERE `user_id`=$user_id AND `mail`='pending' GROUP BY order_num";
$order_res = mysql_query($sel_orders);
$sum = mysql_num_rows($order_res);

$dir = dirname(__FILE__);
require_once($dir.'/dompdf/dompdf_config.inc.php');
if($sum > 0)
{
    while($row1 = mysql_fetch_array($order_res))
    {
        $order_num = $row1['order_num']; // test-123
        $post = new stdClass;
        ob_start();
        include($dir.'/pdf.php');
        $pdf_html = ob_get_contents();
        ob_end_clean();
        $dompdf = new DOMPDF(); // Create new instance of dompdf
        $dompdf->load_html($pdf_html); // Load the html
        $dompdf->render(); // Parse the html, convert to PDF
        $pdf_content = $dompdf->output(); // Put contents of pdf into variable for later
        error_reporting(E_ERROR | E_PARSE);     
        $file_to_save = '"http://www.exampe.com/test/orders/$order_num.pdf"';
        file_put_contents($file_to_save, $dompdf->output());        

    }
}

在 pdf.php 文件中,我创建了以 pdf 格式打印的 html 代码。每次控件进入循环时,我都想创建一个单独的 pdf。我尝试了以下链接中的解决方案,但它对我不起作用。有人请指出我做错了什么?如果需要任何进一步的信息,请告诉我。谢谢!

I want to create multiple pdfs in a loop using dompdf?

【问题讨论】:

  • 你能打开所有订单的PDF吗?你确定循环不止一次运行吗?因为如果循环运行不止一次,您应该只获得最后一个 PDF 渲染。
  • 另外,在您的示例代码中,$file_to_save 有单引号,然后是双引号,这意味着文件名不会按您的预期生成。
  • @BrianS 亲爱的你是对的,循环没有多次运行。实际上 pdf.php 中的结果集变量与我的实际代码文件中的结果集变量冲突。此外,我从我的 swift 项目中调用这些文件,因此我很难进行测试。现在已经解决了,非常感谢您提供的提示!

标签: php dompdf


【解决方案1】:

我非常怀疑网站是否会让您使用 URL 将文件保存到其中,无论哪种方式都更容易使用相对路径和文件名,即使这是您运行代码的网站。

首先为输出使用真实有效的文件名。此外,您将文档保存到 $pdf_content,然后不要使用该变量。

$pdf_content = $dompdf->output(); 

// make this a valid directory and filename for your site
// check that the web server account has correct privilages to write to it
$file_to_save = "/test/orders/$order_num.pdf";

file_put_contents($file_to_save, $pdf_content);

【讨论】:

  • 亲爱的,我使用了相对路径并进行了测试,它不起作用,因此我使用了 URL 路径。如果存在写权限问题,那么我希望甚至不应该创建一个文件。无论如何,问题似乎出在 pdf.php 文件上。让我修改 pdf.php 文件并进行一些测试,如果问题仍然存在,我会再次回来。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-19
相关资源
最近更新 更多