Search code examples
phphtmldompdf

Have dynamic content span across pages in php


I have the following code that dynamically loads items in an invoice. I am looking for a way to adds excess items to a new page, and so on. I would like to limit the # of items on a page to a set amount, say 15 items. Is there a way to do this in php? The code below is within a document that uses dompdf to appear in pages form

foreach ( $invoice['InvoiceDetail'] as $key=>$item){
        $html .= '<tr style="border-bottom: 1px solid #ccc; line-height: 15px;">';
            $itemNo = isset($item['product_id']) ? $item['product_id'] : '';
            $itemName = isset($item['productName']) ? $item['productName']: '';
            $price = isset($item['price']) ? invoiceNumFormat($item['price']): '';
            $quantity = isset($item['quantity']) ? $item['quantity'] : '';
            $total = invoiceNumFormat( $item['price']*$item['quantity']);

            $html .= '<td style="text-align: left"><h5>'.$itemNo.'</h5></td>';
            $html .= '<td style="text-align: left">'.$itemName.'</td>';
            $html .= '<td style="text-align: left">'.$price.'</td>';
            $html .= '<td style="text-align: left" width="10px">'.$quantity.'</td>';
            $html .= '<td style="text-align: right">'.$total.'</td>';
        $html .= '</tr>';
    }

Dynamic Example


Solution

  • For your particular situation you could just indicate to dompdf to break the page, something along the lines of:

    $itemCount = 0;
    foreach ( $invoice['InvoiceDetail'] as $key=>$item){
        $itemCount++;
        $html .= '<tr style="border-bottom: 1px solid #ccc; line-height: 15px;">';
    
            /* snip */
    
            if ($itemCount % 20 == 0) {
                $html .= '<tr><td><div style="page-break-before: always;"></div></td></tr>';
            }
    
            $html .= '<td style="text-align: left"><h5>'.$itemNo.'</h5></td>';
            $html .= '<td style="text-align: left">'.$itemName.'</td>';
            $html .= '<td style="text-align: left">'.$price.'</td>';
            $html .= '<td style="text-align: left" width="10px">'.$quantity.'</td>';
            $html .= '<td style="text-align: right">'.$total.'</td>';
    
        $html .= '</tr>';
    }
    

    Dompdf does not yet recognize page break styling on table rows/cells. Otherwise it would make more sense to place the styling there.