【发布时间】:2017-06-22 15:39:22
【问题描述】:
【问题讨论】:
-
@RyanTheLeach 好的,但那是 iText 5。由于 OP 是 iText 的新手,为什么不使用最新版本的 iText 7?使用 iText 7 创建 PDF 的代码与 iText 5 代码非常不同。
【问题讨论】:
由于您是 iText 的新手,因此您应该使用最新版本的 iText。那是 iText 7.0.3:https://github.com/itext/itext7/releases
该表是使用以下代码创建的:
public static void main(String[] args) throws IOException {
PdfDocument pdf = new PdfDocument(new PdfWriter("table.pdf"));
Document document = new Document(pdf);
Table table = new Table(new float[]{1, 4, 4});
table.setWidthPercent(50);
table
.addHeaderCell(
new Cell().add("A")
.setTextAlignment(TextAlignment.CENTER))
.addHeaderCell(
new Cell().add("B")
.setTextAlignment(TextAlignment.CENTER))
.addHeaderCell(
new Cell().add("C")
.setTextAlignment(TextAlignment.CENTER));
for (int i = 1; i < 11; i++) {
table
.addCell(
new Cell().add(String.format("%s.", i))
.setTextAlignment(TextAlignment.RIGHT)
.setBorderTop(Border.NO_BORDER)
.setBorderBottom(Border.NO_BORDER))
.addCell(
new Cell().add(String.format("key %s", i))
.setBorderTop(Border.NO_BORDER)
.setBorderBottom(Border.NO_BORDER))
.addCell(
new Cell().add(String.format("value %s", i))
.setBorderTop(Border.NO_BORDER)
.setBorderBottom(Border.NO_BORDER));
}
table
.addFooterCell(
new Cell().add("A")
.setTextAlignment(TextAlignment.CENTER))
.addFooterCell(
new Cell().add("B")
.setTextAlignment(TextAlignment.CENTER))
.addFooterCell(
new Cell().add("C")
.setTextAlignment(TextAlignment.CENTER));
document.add(table);
document.close();
}
pdf 对象是将 PDF 语法写入PdfWriter 的低级 PDF 文档。我们使用pdf 对象来创建一个名为document 的Document 实例。这是一个高级文档,我们可以在其中添加各种构建块,例如Paragraph、Image、List 和其他高级对象。
在您的情况下,我们要添加一个表,因此我们创建一个 Table 实例。我们传递一个包含三个元素的float 数组,因为我们需要三列。第一列的宽度是第二列和第三列宽度的 1/4。我们希望表格占据页面上可用宽度的 50%。
现在我们要添加单元格。您可以添加三种类型的单元格:
addHeaderCell() 方法,addCell() 方法,以及addFooterCell() 方法。如果表格不适合页面,它将分布在不同的页面中,并且页眉和页脚单元格将重复。
传递给这些方法之一的参数是Cell。我们可以更改每个单元格的对齐方式、边框等。有关可用属性的更多信息,请阅读tutorial 和API documentation。
【讨论】: