无法重新声明DOMPDF_autoload()

时间:2016-05-05 06:47:28

标签: php dompdf

我知道之前已经问过这个问题,但我还没弄清楚应该如何解决这个问题。例如,此DOMPDF, I cannot create two pdf at time处理同一主题。我试图按照解决方案,但到目前为止还不太好。我有一个循环,我想创建两个pdf文件(两张发票)。案例1仅使用1个循环,在另一个循环中它挂起(不能重新声明DOMPDF_autoload()(先前在第24行的/vendor/dompdf/include/autoload.inc.php中声明)。案例2和3,我有试图从上面的stackoverflow quastion应用,根本不工作(一些运行时错误,语法错误,我无法弄清楚)。

这是我的代码:

$invoices = 2;
$invoice_names = array();
for ($i=1; $i<=$invoices; $i++)
{
$invoice_file_name = 'invoice' .$i. '.pdf';
$invoice_names[] = $invoice_file_name;

require '../vendor/dompdf/include/autoload.inc.php';

// disable DOMPDF's internal autoloader if you are using Composer
define('DOMPDF_ENABLE_AUTOLOAD', false);

// include DOMPDF's default configuration
require_once '../vendor/dompdf/dompdf_config.inc.php';

$htmlString = '';
ob_start();
// This creates html format of an invoice
include('pdf_laskupohja_vanha.php');
$htmlString .= ob_get_clean();

// Case 1 working for the 1. loop
$dompdf = new DOMPDF();
$dompdf->load_html($htmlString);
$dompdf->render();
$output = $dompdf->output();

/* Case 2
$view = $dompdf->load->view("viewname", $htmlString, true);
//create a new dompdf instance
$dompdf->pdf = new DOMPDF();
//render and output pdf
$dompdf->pdf->load_html($view);
$dompdf->pdf->render();
$output = $dompdf->pdf->output(array("compress" => 0));
*/

/* Case 3
$dompdf->load->library('pdf');
$dompdf = new DOMPDF();
$dompdf->set_base_path(['path']);
//create a new dompdf instance (this is the crucial step)
$dompdf->load_view('viewname', $htmlString); 
$dompdf->render();
$output = $dompdf->output();
*/  
file_put_contents('../invoices/' .$invoice_file_name, $output);
}
echo "Invoice(es) OK";

是否有一种“隐藏”方式来实现这些(案例2和3)并未直接显示?可能包括对dompdf_config.inc.php或DOMPDF类的一些修改。事情是我不完全理解php类的结构。可能主要的解决方案是消除前一个循环的类对象并创建另一个但是如何?相信我,我已经好好忍受了好几天了。

1 个答案:

答案 0 :(得分:1)

我想你在这里问几个问题所以我会回答那个可能影响你最多的问题,即重用问题。

known issue重用dompdf对象实例。如果您只需要渲染几个单独的PDF,那么解决方法就是unset $dompdf $dompdf = new DOMPDF(); $dompdf->load_html('hello world'); $dompdf->render(); $pdfHello = $dompdf->output(); unset($dompdf); $dompdf = new DOMPDF(); $dompdf->load_html('goodbye world'); $dompdf->render(); $pdfBye = $dompdf->output(); 变量并重新使用它。

require '../vendor/dompdf/include/autoload.inc.php';

$invoices = 2;
$invoice_names = array();
for ($i=1; $i<=$invoices; $i++)
{
  // PDF-generating code here (NO dompdf require statement)
}
echo "Invoice(es) OK";

另一个值得注意的问题是,您应该只包含dompdf自动加载器一次,而不是每个循环包含一次。将require语句放在文件的顶部。

<elements>
    <!-- <element1 atribute="value"/> -->
    <!-- <element2 atribute="value"/> -->
    <!-- <element3 atribute="value"/> -->
    <!-- <element4 atribute="value"/> -->
    <!-- <element5 atribute="value"/> -->
</elements>