How to Generate a PDF using php

Spread the love

How to Generate a PDF using php

In the modern web development, the need to produce PDF documents dynamically is a common requirement. Whether you’re tasked with generating invoices, reports, certificates, or any other type of printable content, PHP offers a robust set of tools and libraries that make this task not only achievable but also highly customizable. In this tutorial, you’ll learn the step by step process to generate a pdf using php.

generate a pdf using php

By the end of this tutorial, you’ll be able to produce PDFs that cater to your specific needs, adding a valuable dimension to your web-based applications

Following steps will be performed in this tutorial,

1. Install Apache, PHP and MySQL

2. Install TCPDF library using composer

3. Create a db connection to connect to MySQL

4. Create a script to generate PDF using php from MySQL database

5. Execute the script

Prerequisites:

  1. A web server (e.g., Apache) with PHP and MySQL installed.
  2. Basic knowledge of PHP, MySQL, and SQL queries.
  3. Composer for installing PHP libraries.

Step 1: Set Up Your Environment

Ensure you have PHP, MySQL, and a web server installed and running. You can use XAMPP, WAMP, or MAMP for a local development environment.

Step 2: Create a Database

Create a MySQL database and a table to store student exam results. Here’s an example SQL script:

CREATE DATABASE exam_results;

USE exam_results;

CREATE TABLE students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    subject VARCHAR(255) NOT NULL,
    score INT NOT NULL
);


INSERT INTO `students` (`id`, `name`, `subject`, `score`) VALUES
(1, 'John Doe', 'Mathematics', 90),
(2, 'Jane Smith', 'Science', 85),
(3, 'Alice Johnson', 'English', 78),
(4, 'John Doe', 'Chemistry', 90),
(5, 'Jane Smith', 'Chemistry', 85),
(6, 'Alice Johnson', 'Physics', 78),
(7, 'John Doe', 'Biology', 90),
(8, 'Jane Doe', 'Drawing', 85),
(9, 'Alice K', 'Computer Science', 78),
(10, 'John Doe', 'Language Learning', 90),
(11, 'Jane Smith', 'Arts', 85),
(12, 'Alice Johnson', 'Science', 78);

Step 3: Install TCPDF Library (Optional)

To generate PDFs, we’ll use the TCPDF library. You can install it via Composer by creating a composer.json file in your project folder and running composer install Here’s a minimal composer.json.

{
    "require": {
        "tecnickcom/tcpdf": "^6.4"
    }
}

Step 4: Create PHP Script

Create a PHP script generate_results_pdf.php in your project directory. This script will connect to the database, fetch student exam results, and generate a PDF report.

<?php

require_once('vendor/autoload.php');
// Include TCPDF (if using Composer) 

use TCPDF as TCPDF;
// Alias for TCPDF class 
// Create a PDF instance 
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8');
$pdf->SetCreator('Your Name');
$pdf->SetAuthor('Your Name');
$pdf->SetTitle('Student Exam Results');
$pdf->SetSubject('Student exam results report');
$pdf->SetKeywords('TCPDF, PDF, PHP, example, tutorial');

// Add a page 
$pdf->AddPage();
// Connect to the MySQL database (replace with your credentials) 
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'exam_results'; // Your database name 

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
    die('Database connection failed: ' . $conn->connect_error);
}

// Retrieve student exam results from the database 
$query = "SELECT name, subject, score FROM students";
$result = $conn->query($query);

if ($result->num_rows > 0) {
    // Create a table for the exam results
    $html = "<h1 style=\"text-align: center; font-size: 18px;\">Students Exam Results Report</h1>";

    $html .= '<table style="width: 100%; border: none; border-radius: 5px; border-color: #007bff;">
        <tr style="background-color: #f2f2f2; color: #444; text-align: center; font-weight: bold; border-bottom: 2px solid #007bff;
            box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);">
            <th style="text-align: left;  width: 30%; flex: 1 0;">
                <h2 style="font-size: 15px; margin-bottom: 0;">Name</h2>
            </th>
            <th style="text-align: left;  width: 35%; flex: 1 0;">
                <h2 style="font-size: 15px; margin-bottom: 0;">Subject</h2>
            </th>
            <th style="text-align: left; width: 25%; flex: 1 0;">
                <h2 style="font-size: 15px; margin-bottom: 0;">Score</h2>
            </th>
        </tr>';

    $i = 0;
    while ($row = $result->fetch_assoc()) {
        // Add data to the table
        $row_class = ($i % 2 == 0) ? "even" : "odd";
        $html .= '<tr class="' . $row_class . '" style="background-color: ';
        if ($row_class == "even") {
            $html .= '#c3c3c3'; // Lighter tint of main background color
        } else {
            $html .= '#fff'; // White background color for odd rows
        }
        $html .= '; color: #333; text-align: center;">
        <td style="text-align: left; padding: 10px;"><p style="font-size: 14px; margin-bottom: 0;">' . $row['name'] . '</p></td>
        <td style="text-align: left; padding: 10px;"><p style="font-size: 14px; margin-bottom: 0;">' . $row['subject'] . '</p></td>';

        // Apply higher line-height to cells with longer text
        if (strlen($row['score']) > 7) {
            $html .= '<td style="padding: 10px;"><p style="font-size: 14px; margin-bottom: 0;">' . $row['score'] . '</p></td>';
        } else {
            $html .= '<td style="text-align: left; padding: 10px;"><p style="font-size: 14px; margin-bottom: 0;">' . $row['score'] . '</p></td>';
        }

        $html .= '</tr>';
        $i++;
    }
    $html .= '</table>';

    // Output the HTML table to the PDF
    $pdf->writeHTML($html, true, false, true, false, '');
} else {
    echo 'No records found.';
}

// Output the PDF to the browser
$pdf->Output('exam_results.pdf', 'I');





// Close the MySQL connection 
$conn->close();

Step 5: Run Your Script

Save the PHP script and run it by accessing it through your web server. For example, if you placed the script in your project’s root directory, access it in web browser at  http://localhost/your_project/generate_results_pdf.php

The script will connect to the database, retrieve student exam results, and generate a PDF report displaying the results in a tabular format.

generate pdf using php output.

You can further customize the PDF content, styling, and layout to suit your needs. This tutorial provides a foundation for creating dynamic PDF reports from database data using PHP and TCPDF. The PDF report will be saved in the root directory of the project with the name  exam_results.pdf.

Source Code for how to generate a pdf using php

You can find the source code and SQL file for database on our GitHub repository.

generate pdf using php source code

Related Articles

 

Previous Article

Next Article

 

Check Also

How to create WordPress plugin

How to create a WordPress plugin

Spread the loveLast updated:6th March, 2024How to create a WordPress plugin Creating a WordPress plugin …