0

I am trying to add an image in my iText PDF document in Android Studio, with Java, but it always shows the error NullPointerException.

The codes i've trying are:

1.

try { InputStream inputStream = context.getAssets().open("res/drawable/logo.png"); Bitmap bitmapA = BitmapFactory.decodeStream(inputStream); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmapA.compress(Bitmap.CompressFormat.PNG, 100, stream); Image image = Image.getInstance(stream.toByteArray()); return image; }catch (Exception e){ e.printStackTrace(); } 

2.

try { Drawable d = context.getResources().getDrawable(R.drawable.logo); BitmapDrawable bitDw = ((BitmapDrawable) d); Bitmap bmp = bitDw.getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); Image image = Image.getInstance(stream.toByteArray()); return image; }catch (Exception e){ e.printStackTrace(); } 

3.

try { Drawable d = context.getDrawable(R.drawable.logo); BitmapDrawable bitDw = ((BitmapDrawable) d); Bitmap bmp = bitDw.getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); Image image = Image.getInstance(stream.toByteArray()); return image; }catch (Exception e){ e.printStackTrace(); } 

4.

try { Image image = Image.getInstance("res/drawable/logo.png"); return image; } catch (BadElementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 

..and no one of those codes are working. Always the same error, not founding the resource.

My question is, can I add an image to an iText doc? How can I do this?

Ps. I'm using iText5 (implementation 'com.itextpdf:itextg:5.5.10').

2 Answers 2

1

I solved my problem with some small changes. I'll let it here if anyone else is needing it.

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.logo); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, stream); Image img = null; byte[] byteArray = stream.toByteArray(); try { img = Image.getInstance(byteArray); } catch (BadElementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 

Then, this img you can add to your PDF file in iText.

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

Comments

0
 Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.logo); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, stream); ImageData logo = ImageDataFactory.create(stream.toByteArray()); document.add(new Image(logo)); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.