-->

DOMPDF How to make PDFs height automatic

2019-04-16 06:29发布

问题:

I'm afraid that this question does not have an answer, but here it goes.

What I am trying to do is get people to fill in various information about them selves in my website, and echo all of it in a HTML template file (which gets converted into PDF later). Since all users have variable amounts of entries and entry lengths, it's impossible to predict the end result height of the document.

In other words: the more info a user gives about them selves, the higher in size the document gets. And there is no way to set DOMPDF to generate PDF heights according to the end result of the HTML template.

Am I missing a solution right under my nose here?

回答1:

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 ) );