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' ).
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.
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.