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

Itext7向PDF添加图片后显示不全的原因排查

问题排查与解决方案

核心问题原因分析

1. 图片字节读取不完整

你的main方法里用imgIs.available()获取图片长度再读取的方式存在缺陷。available()仅能返回当前输入流中可无阻塞读取的字节数,并非图片文件的总大小。如果图片体积较大或流读取存在缓冲延迟,会导致读取的字节数组不完整,图片数据损坏,最终显示不全。

2. PDF坐标系统理解偏差

iText7中PDF的坐标原点位于页面左下角,而非常规UI的左上角。如果直接设置imageAbsoluteY=500,相当于从页面左下角向上500的位置放置图片,若该位置加上图片高度超出页面总高度,图片的上部会被页面边界截断。

修复代码示例

修复图片读取逻辑

替换main方法中读取图片的代码,确保完整读取所有字节:

// 替换原图片读取代码
ByteArrayOutputStream imgBaos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int readLen;
while ((readLen = imgIs.read(buffer)) != -1) {
    imgBaos.write(buffer, 0, readLen);
}
byte[] imgBytes = imgBaos.toByteArray();

也可以用Apache Commons IO工具类简化实现:

byte[] imgBytes = IOUtils.toByteArray(imgIs);

修复坐标计算逻辑

在addImage方法中,先获取目标页面的实际尺寸,转换为符合PDF坐标系统的正确位置:

try(
        PdfWriter pdfWriter = new PdfWriter(os, writerProperties);
        PdfDocument pdf = new PdfDocument(new PdfReader(is), pdfWriter);
        Document document = new Document(pdf);
){
    int pageNum = pdf.getNumberOfPages();
    PdfPage targetPage = pdf.getPage(pageNum);
    Rectangle pageSize = targetPage.getPageSize();
    
    // 若原本需求是图片距离页面顶部500,转换为左下角为原点的坐标
    float correctY = pageSize.getTop() - imageAbsoluteY - imageHeightY;
    
    Image image = new Image(ImageDataFactory.create(signBytes))
            .scaleAbsolute(imageWidthX, imageHeightY)
            .setFixedPosition(pageNum, imageAbsoluteX, correctY);

    document.add(image);
}

额外注意点

  • 可通过pageSize.getWidth()和pageSize.getHeight()确认页面实际宽高,确保图片位置和尺寸不超出页面范围。
  • 如果目标页面存在自定义裁剪框(CropBox),需用page.getCropBox()替代getPageSize()来计算可显示区域。

内容的提问来源于stack exchange,提问作者Wade

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:05:14