DOMPDF How to make PDFs height automatic

回眸只為那壹抹淺笑 提交于 2019-12-04 19:34:11

There is not a built-in way to do this, but that doesn't mean it is not possible. You happen to be the second person to ask this and that first time I did manage come up with a way it can be done.

The following comes from an original post on the dompdf support group.


First, you need to make a minor modification to the stylesheet of your document. You want to set the top and bottom page margins to zero so they don't add in to the height calculation. So in your first-pass HTML add the following additional style declaration:

@page { margin-top: 0px; margin-bottom: 0px; }

Next, you have to determine what the best first-pass document size will be. I was using a simple document, so I went with a simple 8cm x 8cm page size. You'll probably want to use a larger height to avoid any bugs related to paging. 8cm is roughly 226.77pt. So I set up the first pass to use a document defined with the appropriate dimensions:

$dompdf = new DOMPDF( );
$dompdf->set_paper( array( 0 , 0 , 226.77 , 226.77 ) );
$dompdf->load_html( $first_pass_html );
$dompdf->render( );

Then we get the number of pages that resulted from this pass and unset the $dompdf variable so we can do our second pass:

$page_count = $dompdf->get_canvas( )->get_page_number( );
unset( $dompdf );

Finally, render the document a second time using a page height calculated from the page height used in the first pass multiplied by the number of pages generated (plus a little extra padding to accommodate margins).

$dompdf = new DOMPDF( );
$dompdf->set_paper( array( 0 , 0 , 226.77 , 226.77 * $page_count + 20 ) );
$dompdf->load_html( $original_html );
$dompdf->render( );
$dompdf->stream( 'sample.pdf' , array( 'Attachment' => 0 ) );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!