繁体   English   中英

iText 7-表格单元格中的图像填充完整高度

[英]iText 7 - Image in Cell of Table fill full height

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

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

我的图像如何适应细胞的整个高度?

这是我的问题: 在此处输入图片说明

这是创建表的代码:

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()当前在develop分支上的iText7中存在错误(因此,该错误将出现在7.0.5和更低版本中)。 当前,它将设置AUTO_SCALE_WIDTH (可能是由于复制粘贴的疏忽),除非已经设置了AUTO_SCALE_WIDTH属性,否则它将把它们都设置为false并将AUTO_SCALE设置为true。

  • 修正错字不会导致预期的行为,因为我们现在已经知道了该问题,因此已将其工单添加到了待办事项中。

  • 双向自动缩放(通过AUTO_SCALE -property)可以正常工作,但是会均匀缩放,因此仅在单元格的高度大于宽度的情况下才缩放到宽度。

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

我用相对高度声明(应该包含在7.0.5中)进行了快速测试,但是又再次均匀缩放了图像。 有些试验和错误以及Image.scaleAbsolute()可以得到所需的结果,但这几乎无法自动化。 从理论上讲,您可以编写自己的自定义CellRenderer,提取要排成行的最大Cell的高度,以便与scaleAbsolute()结合使用,从而挂入布局过程,但是您实际上是在自己编写自动缩放逻辑点。

为了传播良好实践,还对OP的已发布代码进行了一些说明:

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

不建议使用构造函数Table(int)(从7.0.2版开始),并且可能导致更高版本出现意外行为(在改进表布局机制时已完成此操作)。 最好传递一个UnitValue[] ,最好使用UnitValue.createPercentArray(float[])UnitValue.createPercentArray(float[])

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

setAutoScale之后的setAutoScaleHeight使后者多余。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM