2

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.

8
  • Did any of the printStackTrace calls above trigger? Commented Nov 16, 2016 at 11:52
  • 1
    Possible duplicate of What is a NullPointerException, and how do I fix it? Commented Nov 16, 2016 at 12:40
  • Ty for replying guys @mkl no. Commented Nov 16, 2016 at 13:17
  • @DanCornilescu Ty for commenting but i am not asking for nullpointer exception. I meant why image is null when i pass them byte array. Commented Nov 16, 2016 at 13:18
  • 1
    Please share the value of imageInBase64EncodedString; otherwise we can't answer your question. Commented Nov 17, 2016 at 13:17

1 Answer 1

6

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 enter image description here

Screenshot 2 (image Object is not null) enter image description here

org.apache.commons.codec.binary.Base64Example enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

You Using ItextPdf Image Class. I am using import org.apache.commons.codec.binary.Base64 for decoding and getting values in byte. But at image.scalePercent(15f) i am getting null...
I've modified the example to include the library you're using and my tests still passed. Can you provide me with the String value you're trying to pass in?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.