java - iText 中的 setRowspan 不起作用

标签 java itext html-table

我正在使用 iText 5.4.4 生成 pdf。我创建了一个表,第一行(即标题)的列跨度为 4 列。之后,我尝试使用 cell.setRowspan(2) 使标题跨 2 行,但这似乎不起作用。

这是我的代码片段:

PdfPCell cell;
cell = new PdfPCell(new Paragraph("Parent Details",font));
cell.setColspan(4);
cell.setRowspan(2);
cell.setHorizontalAlignment(Phrase.ALIGN_CENTER);
cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(cell);

iText in Action一书中,作者说道:“PdfPTable/PdfPCell 中没有 setRowspan() 方法。”如果这样的方法不存在,NetBeans 为什么不会抛出错误?另外,如何使标题跨两行?除了使用嵌套表之外还有其他解决方法吗?

最佳答案

不幸的是,您没有提供足够的代码来重现该问题。因此,我只能给出一个示例来证明行跨度工作正常:

Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("span-in-table.pdf"));
document.open();

PdfPTable table = new PdfPTable(3);

table.addCell("A");
PdfPCell cell = new PdfPCell(new Phrase("B"));
cell.setColspan(2);
cell.setRowspan(2);
table.addCell(cell);
table.addCell("C");
table.addCell("D");
table.addCell("E");
table.addCell("F");

document.add(table);
document.close();

此示例生成此表:

Result table with column span and row span on the right side

看起来和预期的差不多。

或者,如果您更喜欢左侧的 2x2 单元格:

...
PdfPTable table = new PdfPTable(3);

PdfPCell cell = new PdfPCell(new Phrase("A"));
cell.setColspan(2);
cell.setRowspan(2);
table.addCell(cell);
table.addCell("B");
table.addCell("C");
table.addCell("D");
table.addCell("E");
table.addCell("F");

document.add(table);
...

结果

Result table with column span and row span on the left side

In iText in Action book the author says - "There is no method setRowspan() in PdfPTable/PdfPCell." How come NetBeans is not throwing error if such a method does not exists?

嗯,这是 iText in Action 的第一版。在第二版中,您可以阅读:

There was a time when rowspan wasn't supported for PdfPCells. The only way to work around this was to use nested tables.

(page 109 in iText in Action — Second Edition)

您可以在第 4 章中找到示例在表格中组织内容 here .

关于java - iText 中的 setRowspan 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19676637/

相关文章:

java - iText 阅读多列 PDF 文档

maven - 来自 itext 的 jasper-reports 中的依赖错误

jquery - 使用 CSS 或 jQuery 的垂直样式表

HTML 表格行背景颜色与 float 属性不符合预期

java - 将 Java 虚拟机与 System.nanoTime 同步

java - 如何解决android.database.sqlite.SQLiteException : no such column: ttd (code 1)

java - Selenium Chrome 屏幕截图 - html2canvas

java - 如何使用 Spring Boot 构建两个重新打包的 jar

java - 使用 IPdfWriterConfiguration 加密 pdf xDocReport (iText) 不起作用

javascript - 制表符:删除行时如何修改本地数组?