csslaravelpdfdompdf

How to handle page breaks before an element in CSS?


I would like to break the page for every fourth item on each page of the pdf. To break the page I used the page-break-before property. But the problem is the design is broken down from the second page. The code is as below.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>DOM-PDF</title>
  </head>
  <body>
    <table style="width:100%;">
        <thead>
            <tr>
                <th>Serial</th>
                <th>Name</th>
                <th>Roll</th>
                <th>Info</th>
            </tr>
        </thead>
        <tbody>
        @php
        $n = 0;
        for($i=0;$i<10;$i++){
        @endphp
            <tr style="text-align:center;">
                <td>$i+1</td>
                <td>ABC.$i+1</td>
                <td>120803.$i+1</td>
                <td>I am an employee.</td>
            </tr>
        
        @php
        if($n==3){
        echo "<i style='page-break-before:always;'></i> ";
        }
        $n++;
        }
        @endphp
        </tbody>
    </table>
  </body>
</html>

This is the pdf view of page 1

![![enter image description here

This is the pdf view of page 2

![![![enter image description here

On page 2 second row moves to the right. How to fix it?


Solution

  • What about using chunks instead of breaking the table?

    {{-- Replace collect()->times(10) with a collection when you're getting the actual data from DB --}}
    @foreach (collect()->times(10)->chunk(3) as $chunk)
        <table style="width:100%;">
            <thead>
                <tr>
                    <th>Serial</th>
                    <th>Name</th>
                    <th>Roll</th>
                    <th>Info</th>
                </tr>
            </thead>
            <tbody>
                @foreach($chunk as $result)
                    <tr style="text-align:center;">
                        <td>{{ $result }}</td>
                        <td>Rashedul Hasan</td>
                        <td>1208039</td>
                        <td>I am an employee.</td>
                    </tr>        
                @endforeach
            </tbody>
        </table>
        <i style='page-break-before:always;'></i>
    @endforeach