📜  使用Java为 PDF 中的表格设置背景

📅  最后修改于: 2022-05-13 01:54:59.334000             🧑  作者: Mango

使用Java为 PDF 中的表格设置背景

您有没有想过如何将 PDF 表格中的不同单元格设置为各种颜色?好吧,在本文中,我们将看到如何使用您喜欢的语言Java中的iText库设置 PDF 表格中各种单元格的背景。

下载 iText

创建一个新的Java Maven 项目并在 pom.xml 文件中添加以下依赖项。此步骤将所有必需的 jar 文件添加到 Maven 依赖项中。

XML
       
               
         com.itextpdf         
         kernel         
         7.0.2     
        
        
               
         com.itextpdf         
         io         
         7.0.2     
        
        
               
         com.itextpdf         
         layout         
         7.0.2
        
        
               
         com.itextpdf         
         forms         
         7.0.2    
        
        
               
         com.itextpdf         
         pdfa         
         7.0.2     
        
        
               
         com.itextpdf         
         sign         
         7.0.2     
        
        
               
         com.itextpdf         
         barcodes         
         7.0.2     
        
        
               
         com.itextpdf         
         font-asian         
         7.0.2     
        
        
               
         com.itextpdf         
         hyph         
         7.0.2    
       
   


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);
        }
    }
}


将背景设置为 PDF 表格

第 1 步:创建一个空的 PDF 文件。

  • 将空 PDF 的路径分配给 String 变量。
  • 从包com.itextpdf.kernel.pdf 中导入PdfWriter 。 (PdfWriter 允许我们在 PDF 文件上写入内容)
  • PdfWriter 接受一个 String 变量,因为它是一个表示 PDF 目标的参数。
  • 通过传递 PDF 文件的路径来初始化 PdfWriter 对象。

以下代码创建一个空的 PDF。

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

第 2 步:创建一个代表空 PDF 文件的 PDF 文档。

  • 从包 com.itextpdf.kernel.pdf 导入PdfDocument (PdfDocument 用于表示代码中的pdf。此后可用于添加或修改各种功能,例如字体、图像、表格等)
  • PdfDocument 接受 PdfWriter 或 PdfReader 对象作为它的参数。
  • 通过传递 PdfWriter 对象来初始化 PdfDocument。

以下代码创建一个 PdfDocument,它代表空的 PDF 文件。

PdfDocument pdfDoc = new PdfDocument(pdfWriter);

第 3 步:创建文档。

  • 从包com.itextpdf.layout导入文档
  • 创建一个 Document 对象来制作 PDF 的可读版本。
  • Document 类的构造函数之一接受 PdfDocument 对象作为它的参数。
  • 通过传递 PdfDocument 对象来初始化文档。

以下代码创建一个文档。

Document doc = new Document(pdfDoc);

第 4 步:创建一个表。

  • 从包com.itextpdf.layout.element导入
  • 表格由单元格创建,每个单元格占据一个单元行和列。
  • 表构造函数接受列数作为参数。
  • 通过传递列数作为参数来初始化表对象。

以下代码创建一个表。

Table table = new Table(3);

第 5 步:使用 setBackgroundColor(Color.color, float opacity) 将单元格添加到具有偏好背景的表格中。

  • 包 e com.itextpdf.layout.element 中导入Cell
  • 从包com.itextpdf.kernel.color导入颜色
  • 初始化要添加到表格中的单元格数。
  • 使用add(String text)向单元格添加文本。
  • 使用 setBackgroundColor(Color.color, float opacity) 设置单元格的背景颜色。
  • 将单元格添加到表格中。

以下代码创建单元格并将其添加到表中。

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

第 6 步:将表格添加到文档中。

  • 使用document.add(Table table) 将创建的表格添加到文档中。
  • 使用document.close() 关闭文档。

以下代码将表格添加到 PDF 文档。

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

以下代码片段说明了在技术场景中具有不同背景的表。

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);
        }
    }
}

输出:创建了以下格式的表

将背景设置为表格