Zend framework 2 DomPdf No block-level parent found. Not good. error message
This error can be caused by many things, but the most notable is when attempting to reuse DomPdf to render more than one PDF.
This is to do with the way the service manager passes a single instance, and DOMPDF does not clean up after itself properly.
Attempting code like:
$html = $this->getServiceLocator()->get('viewpdfrenderer')->getHtmlRenderer()->render($pdf); $eng = $this->getServiceLocator()->get('viewpdfrenderer')->getEngine(); $eng->load_html($html); $eng->render(); |
Will fail, however despite the answer being very hard to find online the solution is rather simple, simply use the html renderer but request dompdf from the service manager, below I will render multiple PDF’s with different views, save them as files ready to be attached to an email.
// first PDF $pdf = new PdfModel(); $pdf->setTerminal(true); $pdf->setTemplate('template1'); $pdf->setVariables(array( 'foo' => 'bar' )); $html = $this->getServiceLocator()->get('viewpdfrenderer')->getHtmlRenderer()->render($pdf); $dompdf = $this->getServiceLocator()->get('dompdf'); // get fresh instance everytime $dompdf->load_html($html); $dompdf->render(); file_put_contents('file1.pdf', $dompdf->output()); // second pdf $pdf = new PdfModel(); $pdf->setTerminal(true); $pdf->setTemplate('template2'); $pdf->setVariables(array( 'foo' => 'bar' )); $html = $this->getServiceLocator()->get('viewpdfrenderer')->getHtmlRenderer()->render($pdf); $dompdf = $this->getServiceLocator()->get('dompdf'); // get fresh instance everytime $dompdf->load_html($html); $dompdf->render(); file_put_contents('file2.pdf', $dompdf->output()); |
Happy coding!
2,952 views
This entry was posted on Monday, July 25th, 2016 at 10:44 am and is filed under Php, ZF2. You can follow any responses to this entry through the RSS 2.0 feed.
Dear Adrian,
you saved me thousands of hours implementing a new pdfcreation modul!
Thanks a lot! Really!
Are you on PPH?