简体   繁体   中英

iText: how to put transparent images into a pdf without making the transparent parts BLACK?

I'm using iText 5.5.9 inside my Android Studio project to make a PDF file.
When I add an image, the transparent parts turn to black inside the PDF.

How can I avoid that?

Here is the part of my code which illustrates the problem:

        // add card

        Resources res=getResources();
        Drawable drawable=res.getDrawable(R.drawable.card);
        Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

        byte[] bitMapData = stream.toByteArray();
        Image img=Image.getInstance(bitMapData);

        img.scaleAbsolute(300f,156.3f);
        img.setSmask(false);
        doc.add(img);

在此处输入图片说明

If you want to add a transparent circle image with broader (ie stroke) in iText , you can add a circle with stroke.

Use the code below (and change it to suit your needs) :

try {
  PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("myCirclepdffile.pdf"));
  document.open();

  PdfContentByte cb = writer.getDirectContent();

  cb.circle(250.0f, 500.0f, 200.0f);
  cb.stroke();

} catch (Exception e) {
  System.err.println(e.getMessage());
}

Transparent images aren't supported in PDF (such as PNGs or GIFs with a color that acts as if it were transparent), but they are supported in iText.

Transparency in images in PDF is achieved by adding the opaque image along with an image mask that mimics the transparency. For every transparent image added to a PDF, iText adds two images: the opaque image and the mask.

This is true for PNG files and GIF files that support transparency. Unfortunetely, you are using the JPEG format, and JPEG doesn't support transparency. See Transparent background in JPEG image

Use PNG or GIF instead of JPEG.

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