在PDF文件上动态添加图像到iText [英] Add image to iText dynamically on PDF file

查看:430
本文介绍了在PDF文件上动态添加图像到iText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我,我的代码中缺少什么,我正在尝试将图像添加到PDF生成

Can some one please help me what is missing in my code, I am trying to add image in to PDF generation

    fillFieldValue(stamper.getAcroFields(),agntCertBean);
    Image image1 = Image.getInstance(bb);
    image1.scaleAbsolute(25f, 25f);
    PdfContentByte overContent = stamper.getOverContent(1);
    AcroFields form = stamper.getAcroFields();       
    AcroFields.FieldPosition fldPos = (AcroFields.FieldPosition)     
    form.getFieldPositions("ProfilePciture");
    overContent.addImage(image1);
    stamper.close();                                 
    reader.close();


推荐答案

看着你的代码而不需要付出太多的参与,我看到两个主要错误:

Looking at your code without paying too much attending, I see two major mistakes:

[1.]这一行有问题:

[1.] There's something wrong with this line:

AcroFields.FieldPosition fldPos = (AcroFields.FieldPosition)form.getFieldPositions("ProfilePciture");

getFieldPositions()方法返回列出 FieldPosition 元素,您将该列表转换为 FieldPosition 对象。这不起作用,你需要这样的东西:

The getFieldPositions() method returns a List of FieldPosition elements and you're casting that list to a FieldPosition object. That won't work, you need something like this:

AcroFields.FieldPosition fldPos = form.getFieldPositions("ProfilePicture").get(0);

[2。]你得到图片字段的位置,但是你没有做任何事情它!你没有设置图像的位置!

[2.] You get the position of the picture field, but you're not doing anything with it! You're not setting the position of the image!

删除这两行:

image1.scaleAbsolute(25f, 25f);
PdfContentByte overContent = stamper.getOverContent(1);

获得字段位置后添加以下行:

Add these lines after you've obtained the field position:

Rectangle rect = fldPos.position;
image1.scaleToFit(rect.getWidth(), rect.getHeight());
image1.setAbsolutePosition(rect.getLeft(), rect.getBottom());
PdfContentByte overContent = stamper.getOverContent(fldPos.page);

在这些行中,您可以缩放图像以使其适合字段并设置图像的坐标。您还可以获得正确页面的 PdfContentByte 实例,而不是第一页。

In these lines you scale the image so that it fits the field and you set the coordinates of the image. You also get the PdfContentByte instance for the correct page instead of from the first page.

您可能还有其他错误,但请先解决这些问题!

You may have other errors, but please fix these first!

这篇关于在PDF文件上动态添加图像到iText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆