如何使用 Java 向 PDF 添加嵌套表格

问题描述

如何使用 Java 向 PDF 添加嵌套表格。

解决方案

以下是使用 Java 向 PDF 添加嵌套表格的程序。

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;  

public class AddNestedTablesPdf { 
   public static void main(String args[]) throws Exception { 
      String file = "C:/EXAMPLES/itextExamples/addingNestedTableToPDF.pdf"; 

        //创建 PdfDocument 对象
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));
        
        //创建 Document 对象
        Document doc = new Document(pdfDoc);
        
        //创建表格
        Table table = new Table(2);
        
        //向表格中添加单元格
        table.addCell(new Cell().add("Name"));
        table.addCell(new Cell().add("Raju"));
        table.addCell(new Cell().add("Id"));
        table.addCell(new Cell().add("1001"));
        table.addCell(new Cell().add("Designation"));
        table.addCell(new Cell().add("Programmer"));
        
        //为联系人创建表格
        Table contact = new Table(2);
        
        //在表格中添加表格
        contact.addCell(new Cell().add("Phone"));
        contact.addCell(new Cell().add("email"));
        contact.addCell(new Cell().add("Address"));
        contact.addCell(new Cell().add("9848022338"));
        contact.addCell(new Cell().add("Raju123@gmail.com"));
        contact.addCell(new Cell().add("Hyderabad"));
        
        //将表格添加到单元格
        table.addCell(new Cell().add("Contact"));
        table.addCell(new Cell().add(contact));
        
        //将表格添加到文档
        doc.add(table);
        
        //关闭文档
        doc.close();  
        System.out.println("Nested Table Added successfully..");
   } 
} 

输出

已添加嵌套表
java_itext.html