简体   繁体   中英

How can I import an image to my PDF using itext

I already create table and some extra information as a PDF. But I couldn't import image to my PDF whatever I did. I have my_thumb.png file in assets folder.

in my MainActivity class

try {
        inputStream = MainActivity.this.getAssets().open("my_thumb.png");
        Bitmap bmp = BitmapFactory.decodeStream(inputStream);
       ByteArrayOutputStream stream = new ByteArrayOutputStream();
       bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
       model.setThumbStream(stream); 
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

in my CreatePDF class

Image thumb = Image.getInstance(Model.getThumbStream().toByteArray());
   companyLogo.setAbsolutePosition(document.leftMargin(),121);
 companyLogo.scalePercent(25);

   document.add(thumb); 

and the problem is

bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);

this line returns with null.

What is the point that I missing?

Thanks in advance.

You first get the png to drawable

Drawable d = Drawable.createFromStream(getAssets().open("my_thumb.png"), null);

then convert drawable to bitmap and get the byte array :)

Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bitmapdata = stream.toByteArray();

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