Open In App

Setting Background to a Table in a PDF using Java

Last Updated : 08 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Have you ever wondered how different cells in a PDF table are set to various colors? Well, in this article we’ll be seeing how we can set the background of various cells in a PDF table using the iText library in your favorite language Java.

Downloading iText

Create a new Java Maven project and add the following dependencies in the pom.xml file. This step adds all the required jar files into the Maven dependencies.

XML




<dependencies>       
      <dependency>         
         <groupId>com.itextpdf</groupId>         
         <artifactId>kernel</artifactId>         
         <version>7.0.2</version>     
      </dependency>  
        
      <dependency>         
         <groupId>com.itextpdf</groupId>         
         <artifactId>io</artifactId>         
         <version>7.0.2</version>     
      </dependency>  
        
      <dependency>         
         <groupId>com.itextpdf</groupId>         
         <artifactId>layout</artifactId>         
         <version>7.0.2</version>
      </dependency>  
        
      <dependency>         
         <groupId>com.itextpdf</groupId>         
         <artifactId>forms</artifactId>         
         <version>7.0.2</version>    
      </dependency>  
        
      <dependency>         
         <groupId>com.itextpdf</groupId>         
         <artifactId>pdfa</artifactId>         
         <version>7.0.2</version>     
      </dependency>  
        
      <dependency>         
         <groupId>com.itextpdf</groupId>         
         <artifactId>sign</artifactId>         
         <version>7.0.2</version>     
      </dependency>  
        
      <dependency>         
         <groupId>com.itextpdf</groupId>         
         <artifactId>barcodes</artifactId>         
         <version>7.0.2</version>     
      </dependency>  
        
      <dependency>         
         <groupId>com.itextpdf</groupId>         
         <artifactId>font-asian</artifactId>         
         <version>7.0.2</version>     
      </dependency>  
        
      <dependency>         
         <groupId>com.itextpdf</groupId>         
         <artifactId>hyph</artifactId>         
         <version>7.0.2</version>    
      </dependency
   </dependencies>


Setting the background to a PDF Table

Step 1: Create an empty PDF file.

  • Assign the path of the empty PDF to a String variable.
  • Import PdfWriter from the package com.itextpdf.kernel.pdf. (PdfWriter allows us to write content on our PDF file)
  • PdfWriter accepts a String variable as it’s a parameter which represents the destination of the PDF.
  • Initialize the PdfWriter object by passing the path of the PDF file.

The following code creates an empty PDF.

String path = "F:/Table.pdf"; 
PdfWriter pdfWriter = new PdfWriter(path);

Step 2: Create a PDF document which represents the empty PDF file.

  • Import PdfDocument from the package com.itextpdf.kernel.pdf. (PdfDocument is used represent the pdf in code. This later can be used to add or modify various features such as font, images, table, etcetera)
  • PdfDocument accepts a PdfWriter or PdfReader object as it’s parameter.
  • Initialize the PdfDocument by passing the PdfWriter object.

The following code creates a PdfDocument which represents the empty PDF file.

PdfDocument pdfDoc = new PdfDocument(pdfWriter);

Step 3: Create a Document.

  • Import Document from the package com.itextpdf.layout.
  • A Document object is created to make a readable version of the PDF.
  • One of the constructors of the Document class accepts PdfDocument object as it’s parameters.
  • Initialize the document by passing the PdfDocument object.

The following code creates a document.

Document doc = new Document(pdfDoc);

Step 4: Create a Table.

  • Import Table from the package com.itextpdf.layout.element.
  • A table is created by cells, and each cell occupies a unit row and column.
  • The table constructor accepts the number of columns as it’s parameters.
  • Initialize the table object by passing the number of columns as it’s a parameter.

The following code creates a Table.

Table table = new Table(3);

Step 5: Add cells to the table with a favoured background using setBackgroundColor(Color.color, float opacity).

  • Import Cell from the package com.itextpdf.layout.element.
  • Import Color from the package com.itextpdf.kernel.color.
  • Initialize the number of cells you want to add to the table.
  • Add text to the cells using add(String text).
  • Set the background color of the cells using setBackgroundColor(Color.color, float opacity).
  • Add the cells to the table.

The following code creates and adds cells to the Table.

Cell cell = new Cell();
cell.add("Geeks for Geeks");
cell.setBackgroundColor(Color.GREEN, 2);
table.add(cell);

Step 6: Add the table to document.

  • Add the table created to the document using document.add(Table table).
  • Close the document using document.close().

The following code adds the table to the PDF Document.

document.add(table);
document.close();

The following code snippet illustrates how tables with a varied background in a technical scenario.

Java




// Java program to set the background of a PDF table
  
// Importing the necessary classes
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
  
// Personal Info Class
class PersonalInfo {
  
    // Name of each person
    String name;
  
    // Age of each person
    int age;
  
    // Country of origin of each person
    String origin;
  
    // Initializing the PersonalInfo object
    PersonalInfo(String name, int age, String origin)
    {
        this.name = name;
        this.age = age;
        this.origin = origin;
    }
}
  
public class TableBackground {
  
    public static void main(String[] args)
    {
  
        // Try catch block to catch file Exceptions
        try {
  
            // Path of the PDF file
            String path = "F:/Table.pdf";
  
            // Creating a PDF writer object
            PdfWriter writer = new PdfWriter(path);
  
            // Creating a PDF Document object
            PdfDocument pdf = new PdfDocument(writer);
  
            // Creating a Document object
            Document doc = new Document(pdf);
  
            // Creating an empty table with three columns
            Table table = new Table(3);
  
            // Initializing three cells which make the first
            // row of the table
            Cell c1 = new Cell();
            Cell c2 = new Cell();
            Cell c3 = new Cell();
  
            // Adding text to the cells
            c1.add("Name");
            c2.add("Age");
            c3.add("Origin");
  
            // Setting the background color of each cell
            c1.setBackgroundColor(Color.GREEN);
            c2.setBackgroundColor(Color.GREEN);
            c3.setBackgroundColor(Color.GREEN);
  
            // Aligning the text to the center of each cell
            c1.setTextAlignment(TextAlignment.CENTER);
            c2.setTextAlignment(TextAlignment.CENTER);
            c3.setTextAlignment(TextAlignment.CENTER);
  
            // Adding the cells to the table
            table.addCell(c1);
            table.addCell(c2);
            table.addCell(c3);
  
            // Initializing an array of personal info
            PersonalInfo[] personalInfo
                = new PersonalInfo[3];
  
            // Adding data to the personal info array
            personalInfo[0]
                = new PersonalInfo("Yuri", 37, "Russian");
            personalInfo[1]
                = new PersonalInfo("Diksha", 18, "Indian");
            personalInfo[2]
                = new PersonalInfo("Sergio", 34, "Italian");
  
            // For loop to iterate over each person
            for (PersonalInfo pi : personalInfo) {
  
                // Initializing three empty cells which
                // represent the name, gender and origin of
                // a person
  
                // Cell 1 represents name
                c1 = new Cell();
  
                // Cell 2 represents age
                c2 = new Cell();
  
                // Cell 3 represents origin
                c3 = new Cell();
  
                // Checking whether the person is Indian
                if (pi.origin.equals("Indian")) {
  
                    // Setting the color of the cells to the
                    // colors of the Indian flag
                    c1.setBackgroundColor(Color.ORANGE, 10);
                    c2.setBackgroundColor(Color.WHITE);
                    c3.setBackgroundColor(Color.GREEN);
                }
  
                // Checking whether the person is Russian
                else if (pi.origin.equals("Russian")) {
  
                    // Setting the color of the cells to the
                    // colors of the Russian flag
                    c1.setBackgroundColor(Color.WHITE);
                    c2.setBackgroundColor(Color.BLUE);
                    c3.setBackgroundColor(Color.RED);
                }
  
                // Checking whether the person is Italian
                else if (pi.origin.equals("Italian")) {
  
                    // Setting the color of the cells to the
                    // colors of the Italian flag
                    c1.setBackgroundColor(Color.GREEN);
                    c2.setBackgroundColor(Color.WHITE);
                    c3.setBackgroundColor(Color.RED);
                }
  
                // Adding the person's details to their
                // respective cells
                c1.add(pi.name);
                c2.add(pi.age + "");
                c3.add(pi.origin);
  
                // Aligning the text to the center of each
                // cell
                c1.setTextAlignment(TextAlignment.CENTER);
                c2.setTextAlignment(TextAlignment.CENTER);
                c3.setTextAlignment(TextAlignment.CENTER);
  
                // Adding the cells to the table
                table.addCell(c1);
                table.addCell(c2);
                table.addCell(c3);
            }
  
            // Adding the table to the document
            doc.add(table);
  
            // Closing the document
            doc.close();
  
            System.out.println("Table Created");
        }
        // Catching any unwanted exceptions
        catch (Exception e) {
            System.err.println(e);
        }
    }
}


Output: A Table of the following format is created

set background to a table



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads