Add Table to PDF using PHP

Insert table to PDF document programmatically using Aspose.PDF for PHP via Java Library

How to adding Tables in PDF document Using PHP via Java Library

In order to add table in a PDF, we’ll use Aspose.PDF for PHP via Java API which is a feature-rich, powerful and easy-to-use document manipulation tool in php-java. Install Tomcat 9.0 version on any location, add Aspose.PDF.war, for more details check the GitHub page.

Add Table to PDF using PHP


You need Aspose.PDF for PHP via Java to try the code in your environment.

  1. Load the PDF with an instance of Document.
  2. Access the Page via its index.
  3. Create Table object.
  4. Set table setting (e.g. set the borders).
  5. Populate table.
  6. Add the table to a page.
  7. Save the file.

Add Table in PDF - PHP

// Open document
$document = new Document($inputFile);        
// Initializes a new instance of the Table
$table = new Table();
$colors= new Color();
// Set the table border color as LightGray
$borderSide = new BorderSide();
$borderInfo = new BorderInfo($borderSide->All, 0.5, $colors->getLightGray());
$table->setBorder($borderInfo);
// set the border for table cells
$table->setDefaultCellBorder($borderInfo);
// create a loop to add 10 rows
for ($row_count = 1; $row_count < 10; $row_count++) {
    // add row to table
    $row = $table->getRows()->add();
    // add table cells
    $row->getCells()->add("Column (" . $row_count . ", 1)");
    $row->getCells()->add("Column (" . $row_count . ", 2)");
    $row->getCells()->add("Column (" . $row_count . ", 3)");
}
// Add table object to first page of input document
$document->getPages()->add()->getParagraphs()->add($table);

// Save resulting PDF document.    
$document->save($outputFile);
$document->close();