我已经在java中使用iText创建了表格。但我想为我的一个项目创建两个并行表。有人能告诉我使用iText创建两个并行表的解决方案吗?
答案 0 :(得分:4)
以下是代码段
package com.example;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
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.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class PdfTest {
private Document document;
public PdfTest() {
document = new Document();
}
public boolean openPdf() {
boolean status = false;
try {
File pdfFile = new File("test.pdf");
if (pdfFile != null) {
PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
document.open();
status = true;
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (DocumentException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return status;
}
public void closePdf() {
document.close();
}
public void generatePdf() throws DocumentException {
Paragraph paragraph = new Paragraph();
PdfPCell cell = null;
// Main table
PdfPTable mainTable = new PdfPTable(2);
mainTable.setWidthPercentage(100.0f);
// First table
PdfPCell firstTableCell = new PdfPCell();
firstTableCell.setBorder(PdfPCell.NO_BORDER);
PdfPTable firstTable = new PdfPTable(2);
firstTable.setWidthPercentage(50.0f);
cell = new PdfPCell(new Phrase("T1R1C1"));
firstTable.addCell(cell);
cell = new PdfPCell(new Phrase("T1R1C2"));
firstTable.addCell(cell);
cell = new PdfPCell(new Phrase("T1R2C1"));
firstTable.addCell(cell);
cell = new PdfPCell(new Phrase("T1R2C2"));
firstTable.addCell(cell);
firstTableCell.addElement(firstTable);
mainTable.addCell(firstTableCell);
// Second table
PdfPCell secondTableCell = new PdfPCell();
secondTableCell.setBorder(PdfPCell.NO_BORDER);
PdfPTable secondTable = new PdfPTable(2);
secondTable.setWidthPercentage(50.0f);
cell = new PdfPCell(new Phrase("T2R1C1"));
secondTable.addCell(cell);
cell = new PdfPCell(new Phrase("T2R1C2"));
secondTable.addCell(cell);
cell = new PdfPCell(new Phrase("T2R2C1"));
secondTable.addCell(cell);
cell = new PdfPCell(new Phrase("T2R2C2"));
secondTable.addCell(cell);
secondTableCell.addElement(secondTable);
mainTable.addCell(secondTableCell);
paragraph.add(mainTable);
document.add(paragraph);
}
}
用
测试PdfTest pdfTest = new PdfTest();
try {
if (pdfTest.openPdf()) {
pdfTest.generatePdf();
pdfTest.closePdf();
}
} catch (Exception ex) {
ex.printStackTrace();
}
希望这有帮助。
答案 1 :(得分:3)
请查看column_table.pdf文档。从第3页开始,您将看到页面的布局有两列彼此相邻。这是通过使用ColumnText
类来实现的。有关源代码的信息,请参阅ColumnTable或访问ColumnText
的关键字页面查看其他代码示例。