简体   繁体   中英

How to convert Byte Array to image using itextPdf and display in pdf

How to convert byte array to image in itext pdf and display in pdf. This is what i am doing but i am getting nullpointer exception..

    Base64 decoder = new Base64();
    byte[] imageByte = decoder.decode(imageInBase64EncodedString);
        Image image = null;
        try {
            image = Image.getInstance(imageByte);
        } catch (BadElementException e1) {
            e1.printStackTrace();
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            image.scalePercent(15f);  <-----Here i am getting NullPointer Exception
            image.scaleAbsoluteWidth(520f);
            image.setAbsolutePosition(40f,725f);
            document.add(image);
       }catch(Exception e){
            e.printStackTrace();
       }

I am not understanding why image is not created even i pass them bytes.

The problem is most likely the String value you're passing in, as it's very likely you're running into an exception for bad formatting in the value.

I've tried your example, using a BASE64 String example from PasteBin ( http://pastebin.com/bfc1E1NV ) that someone was kind enough to post, and was successful in running the scripts as per your code provided.

ItextPdf Example

Screenshot 1 在此处输入图片说明

Screenshot 2 (image Object is not null) 在此处输入图片说明

org.apache.commons.codec.binary.Base64Example 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM