iText:具有不同 cell/column 宽度的不同 table 行

iText: Different table rows with different cell/column widths

如何使用 Java 创建一个 table 三行如下:

iText 中的代码会是什么样子?

所以您想使用 iText 创建如下所示的 table:

屏幕截图中的 PDF 是使用 TableMeasurements example. The resulting PDF can also be downloaded for inspection: table_measurements.pdf

创建的

看到这个屏幕截图时,首先映入眼帘的是 table 看起来不像 "complete"。这意味着我们将不得不按照我昨天在 SO 上已经解释过的方式(以及之前的很多次)完成 table: (which was actually a duplicate of How to generate pdf if our column less than the declared table column and ItextSharp, number of Cells not dividable by the length of the row and Odd Numbered Cell Not Added To Pdf and PdfTable: last cell is not visible 和 ...)

评论区有人问我:

How can I complete row with cells with no border?

我回答:

Use table.getDefaultCell().setBorder(Rectangle.NO_BORDER);

请注意,PdfPCell.NO_BORDER 也可以作为 PdfPCell 扩展 Rectangle class。

在你的情况下,我们会有这样的事情:

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    PdfPTable table = new PdfPTable(10);
    table.setTotalWidth(Utilities.millimetersToPoints(100));
    table.setLockedWidth(true);
    table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
    table.addCell(getCell(10));
    table.addCell(getCell(5));
    table.addCell(getCell(3));
    table.addCell(getCell(2));
    table.addCell(getCell(3));
    table.addCell(getCell(5));
    table.addCell(getCell(1));
    table.completeRow();
    document.add(table);
    document.close();
}

为了使示例更逼真,我创建了一个 table,宽度精确为 100 毫米。对于要确认的宽度,我锁定了宽度。如前所述,我确保默认单元格没有边框。添加所有具有不同宽度(10 厘米、5 厘米、3 厘米、2 厘米、3 厘米、5 厘米、1 厘米)的单元格后,我完成了该行。

getCell() 方法是什么样的,您可能想知道。 Amedee 在评论中已经回答了这个问题(出于某种原因你忽略了):

private PdfPCell getCell(int cm) {
    PdfPCell cell = new PdfPCell();
    cell.setColspan(cm);
    cell.setUseAscender(true);
    cell.setUseDescender(true);
    Paragraph p = new Paragraph(
            String.format("%smm", 10 * cm),
            new Font(Font.FontFamily.HELVETICA, 8));
    p.setAlignment(Element.ALIGN_CENTER);
    cell.addElement(p);
    return cell;
}

我们创建一个 PdfPCell 并设置 colspan 以反映以厘米为单位的宽度。我添加了一些更花哨的东西。我没有在这个例子中使用官方网站或 Whosebug 上没有解释的任何功能。

更多 rowspan 和 colspan 示例,请查看 Colspan and rowspan section in the official documentation