icon

Table of Contents

How to generate PDF documents with PHP

PHP is a recursive acronym for Hypertext Preprocessor. This means that it refers to itself. The first P stands for PHP, and the second P stands for Preprocessor. The Hypertext part refers to the fact that PHP is often used to generate HTML pages that can be displayed in a web browser.

It is an open-source server-side scripting language used for web development and enables developers to create dynamic and interactive web pages. One interesting feature of PHP is its ability to generate PDF documents.

Generating PDF documents with PHP can be extremely useful in various scenarios, such as creating invoices, reports, or even e-books. It allows developers to create visually appealing documents that can be easily printed, shared, and stored. PDF documents generated with PHP can also contain interactive elements such as hyperlinks, form fields, and multimedia content.

There are various libraries available to generate PDF documents with PHP such as FPDF, TCPDF, or DOMPDF. These libraries provide a wide range of features for creating PDF documents, such as setting page size, margins, fonts, and images.

In this article, I would briefly discuss some of these libraries along with some code snippets and show you how to generate a PDF document using PHP and CraftMyPDF.

1. Common libraries to generate PDFs in PHP

PHP is an incredibly versatile language that has many benefits for web developers. One of the most impressive features of PHP is its ability to effortlessly generate PDF documents. With the help of powerful libraries, converting your files to PDF has never been easier.

Here are just a few of the top libraries that can assist you in creating beautiful, dynamic PDF documents:

1.1 FPDF (Free Portable Document Format)

FPDF is a PHP library that allows you to create PDF documents smoothly. Even if you’re a complete newbie to PHP and PDF generation, you can quickly get started with this powerful library. Here’s what you need to do:

i. Download the FPDF library from its official website.

ii. Once you’ve downloaded it, you can extract the files and save them in a newly created directory/folder called fpdf. You can name your directory however you like.

iii. Next, create a new PHP file called “newFPDFScript” (or any name you like) in the same directory you just created.

iv. Include the FPDF library in your newly created PHP script file using the “require” command.

<?php
    require('./fpdf.php');
?>

v. Create a new instance of the FPDF class.

<?php
    require('./fpdf.php');
    class mypdf extends FPDF{
    }
    $pdf = new mypdf();
?>

vi. Once you’ve created your class, you can start adding content to your PDF document. For example, you can add a new page using the “customizePage” function:

<?php
    
require('./fpdf.php');

class mypdf extends FPDF{
    function customizePage() {
       $this->SetFont('Arial', 'B',16);
       $this->Cell(40,10,'Welcome to CraftMyPDF!');
    }
}

$pdf = new mypdf();
// Call the AddPage method to add a page to the PDF document
$pdf->AddPage(); 
$pdf->customizePage();
$pdf->Output();      
?>

Save the file and test on your localhost. Your localhost URL should look similar to this http://localhost/fpdf/newFPDFScript.php

In this example, we created a new instance of the FPDF class and called the customizePage method to customize a page in our PDF document.

We then set the font and font size using the SetFont method, and added some text to the PDF document using the Cell method.

Finally, we called the AddPage method to add a page to the PDF document and output the PDF document using the Output method.

1.2 DOMPDF

Dompdf is a PHP library that allows you to convert HTML documents to PDF format. It is open source and is based on the PHP DOM extension. It uses the CSS Parser to convert CSS styles into inline style attributes and also supports a variety of HTML features, including tables, images, and basic HTML and CSS layouts.

The library is designed to be easy to use and integrate into your PHP application. You can create a PDF document by simply passing an HTML string to the Dompdf library, which will generate a PDF file that you can then save to your server or send to the client.

Dompdf also supports advanced features like custom fonts, page numbering, headers, and footers. It also has built-in support for Unicode and right-to-left languages. The library can be installed via composer using the following command

composer require dompdf/dompdf

Alternatively, you have the option of cloning the repository from Github onto your system. Once you have cloned the repository, navigate to the folder you cloned and create a new file named “index.php”. Then, insert the following code snippet into the file.

<?php
// Include autoloader 
//Make sure you link the file correctly using your own localhost url
require_once 'C:\xampp\htdocs\dompdf\autoload.inc.php'; 

    
// Reference the Dompdf namespace 
use Dompdf\Dompdf; 
    
// Instantiate and use the dompdf class 
$dompdf = new Dompdf();

$html='
<style>
    table {
        font-family: arial;
        width:400px;
        border-collapse: collapse;
    }
    td, th {
        border: 1px solid black;
        text-align: left;
        padding: 8px;
    }
    tr:nth-child(even) {
        background-color: seagreen;
    }
</style>
<h1>Welcome to CraftMyPDF</h1>
<h3>List of Registered users </h3>
<table>
    <tr>
        <th>Email</th>
        <th>Username</th>
        
    </tr>
    <tr>
        <td>[email protected]</td>
        <td>vicboy</td>
    </tr>
    <tr>
        <td>[email protected]</td>
        <td>forever_janet</td>
    </tr>

</table>

';
// Load HTML content 
$dompdf->loadHtml($html);
    
    
// (Optional) Setup the paper size and orientation 
$dompdf->setPaper('A4', 'landscape'); 
    
// Render the HTML as PDF 
$dompdf->render(); 
    
// Output the generated PDF to Browser 
$dompdf->stream();
?>

Save the file and test on your localhost.

This code creates a PDF document with the following HTML and CSS layout.

1.3 TCPDF

TCPDF is a PHP library for generating PDF documents. It allows developers to easily create and manipulate PDF files using PHP code. It provides a wide range of features such as support for various fonts and Unicode characters, different page formats, header and footer customization, bookmarks, annotations, and digital signatures.

It also allows developers to add images, text, and vector graphics to the PDF document.

TCPDF has been used for various purposes, such as generating invoices, certificates, reports, and other types of documents. It is highly customizable and can be integrated with various PHP frameworks and applications.

In order for it to work, the following steps are necessary:

  1. Clone the repository.
  2. Create a file with the name ‘pdfScript.php’ (or any other desired name) within the cloned folder.
  3. Insert the provided code snippet into the created file
<?php

    // Include the main TCPDF library (search for installation path).
    require_once('tcpdf.php');

    // create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    // set document information
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('Nicole Asuni');
    $pdf->SetTitle('PDF file using TCPDF');

    // set default header data
    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 006', PDF_HEADER_STRING);

    // set header and footer fonts
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

    // set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    // set margins
    $pdf->SetMargins(20, 20, 20);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    // set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    // set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

    // add a page
    $pdf->AddPage();

    $html = <<<EOD
<h1>TCPDF PHP Library is easy!</h1>
<p> My name is Ayeesha </p>
<i>This is an example of the TCPDF library.</i>
<p>I am using the default header and footer</p>
<p>Please check the source code documentation for more examples of using TCPDF.</p>

EOD;

// Print text using writeHTMLCell()
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);

        
    // $pdf->writeHTML($html, true, false, true, false, '');
    
        // add a page
    $pdf->AddPage();

    $html = '<h4>Second page</h4>';
    
    $pdf->writeHTML($html, true, false, true, false, '');

    // reset pointer to the last page
    $pdf->lastPage();
    //Close and output PDF document
    $pdf->Output('example.pdf', 'I');

?>

Save the file and test on your localhost

By utilizing the TCPDF library’s default header and footer, a PDF document is created. Additional examples of how to implement the library can be located on their website.

2. Using CraftMyPDF to generate PDFs in PHP

CraftMyPDF allows you to generate PDFs in PHP smoothly. It supports the use of REST APIs which can help you easily design PDF templates and generate eye-catching PDF documents using JSON data. It boasts several impressive capabilities, including:

  • The ability to convert HTML to PDF
  • Compatibility with CSS, JavaScript, PHP, and Python
  • Integration with various no-code platforms such as Zapier, n8n, Airtable, Bubble.io, and more.
  • Support for custom footer and header with page numbers and total pages.

To generate a PDF document in PHP using CraftMyPDF, here’s what you need to do:

  1. Sign up/Login: Create an account on CraftMyPDF or login if you already have an existing account. Don’t worry, you do not need to input your card details.
  2. Go to Manage Templates: After your registration is complete, you would be automatically directed to your dashboard. Go to Manage Templates which is located at the top of the page, on your “Manage Templates” page, select New PDF Template.
  1. Select New PDF Template: After selecting “New PDF Template”, you would be directed to a “Create a new template” page. You can decide to choose whatever template suits you best with the possibility of modifying it as you wish. I would be choosing the “Simple invoice” template.
  1. Create Template: Click on the Create template button. You would be redirected to your dashboard where you can view your template_id, edit, clone etc. You can also modify the name of your template (template_id) to whatever you like. Your new invoice template is ready to go!

  2. Get API Key from “API Integration”: Now, back to your dashboard, click on the API Integration toolbar, and copy the default API key that has been generated for you. We would be using this API key to create our API endpoint so make sure it’s copied on your clipboard.

  1. Copy the following code snippet into your PHP script, we would be inserting some parameters like the template_id, API key, CraftMyPDF URL, and JSON data from our invoice.
<?php
function main() {
    $api_key = "a4b8MTg3MzoxODczOnd2SEkwM1d3QUxnWUpw123";
    $data = [
        'invoice_number' => 'INV38379',
        'date' => '2021-09-30',
        'currency' => 'USD',
        'due_date' => '2022-09-30',
        'discount' => 5,
        'tax' => 7,
        'company_name' => 'LOGO Consulting Pte Ltd',
        'email' => '[email protected]',
        'client' => 'Orsis Pte Ltd',
        'client_address' => '2769 Nutter Street,',
        'client_address2' => 'Kansas City, Missouri',
        'client_address3' => '64105',
        'items' => [
            [
                'description' => 'AWS Webservices',
                'quantity' => 10,
                'unit_price' => 50,
                'total' => 500
            ],
            [
                'description' => 'Web Design & Elementor Theme',
                'quantity' => 5,
                'unit_price' => 40,
                'total' => 200
            ],
            [
                'description' => 'Software Development',
                'quantity' => 2,
                'unit_price' => 60,
                'total' => 120
            ],
            [
                'description' => 'IT Consulting',
                'quantity' => 20,
                'unit_price' => 50,
                'total' => 1000
            ],
            [
                'description' => 'Social Media Page',
                'quantity' => 8,
                'unit_price' => 40,
                'total' => 320
            ]
            ],
    'gross_total'=> 25055
    ]
        ;

    $json_payload = [
        "data" => json_encode($data),
        "output_file" => "output.pdf",
        "export_type" => "json",
        "expiration" => 10,
        "template_id" => "d1d77b2b2e24ae40"
    ];

    $url = "https://api.craftmypdf.com/v1/create";
    $headers = ["X-API-KEY: $api_key"];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    echo $response;
}

main();
?>

Note: Replace the API key and the template_id with the correctly generated values for the script to work

This endpoint aims to produce a PDF document that incorporates both JSON data and a pre-defined template. We can test the script on our localhost to ensure it works. You should get an output similar to this.

Copy the link to the PDF file and paste in your browser, the final output should look like this

3. Test CraftmyPDF with PostMan

We can also test the API on Postman, here’s what you need to do:

  1. Open Postman and create a new request by clicking on the “New” button.
  2. Select the HTTP method as POST.
  3. In the request URL field, enter the API endpoint URL provided by the third-party API. In this case, the URL is https://api.craftmypdf.com/v1/create.
  4. In the request HEADERS section, add a new header with the key X-API-KEY and the value of your API key (a4b8MTg3MzoxODczOnd2SEkwM1d3QUxnx1234). This header is required for authentication.
  5. In the request body section, select the raw format and choose JSON as the data type.
  6. Paste the following JSON payload in the request body field:
{
    "data": {
    "invoice_number": "INV38379",
    "date": "2021-09-30",
    "due_date": "2021-10-30",
    "currency": "USD",
    "tax": 7,
    "company_name": "LOGO consulting",
    "email": "[email protected]",
    "client": "OpenAI Ltd",
    "client_address": "20 New York, NJ",
    "client_address2": "Washington, DC",
    "client_address3": "Akansas",
    "items": [
        {
            "description": "AWS Web services",
            "quantity": 10,
            "unit_price": 50,
            "total": 100
        },
            
        {
            "description": "Web Design & Elementor Theme",
            "quantity": 5,
            "unit_price": 40,
            "total": 200
        },
        {
            "description": "Software Development",
            "quantity": 2,
            "unit_price": 60,
            "total": 120
        },
        {
            "description": "IT Consulting",
            "quantity": 20,
            "unit_price": 50,
            "total": 1000
        },
        {
            "description": "Social Media Page",
            "quantity": 8,
            "unit_price": 40,
            "total": 320
        }
    ],
    "total_amount": 82542.56
    },
    "load_data_from": null,
    "template_id": "d1d77b2b2e24ae40",
    "version": 8,
    "export_type": "json",
    "expiration": 60,
    "output_file": "output.pdf",
    "is_cmyk": false,
    "image_resample_res": 600,
    "direct_download": 0,
    "cloud_storage": 1
}

This is the same payload that is being used in the PHP code.

7. Click on the “Send” button to send the request. If everything goes well, you should receive a response with the download URL for the generated PDF file similar to the screenshot below.

With the URL, you should be able to generate a PDF similar to the image below.

4. Benefits of CraftMyPDF

CraftMyPDF has several benefits, including:

  • Drag-and-drop editor that gives you the ability to generate high-quality PDFs quickly and easily, without the need for complex coding or design skills.
  • Integration with various no-code platforms such as Zapier, n8n, Airtable, Bubble.io, and more.
  • Access to a diverse range of quality fonts. Our font selection supports over 25 languages including Latin, Greek, Arabic, Japanese, Chinese, Vietnamese, Korean, Hebrew, Arabic, Tamil, and more.
  • Our PDF editor can be seamlessly integrated into your application.
  • Expressions and formatting for datetime, currency, and custom formats are fully supported by our PDF template editor. Additionally, these expressions can be utilized to incorporate headers and footers into your PDF document.
  • It allows you to create fillable PDF templates smoothly with our drag-and-drop editor.

5. Conclusion

There are several ways to generate PDF documents using PHP, including libraries such as FPDF, Dompdf, and TCPDF, as well as using a service like CraftMyPDF.

With the ability to create customized PDFs, incorporating different styles and templates, you can effectively communicate your ideas to your target audience.

So, whether you’re a developer, web designer, or just someone who needs to create PDFs regularly, there are plenty of options available to help you get the job done.

Recent Posts
blog

How to generate PDF documents with PHP

There are various libraries available to generate PDF documents with PHP such as FPDF, TCPDF, or DOMPDF. These libraries provide a wide range of features for creating PDF documents, such as setting page size, margins, fonts, and images.

In this article, I would briefly discuss some of these libraries along with some code snippets and show you how to generate a PDF document using PHP and CraftMyPDF.

Read More »
blog

5 Ways to generate PDFs with C#

In this article, we will cover different options available, including using libraries such as iTextSharp and PdfSharp, cloud-based APIs such as CraftMyPDF, built-in classes in the .NET Framework like the PrintDocument class, and the Microsoft Office Interop library.

Read More »
blog

How to Generate PDF Invoices with Zapier

With PDF invoices, it’s easier to send invoices directly to clients without needing paper copies.

In this article, I would be showing you how to generate PDF invoices with Zapier and also help you understand the benefits of doing this. Let’s get to it!

Read More »
blog

Best-performing Banner Ads Sizes in 2023

Choosing the most appropriate banner for your company isn’t always easy. There are lots of things to consider such as the color, size, type of banner, and so on. This could be a little problematic if you have no knowledge of the different types of banner ads but don’t worry, that’s why I’m here.

Read More »
blog

How to create PDF invoices with Bubble.io

In this tutorial, we will create line items for an invoice template.

The takeaway of the tutorial is to build JSON with our Bubble plugin actions Thing(s) to JSON and Build JSON for complex JSON that consists of line items(an array). Then, the JSON will be used for generating the dynamic PDF documents.

Read More »
Copyright ©2024 CraftMyPDF.com

Email us at [email protected] for support