Pdf Renderer in android converted image is Transparent background
Asked Answered
A

2

9

I'm a newbie for android developing. I'm working on converting Pdf to Image and storing it in a location. I have used the PdfRenderer (API level 21) to convert the PDF to bitmap Image. The converted image is Transparent background. Please guide me to convert the image with white background. So that I can convert it to binary digits.

PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));

        Bitmap bitmap;
        final int pageCount = renderer.getPageCount();
        System.out.println("pageCount"+pageCount);
        for (int i = 0; i < pageCount; i++) {
            PdfRenderer.Page page = renderer.openPage(i);

            int width = getResources().getDisplayMetrics().densityDpi / 72 * page.getWidth();
            int height = getResources().getDisplayMetrics().densityDpi / 72 * page.getHeight();
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
            storeImage(bitmap,"test.bmp");//I have wrote a function here to save the image

This is the Transparent Image I get after converting

Thanks in advance.

Admissive answered 21/7, 2017 at 12:35 Comment(1)
Just save it as JPG. And you'll automatically lose any transparency information.Lobelia
A
21

I have used canvas and it worked

Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(bitmap, 0, 0, null);

Thank you.

Admissive answered 25/7, 2017 at 8:23 Comment(0)
O
16

Using Abdul's answer, this is the complete implementation that worked for me to avoid having a transparent background in a bitmap that came from a Pdf.

int pageCount = renderer.getPageCount();
for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
    PdfRenderer.Page page = renderer.openPage(pageIndex);
    Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(), Bitmap.Config.ARGB_8888);
    // Paint bitmap before rendering
    Canvas canvas = new Canvas(bitmap);
    canvas.drawColor(Color.WHITE);
    canvas.drawBitmap(bitmap, 0, 0, null);
    // Render Pdf page into bitmap
    page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
    page.close();
    bitmaps.add(bitmap);
}
Olympium answered 1/12, 2017 at 6:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.