Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

java - Add image to acrofield in iText?

I'm trying to fill PDF using acrofields, I'm able to add string data perfectly, but having issues in adding images to acrofields. This is my code for adding string data..

    File f = new File("F:/Test/Agreement.pdf");
    InputStream sourceTemplatePDFUrlStream = new BufferedInputStream(new FileInputStream(f));
    File destinationFile = new File("F:/Test/ag1.pdf");

    PdfReader reader = new PdfReader(sourceTemplatePDFUrlStream);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
            destinationFile));

    AcroFields form = stamper.getAcroFields();
    Image img = Image.getInstance("E:/signature/signature.png");
    Set fields = form.getFields().keySet();

    Hashtable val = new Hashtable();
    val.put("name", "xxx" );
    val.put("city_street_zip", "xxx"+"                    "+"xxx"+"                "+"xxx");
    val.put("chck_1", "Yes" );
    val.put("chck_2", "No");
    val.put("chck_3", "Yes" );
    val.put("street_address", "xxx" );
    val.put("account_num", "1234");



    Enumeration enumeration = val.keys();

    // iterate through Hashtable val keys Enumeration
    while (enumeration.hasMoreElements()) {
        String nextElement = (String) enumeration.nextElement();
        String nextElementValue = (String) val.get(nextElement);
        //System.out.println(nextElement + ":=================fillData===================:" + nextElementValue);
        form.setField(nextElement, nextElementValue);
    }

    //Form flattening makes the form non-editable and saveable with the 
    //form val filled in
    stamper.setFormFlattening(true);

    stamper.close();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...