iText 7 - Table 单元格中的图像填充全高

iText 7 - Image in Cell of Table fill full height

我在 table 的单元格中添加了图像,但它不适合整个高度。

高度不固定,可以在两行之间变化。

我的图像如何适合我的单元格的整个高度?

这是我的问题:

这是我的 table 的创建代码:

int nbColumns = 7 + planning.size() *4;
Table table = new Table(nbColumns);
table.setWidthPercent(100);
table.addCell(createCell(""));
table.addCell(createCell("Col1"));
table.addCell(createCell("Col2"));
DateFormat hourFormat = new SimpleDateFormat("HH", Locale.FRENCH);
for(Date hourDate : planning){
    table.addCell(new Cell(1,4).setTextAlignment(TextAlignment.CENTER).add(hourFormat.format(hourDate)).setFont(regular).setFontSize(10));
}

table.addCell(createCell("Long"));
table.addCell(createCell("A"));
table.addCell(createCell("B"));
table.addCell(createCell(""));

以下是我为每个单元格添加图像的方法:

String IMG = // my img path
table.addCell(createImageCell(IMG));

public static Cell createImageCell(String path) throws MalformedURLException {
            Image img = new Image(ImageDataFactory.create(path));
            Cell cell = new Cell().add(img.setMargins(0,0,0,0).setAutoScaleHeight(true).setAutoScale(true)).setPadding(0);
            cell.setBorder(null);
            return cell;
        }

为了可见性,将此作为答案发布。

关于自动缩放:

  • setAutoScaleHeight() 目前在开发分支的 iText7 中存在漏洞(因此该漏洞将出现在 7.0.5 和之前的版本中)。它当前设置 AUTO_SCALE_WIDTH(可能是由于复制粘贴的疏忽),除非 AUTO_SCALE_WIDTH属性 已经设置,否则它将把它们都设置为 false 并设置 AUTO_SCALE 为真。

  • 修复拼写错误不会导致预期的行为,因为我们现在已经意识到这个问题,所以它的票已添加到我们的待办事项列表中。

  • 双向自动缩放(通过 AUTO_SCALE-属性)工作正常,但会统一缩放,因此仅在单元格较大的情况下缩放到宽度高度大于宽度。

至于绕过它的临时解决方案或技巧,我没有通用的 :( 目前,除了等待修复。

我用相对高度声明(应该包含在 7.0.5 中)做了一个快速测试,但再次统一缩放了图像。一些试错和 Image.scaleAbsolute() 可以得到想要的结果,但这很难自动化。从理论上讲,您可以通过编写自己的自定义 CellRenderer 来挂钩布局过程,将最大单元格的高度提取到行中以与 scaleAbsolute() 结合使用,但您有点像自己编写自动缩放逻辑那时。

为了传播良好实践,对 OP 发布的代码也有一些评论:

int nbColumns = 7 + planning.size() *4;
Table table = new Table(nbColumns);

构造函数 Table(int) 已弃用(自 7.0.2 起)并且可能导致更高版本中的意外行为(这是在改进 table 布局机制时完成的)。最好传递一个 UnitValue[],最好使用 UnitValue.createPercentArray(float[])UnitValue.createPercentArray(float[])

创建
img.setMargins(0,0,0,0).setAutoScaleHeight(true).setAutoScale(true))

setAutoScalesetAutoScaleHeight 之后使后者多余。