How to Add Tables to PDF Files with PHP

Learn how to integrate the pdfRest Add to PDF API with PHP and programmatically insert professional tables into PDF files.
Share this page

Why Add Tables to PDF with PHP?

The pdfRest Add to PDF API Tool provides a robust solution for integrating table data into existing PDF documents. This tutorial will guide you through the process of sending an API call to the Add to PDF endpoint using PHP. By leveraging this tool, developers can programmatically enhance PDFs with structured data, making it a valuable asset for automating document workflows.

Consider a scenario where a project manager needs to regularly update a PDF report with the latest project status, including milestones, owners, and progress. Using the Add to PDF API, they can automate this process, ensuring that the document is always up-to-date with minimal manual intervention. This not only saves time but also reduces the risk of errors in the documentation process.

Add Tables to PDF with PHP Code Example

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;

// By default, we use the US-based API service. This is the primary endpoint for global use.
$apiUrl = 'https://api.pdfrest.com';

/* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based service by uncommenting the URL below.
 * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 */
// $apiUrl = 'https://eu-api.pdfrest.com';

function projectStatusTable(): array
{
    $headerStyle = ['background_color_rgb' =--> [26, 72, 112], 'text_color_rgb' => [255, 255, 255]];
    return [[
        'page' => 1, 'x' => 54, 'y' => 540, 'width' => 504,
        'columns' => [['width' => 210], ['width' => 144], ['width' => 150]],
        'tag_structure_type' => 'Table',
        'style' => ['padding' => ['top' => 6, 'right' => 8, 'bottom' => 6, 'left' => 8], 'text_size' => 10],
        'header_rows' => [['cells' => [
            ['text' => 'Milestone', 'tag_structure_type' => 'TH', 'style' => $headerStyle],
            ['text' => 'Owner', 'tag_structure_type' => 'TH', 'style' => $headerStyle],
            ['text' => 'Status', 'tag_structure_type' => 'TH', 'style' => $headerStyle],
        ]]],
        'rows' => [
            ['cells' => [['text' => 'Requirements review'], ['text' => 'Maya Chen'], ['text' => 'Complete', 'tag_structure_type' => 'TD', 'style' => ['background_color_rgb' => [220, 252, 231]]]]],
            ['cells' => [['text' => 'Prototype delivery'], ['text' => 'Jordan Lee'], ['text' => 'In progress', 'tag_structure_type' => 'TD', 'style' => ['background_color_rgb' => [254, 249, 195]]]]],
            ['cells' => [['text' => 'Stakeholder approval'], ['text' => 'Avery Patel'], ['text' => 'Planned', 'tag_structure_type' => 'TD', 'style' => ['background_color_rgb' => [239, 246, 255]]]]],
        ],
        'footer_rows' => [['cells' => [[
            'text' => 'Next review: Friday, 10:00 AM', 'col_span' => 3, 'tag_structure_type' => 'TD',
            'style' => ['background_color_rgb' => [245, 247, 250], 'text_color_rgb' => [55, 65, 81]],
        ]]],
    ]]];
}

// Add an accessible project-status table with a header, colored status cells, and a footer.
$request = new Request('POST', $apiUrl . '/pdf-with-added-tables', [
    'Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', // Replace with your API key.
]);
$response = (new Client(['http_errors' => false]))->send($request, [
    'multipart' => [
        ['name' => 'file', 'contents' => Utils::tryFopen('/path/to/input.pdf', 'r'), 'filename' => 'input.pdf'],
        ['name' => 'table_objects', 'contents' => json_encode(projectStatusTable())],
        ['name' => 'tag_enabled', 'contents' => 'true'],
        ['name' => 'tag_language', 'contents' => 'en-US'],
        ['name' => 'output', 'contents' => 'project-status'],
    ],
]);

echo $response->getBody() . PHP_EOL;

Source: GitHub

Breaking Down the Code

The provided PHP script begins by including necessary packages using Composer's autoload feature. It utilizes GuzzleHttp for making HTTP requests, and Psr7 for handling requests and utilities.

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;

The API endpoint is set to the US-based service by default. Users in Europe can switch to the EU-based endpoint for GDPR compliance by uncommenting the relevant line.

$apiUrl = 'https://api.pdfrest.com';
// $apiUrl = 'https://eu-api.pdfrest.com';

The projectStatusTable function constructs an array representing the table to be added to the PDF. It specifies the page, position, dimensions, and styles for the table, header, rows, and footer.

function projectStatusTable(): array
{
    ...
}

A POST request is created, targeting the /pdf-with-added-tables endpoint. The request includes an API key for authentication.

$request = new Request('POST', $apiUrl . '/pdf-with-added-tables', [
    'Api-Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
]);

The request payload is multipart, containing the input PDF file, table data, and additional parameters like tag_enabled and tag_language. These parameters ensure that the PDF is tagged and specifies the language for tagging.

$response = (new Client(['http_errors' => false]))->send($request, [
    'multipart' => [
        ['name' => 'file', 'contents' => Utils::tryFopen('/path/to/input.pdf', 'r'), 'filename' => 'input.pdf'],
        ['name' => 'table_objects', 'contents' => json_encode(projectStatusTable())],
        ['name' => 'tag_enabled', 'contents' => 'true'],
        ['name' => 'tag_language', 'contents' => 'en-US'],
        ['name' => 'output', 'contents' => 'project-status'],
    ],
]);

The response from the API is output to the console, displaying the result of the API call.

echo $response->getBody() . PHP_EOL;

Beyond the Tutorial

In this tutorial, we successfully demonstrated how to use PHP to make an API call to pdfRest's Add to PDF tool, adding a table to a PDF document. This example serves as a foundation for integrating more complex features into your PDF workflows.

We encourage you to explore all the pdfRest API Tools in the API Lab. For further details, consult the API Reference Guide. This example demonstrates a multipart API call; for JSON payloads, refer to the GitHub repository.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.