【问题标题】:Table Generation using Itext in given format使用给定格式的 Itext 生成表
【发布时间】:2017-06-22 15:39:22
【问题描述】:

我想使用 itext 生成这样的表格:

其中第一列有数字,如 1,2,3..... 第二列有属性名称,如--name,roll no 等......最后一列有与每个属性对应的实际数据。

【问题讨论】:

标签: java itext


【解决方案1】:

由于您是 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 对象来创建一个名为documentDocument 实例。这是一个高级文档,我们可以在其中添加各种构建块,例如ParagraphImageList 和其他高级对象。

在您的情况下,我们要添加一个表,因此我们创建一个 Table 实例。我们传递一个包含三个元素的float 数组,因为我们需要三列。第一列的宽度是第二列和第三列宽度的 1/4。我们希望表格占据页面上可用宽度的 50%。

现在我们要添加单元格。您可以添加三种类型的单元格:

  • 标题单元格:使用addHeaderCell() 方法,
  • 体细胞:使用addCell() 方法,以及
  • 页脚单元格:使用addFooterCell() 方法。

如果表格不适合页面,它将分布在不同的页面中,并且页眉和页脚单元格将重复。

传递给这些方法之一的参数是Cell。我们可以更改每个单元格的对齐方式、边框等。有关可用属性的更多信息,请阅读tutorialAPI documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 2011-06-24
    相关资源
    最近更新 更多