Add image to acrofield in iText?

情到浓时终转凉″ 提交于 2019-11-28 08:37:38

The "official" way to do this, is to have a Button field as placeholder for the image, and to replace the "icon" of the button as described in my book:

PushbuttonField ad = form.getNewPushbuttonFromField(imageFieldName);
ad.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
ad.setProportionalIcon(true);
ad.setImage(Image.getInstance("E:/signature/signature.png"));
form.replacePushbuttonField("advertisement", ad.getField());

See ReplaceIcon.java for the full code sample.

DISCLAIMER: I'm the original developer of iText and the author of the "iText in Action" books.

The following solution worked:

public static void addImage(PdfStamper stamper,AcroFields form,String field,String fieldValue){
    try{
        System.out.println("Field "+field);
    java.util.List<AcroFields.FieldPosition> photograph = form.getFieldPositions(field);
    if(photograph!=null && photograph.size()>0){
    Rectangle rect= photograph.get(0).position;
    //if(StringUtils.isNotBlank(fieldValue)){
    Image img = Image.getInstance(fieldValue);
    img.scaleToFit(rect.getWidth(), rect.getHeight());
    img.setBorder(2);
    img.setAbsolutePosition(
    photograph.get(0).position.getLeft() + (rect.getWidth() - img.getScaledWidth() )
    , photograph.get(0).position.getTop() - (rect.getHeight()));
    PdfContentByte cb = stamper.getOverContent((int)photograph.get(0).page);
    cb.addImage(img);
    //}
    }
    }catch(Exception e){
        e.printStackTrace();
    }
    }

calling the above method:

addImage(stamper, form, "CustomerSign", "E:/signature/signature.png");

where CustomerSign is AcroField

You can try add this with your code for adding Image

PdfContentByte content = stamper.getOverContent(reader.getNumberOfPages());
Image image = Image.getInstance(new URL("E:/signature/signature.png"));
image.setAbsolutePosition(450,650);
image.scaleAbsolute(200,200);
content.addImage(image);
reader.close();
return output.toByteArray();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!