表格单元格中的列表项目未格式化

Dan*_*lor 0 java itext tabular

我有使用iText(版本5.5.2)生成的PDF问题.我有一个表应该包含各种元素,包括列表.

但是,单元格内的列表被错误地显示 - 它根本不作为列表呈现,而是列表项目一个接一个地显示.

所以与其

  1. ITEM1
  2. ITEM2
  3. 项目3

我有

item1item2item3

我正在使用以下代码:

private static Paragraph list(String... items) {
    Paragraph para = new Paragraph();
    com.itextpdf.text.List list = new com.itextpdf.text.List(true, 10);
    for (String item : items) {
        list.add(new ListItem(item));
    }
    para.add(list);
    return para;
}

    document.add(list("item1","item2","item3));
    PdfPTable table = new PdfPTable(2);
    table.addCell("Some list");
    table.addCell(list("item1","item2","item3));
    document.add(table);
Run Code Online (Sandbox Code Playgroud)

添加到表中的元素与添加到文档中的元素相同.区别在于,第一个正确显示为列表,第二个没有列表格式.

我在这里做错了什么?

Bru*_*gie 6

要添加ListPdfPTable文本模式.那永远不会奏效.您应该添加List复合模式.在以下问题的答案中解释了文本模式复合模式之间的区别:

如果您想找到解释这两个概念之间差异的更多有用答案,请下载免费电子书StackOverflow上的最佳iText问题(我找到了上述问题的链接).

我还搜索了官方iText网站上沙盒示例,这就是我发现ListInCell示例显示了向列表添加列表的许多不同方法的方法PdfPCell:

// We create a list:
List list = new List();                
list.add(new ListItem("Item 1"));
list.add(new ListItem("Item 2"));
list.add(new ListItem("Item 3"));

// We wrap this list in a phrase:     
Phrase phrase = new Phrase();
phrase.add(list);
// We add this phrase to a cell
PdfPCell phraseCell = new PdfPCell();
phraseCell.addElement(phrase);           

// We add the cell to a table:
PdfPTable phraseTable = new PdfPTable(2);
phraseTable.setSpacingBefore(5);
phraseTable.addCell("List wrapped in a phrase:");
phraseTable.addCell(phraseCell);

// We wrap the phrase table in another table:
Phrase phraseTableWrapper = new Phrase();
phraseTableWrapper.add(phraseTable);

// We add these nested tables to the document:
document.add(new Paragraph("A list, wrapped in a phrase, wrapped in a cell, wrapped in a table, wrapped in a phrase:"));
document.add(phraseTableWrapper);

// This is how to do it:

// We add the list directly to a cell:
PdfPCell cell = new PdfPCell();
cell.addElement(list);
// We add the cell to the table:
PdfPTable table = new PdfPTable(2);
table.setSpacingBefore(5);
table.addCell("List placed directly into cell");
table.addCell(cell);
Run Code Online (Sandbox Code Playgroud)

生成的PDF(list_in_cell.pdf)看起来就像我期望的那样.

但是,有两点需要注意:

  • 该示例提到"此示例由Bruno Lowagie为潜在客户编写.此示例中的代码与最新版本的iText一起使用.它不适用于早于iText 5的版本",我不知道它是否可行使用iText 5.5.2.
  • 我知道表中不支持嵌套列表.因此,如果您需要单元格内的列表中的列表,您将获得看起来不像您想要的结果.

  • 好吧我的问题是,我认为table.addCell(Element)与创建单元格相同,向单元格添加元素并将单元格添加到表格.... (2认同)