Tag

pdf generator in php

Browsing

Hi, Do you need to generate PDFs dynamically in your PHP web application? Look no further! In this step-by-step guide, we’ll show you how to generate PDFs in PHP using a variety of tools and techniques. From setting up your development environment to generating PDFs from HTML, we’ll cover all the bases. Whether you need to generate PDFs on button click, save them to a folder, or create custom PDFs, this guide has got you covered.

We’ll also explore popular PDF libraries for PHP and share best practices for optimizing PDF generation performance. So, let’s dive in and learn how to generate PDFs in PHP like a pro! So let’s get started with the steps by step guide. You check this demo also before starting to code.

Check Also: Load more data using jQuery, AJAX, and PHP

when you click on the Load more button it will load another 2 quotes and append them to the current list. This process will go so on and so far until there are no remaining quotes

Follow these steps to generate PDFs in PHP

1. Install Composer

A composer is a tool for dependency management in PHP, that allows you to add/install the libraries and packages for your project and it will manage (install/update) them for you. Go to the download page download the Composer-Setup.exe, and get it installed on your machine. To verify the installation open the command prompt and type in “composer” You will see the version and other information.

2. Install mPDF Library

For generating PDFs using PHP, Composer is required because we are going to use mPDF which is a PHP library that will be installed via Composer. So go to your project folder, open the command prompt & hit the command given below, this will install the mPDF library.

composer require mpdf/mpdf

3. Create files & folders

So we are ready to generate PDF in PHP, before that we need to create files & folders and create the highlighted files in your project directory as per the given screenshot. Vendor folder, composer.json & composer. lock file will be created automatically when you complete step-2.

Let me just walk you through these files and folders:

  • “docs” is the folder to store the generated PDF
  • index.php is the main file that will display the UI screen to generate pdf on button click.
  • script.php file will contain the business logic to create a pdf in PHP
  • style.css file contains the CSS to style the PDF

4. Write the code

So we have created the files and folder, and after that update your files with the code given below.

index.php

<!doctype html>
<html lang="en">
<head>
    <title>Generate PDfs in PHP - Coding Birds Online</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png" type="image/x-icon">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div class="card card-signin my-5">
                <div class="card-body">
                    <center>
                        <img width="50" src="https://codingbirdsonline.com/wp-content/uploads/2019/12/cropped-coding-birds-favicon-2-1-192x192.png">
                        <h5 class="card-title text-center mt-4">Click to Download PDF</h5>
                        <img src="https://codingbirdsonline.com/cdn/icons/download.png"
                    </center>
                    <div class="mt-3">
                        <a href="script.php" class="btn btn-danger">Click to Download PDF</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

script.php

<?php
require("vendor/autoload.php");

try {
    $html = getPdfContent();
    $filename = "invoice.pdf";
    $stylesheet = file_get_contents('style.css');
    $mpdf = new \Mpdf\Mpdf();
    $mpdf->WriteHTML($stylesheet,\Mpdf\HTMLParserMode::HEADER_CSS);
    $mpdf->WriteHTML($html);
    ob_clean();
    $mpdf->Output($filename, "D"); // This downloads the file
    $mpdf->Output("docs/$filename", "F"); // This saves the file to folder
} catch (\Mpdf\MpdfException $e) {
    echo "Something went wrong: ". $e->getMessage();
}
/**
 * This function prepares the PDF content
 * @return html|string
 */
function getPdfContent(){
    /**
     * Here this $student is just an static data
     * Create your own business logic like get the data from db, modify, loop...etc
     */
    $students = array(
        array(
          "name" => "Ankit",
          "email" => "ankit@ankit.com",
          "contact" => "xxxxxxx85555",
          "country" => "India",
        ),
        array(
            "name" => "Parth",
            "email" => "parth@gmail.com",
            "contact" => "xxxxxxx88855",
            "country" => "India",
        ),
        array(
            "name" => "Rohit",
            "email" => "rohit@gmail.com",
            "contact" => "xxxxxxx85525",
            "country" => "India",
        ),
        array(
            "name" => "Allex",
            "email" => "allex@gmail.com",
            "contact" => "xxxxxxx85555",
            "country" => "India",
        )
    );
    $table = '<table>
              <tr>
                <th>#</th>
                <th>Name</th>
                <th>Email</th>
                <th>contact</th>
                <th>Country</th>
              </tr>';
    foreach ($students as $key => $student){
        $table .= '
              <tr>
                <td>'.($key+1).'</td>
                <td>'.$student['name'].'</td>
                <td>'.$student['email'].'</td>
                <td>'.$student['contact'].'</td>
                <td>'.$student['country'].'</td>
              </tr>';
    }
    $table .= '</table>';
    return $table;
}

style.css

table {
    border-collapse: collapse;
    width: 100%;
}
th {
    background: #ccc;
    text-align: left;
}

th, td {
    border: 1px solid #ccc;
    padding: 8px;
}

tr:nth-child(even) {
    background: #efefef;
}

tr:hover {
    background: #d1d1d1;
}

5. Run It!!

Since we have completed writing the code, and now it is time to see what our changes look like. So save all files and after that open the project in your local host. In my case it is http://localhost/projects/codingbirds_/generate-pdfs-in-php.

Here is the output screenshot that looks like.

Generate PDFs in PHP

When you click, it will generate PDF and save in a folder(docs).

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also before starting to code.

Conclusion

I hope you learned what I explained in the above steps, If you have any suggestions are appreciated. And if you have any errors or issues please comment definitely I will try to help. You can download the full 100% working source code from here.

As I have shown If this code works for you, please leave a nice ❤️ comment so that others can find it useful which always gives me the motivation to create such content.