Java如何在iText中创建嵌套表?
本示例向您展示如何在iText中创建嵌套表。要创建嵌套表,您可以com.itextpdf.text.pdf.PdfPTable使用com.itextpdf.text.pdf.PdfPCell的addElement()方法将对象添加到单元格中。
package org.nhooo.example.itextpdf; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class TableNestedDemo { public static void main(String[] args) { Document doc = new Document(); try { PdfWriter.getInstance(doc, new FileOutputStream("TableNestedDemo.pdf")); doc.open(); PdfPTable table = new PdfPTable(3); PdfPCell cell1 = new PdfPCell(new Phrase("Cell 1")); PdfPCell cell2 = new PdfPCell(new Phrase("Cell 2")); PdfPCell cell3 = new PdfPCell(new Phrase("Cell 3")); PdfPTable nestedTable = new PdfPTable(2); nestedTable.addCell(new PdfPCell(new Phrase("Nested 1"))); nestedTable.addCell(new PdfPCell(new Phrase("Nested 2"))); cell3.addElement(nestedTable); table.addCell(cell1); table.addCell(cell2); table.addCell(cell3); doc.add(table); } catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); } finally { doc.close(); } } }
Maven依赖
<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.10</version> </dependency>