You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 20:46:08