Creating Multi-Page PDFs in PHP Using FPDF: Fixed Records vs. Dynamic Page Addition


Generate PDF with Multiple Pages Dynamically based on number of rows of records in PHP using FPDF

Part I : Using number of records per page & total records

In this part, we create a multipage PDF where the number of pages is determined based on the total records from a database table. The pages are dynamically added as needed.

Steps to Generate the PDF

  • Connect to the Database: Retrieve the total number of records. ( Show the code for config.php file )
  • Determine the Number of Pages: Use the ceil() function to calculate the total pages.
  • Loop Through Pages: Fetch 10 records per page and generate a new page if needed.
  • Apply Alternate Row Colors: Enhance table readability by using different row colors.

PHP Code to Generate Multi-Page PDF

<?Php
require('config.php'); // Database Connection
require('fpdf.php'); // Include FPDF Library

$pdf = new FPDF();
$pdf->SetFont('Arial', 'B', 16);

// Column width settings
$width_cell = array(20, 50, 40, 40, 40);

// Fetch total records
$sql_total = "SELECT COUNT(*) AS total FROM student";
$total_result = $dbo->query($sql_total);
$total_records = $total_result->fetch(PDO::FETCH_ASSOC)['total'];

// Define records per page
$records_per_page = 10;
$total_pages = ceil($total_records / $records_per_page);

// Loop through pages
for ($page = 0; $page < $total_pages; $page++) {
    $pdf->AddPage();

    // Print Table Header (Repeats on every new page)
    $pdf->SetFillColor(193, 229, 252);
    $pdf->Cell($width_cell[0], 10, 'ID', 1, 0, 'C', true);
    $pdf->Cell($width_cell[1], 10, 'NAME', 1, 0, 'C', true);
    $pdf->Cell($width_cell[2], 10, 'CLASS', 1, 0, 'C', true);
    $pdf->Cell($width_cell[3], 10, 'MARK', 1, 0, 'C', true);
    $pdf->Cell($width_cell[4], 10, 'GENDER', 1, 1, 'C', true);

    // Fetch records for current page
    $offset = $page * $records_per_page;
    $sql = "SELECT * FROM student LIMIT $offset, $records_per_page";
    $result = $dbo->query($sql);

    // Alternate row colors
    $pdf->SetFillColor(235, 236, 236);
    $fill = false;

    // Display records for current page
    foreach ($result as $row) {
        $pdf->Cell($width_cell[0], 10, $row['id'], 1, 0, 'C', $fill);
        $pdf->Cell($width_cell[1], 10, $row['name'], 1, 0, 'L', $fill);
        $pdf->Cell($width_cell[2], 10, $row['class'], 1, 0, 'C', $fill);
        $pdf->Cell($width_cell[3], 10, $row['mark'], 1, 0, 'C', $fill);
        $pdf->Cell($width_cell[4], 10, $row['gender'], 1, 1, 'C', $fill);
        $fill = !$fill;
    }
}
$pdf->Output();
?>
DEMO : Multi-Page PDF by using fixed number of records per page

Part II: Dynamic Page Addition Based on Available Space

In this approach, instead of using a fixed number of records per page, we dynamically check the available space on the page. When there is not enough space to accommodate the next row, a new page is added automatically to continue displaying records.

How It Works?

  • We use $pdf->GetY() to check the current Y position (vertical space used).
  • If the next row exceeds the bottom margin, a new page is created.
  • This allows flexible record display without restricting to a fixed number of rows per page.

Key Code Logic

The following condition checks whether a new page is needed:

if ($pdf->GetY() + 10 > 280) { // Adjust if Needed
    $pdf->AddPage(); // Add a new page
}

Benefits of This Approach

  • Adaptive Page Management: No need to predefine records per page.
  • Efficient Space Usage: Records are adjusted dynamically based on available space.
  • Scalability: Works well with varying row heights and different page sizes.

This method ensures that all records fit optimally in the available space, making the PDF generation dynamic and efficient.



<?php
require('config.php'); // Database Connection
require('fpdf.php'); // Include FPDF Library

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);

// Column Widths
$width_cell = [20, 50, 40, 40, 40];

// Function to Print Table Headers
function add_table_header($pdf, $width_cell) {
    $pdf->SetFillColor(193,229,252);
    $pdf->Cell($width_cell[0],10,'ID',1,0,'C',true);
    $pdf->Cell($width_cell[1],10,'NAME',1,0,'C',true);
    $pdf->Cell($width_cell[2],10,'CLASS',1,0,'C',true);
    $pdf->Cell($width_cell[3],10,'MARK',1,0,'C',true);
    $pdf->Cell($width_cell[4],10,'GENDER',1,1,'C',true);
}

// Print Initial Table Headers
add_table_header($pdf, $width_cell);
$pdf->SetFont('Arial', '', 14);
$pdf->SetFillColor(235,236,236);

$fill = false; // Alternate Row Color

// SQL Query to Fetch All Records
$sql = "SELECT * FROM student";

// Loop Through Records
foreach ($dbo->query($sql) as $row) {

    // Check if Space is Left for Next Row
    if ($pdf->GetY() + 10 > 280) { // Adjust if Needed
        $pdf->AddPage();
        add_table_header($pdf, $width_cell); // Reprint Headers
    }

    // Print Row Data
    $pdf->Cell($width_cell[0],10,$row['id'],1,0,'C',$fill);
    $pdf->Cell($width_cell[1],10,$row['name'],1,0,'L',$fill);
    $pdf->Cell($width_cell[2],10,$row['class'],1,0,'C',$fill);
    $pdf->Cell($width_cell[3],10,$row['mark'],1,0,'C',$fill);
    $pdf->Cell($width_cell[4],10,$row['gender'],1,1,'C',$fill);

    // Toggle Row Color
    $fill = !$fill;
}

// Output PDF
$pdf->Output();
?>
DEMO : Multi-Page PDF based on Available Space

pdf-data-student_v1 : Download Zip file for PDF document creation with data from table ( Including SQLite database ) from end of this page


MultiCell Cell()
Adding Image to PDF File

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com











    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer