关于Java:从PdfPTable列(iText)获取绝对宽度

Get absolute width from PdfPTable column (iText)

当以表列的相对大小指定表列时,如何从iText获取列的绝对宽度?

我尝试了什么

我将3列的相对宽度指定为float,如下所示:

1
2
3
PdfPCell cell2;
PdfPTable table2 =  new PdfPTable(new float[]{(float) 4.5, (float) 0.5, 9});
table2.setWidthPercentage(100);

我得到了什么

我尝试使用table2.getAbsoluteWidths()[2],但结果是浮点型0.0

我所期望的

在PDF上已动态计算表格宽度之后,我想获得每一列的绝对宽度(已最大化)。

-----------------------编辑---------------------- <铅>

实际上,在添加文档之前,我需要一列的宽度,然后替换我的硬编码浮点变量限制。

当在函数restrictWidthOfFont

中进行拆分而获得最大宽度页面时,我有很多数据字符串并且要在另一列中设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
String fullAlamatPP ="test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test";

float restrictions = (float) 330.12103; // this is width of a column from table

String alamatSesuaiKtpPP[] = restrictWidthOfFont(fullAlamatPP, font_body, restrictions);

Phrase p_alamat1_ct = new Phrase(alamatSesuaiKtpPP[0], font_body);
p_alamat1_ct.add(dottedline);
cell2 = new PdfPCell(p_alamat1_ct);
cell2.setBorder(PdfPCell.NO_BORDER);
table2.addCell(cell2);

Phrase p_alamat2_ct = new Phrase(alamatSesuaiKtpPP[1], font_body);
p_alamat2_ct.add(dottedline);
cell2 = new PdfPCell(p_alamat2_ct);
cell2.setBorder(PdfPCell.NO_BORDER);
table2.addCell(cell2);    

private static String[] restrictWidthOfFont(String character, Font font, float restrictions) {
        String results[];
        results = new String[] {"",""};
        String concatChar ="";
        float widthOfString = 0;
        for (int i = 0; i < character.length();i++) {
            concatChar += character.charAt(i);
            widthOfString = font.getCalculatedBaseFont(true).getWidthPoint(concatChar, font.getCalculatedSize());
//                System.out.println("widthOfString" + widthOfString);
            if (widthOfString > restrictions) {
                results[0] = concatChar.substring(0, concatChar.length() - 1);
                results[1] = character.substring(i, character.length());
                break;
            }
        }

        if (results[0] =="") {
            results[0] = character;
        }
        return results;
}

在添加表格文档之前是否可能获得列的宽度?


问题与解释

函数table.getAbsoluteWidths()依赖于必须设置表的totalWidth的要求,因此table.getTotalWidth() > 0

这是因为在com.itextpdf.text.pdf.PdfPTable类中调用了方法calculateWidths(),该方法然后计算所有列的绝对宽度:

1
this.absoluteWidths[k] = this.totalWidth * this.relativeWidths[k] / total;

为了确保在检索relativeWidths数组之前已设置totalWidth,您需要:

  • (A)设置此答案中所述的totalWidth
  • 或(B)在表格中添加单元格