如何在iText 9的Paragraph中垂直对齐文本与图片元素?
在iText 9中实现Paragraph内元素的垂直对齐
你遇到的问题是Paragraph.setVerticalAlignment(VerticalAlignment.MIDDLE)未生效,这是因为该方法控制的是整个段落相对于其父容器的垂直位置,而非段落内部行内元素(图片、文本)之间的对齐。要让图片和文本垂直居中对齐,需要单独设置每个元素的垂直对齐属性。
解决方案代码示例
val icon = Image(ImageDataFactory.create(XXX::class.java.getResource("/pdf/xxx.png"))) .scaleToFit(30f, 30f) .setBorder(DashedBorder(1f)) .setVerticalAlignment(VerticalAlignment.MIDDLE) // 给图片设置垂直居中对齐 val text = Text(" %d best practices ") .setBorder(SolidBorder(Color.createColorWithColorSpace(floatArrayOf(1f, 0f, 0f)), 1f)) .setVerticalAlignment(VerticalAlignment.MIDDLE) // 给文本设置垂直居中对齐 bestPractice.add( Paragraph() .add(icon) .add(text) .setBorder(SolidBorder(1f)) )
补充优化方案
如果需要更精准的对齐效果(比如对齐到示意图中的绿色线),可以用InlineBlock包裹图片,通过块级元素的对齐规则实现更稳定的效果:
val iconBlock = InlineBlock() .add(icon) .setVerticalAlignment(VerticalAlignment.MIDDLE) val text = Text(" %d best practices ") .setBorder(SolidBorder(Color.createColorWithColorSpace(floatArrayOf(1f, 0f, 0f)), 1f)) .setVerticalAlignment(VerticalAlignment.MIDDLE) bestPractice.add( Paragraph() .add(iconBlock) .add(text) .setBorder(SolidBorder(1f)) )
预期对齐效果:
内容的提问来源于stack exchange,提问作者poussma
相关产品推荐
相关产品推荐

