How to render PDF in Android

前端 未结 6 827
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 09:03

In my application I will receive a byte stream and convert it to a pdf file in the phone memory. How do I render that to a pdf? And show it on an activity?

6条回答
  •  难免孤独
    2020-11-22 10:00

    Android-Lollipop (api 21) introduce a new API : PdfRenderer

    This API allows you to create a Bitmap from a page in a PDF document.

    Shortly :

    • get a seekable file descriptor from your pdf document :

        ParcelFileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
      
    • create the PdfRenderer

        PdfRenderer renderer = new PdfRenderer(fd);
      
    • prepare the Bitmap

        Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_4444);
      
    • get the PdfRenderer.Page to render

        PdfRenderer.Page page = renderer.openPage(pageIndex);
      
    • render the page on the prepared bitmap

        page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
      
    • now you can do what you want with the bitmap.

    • note that the 2 null args may allow you to clip some portion in the page and perform a transformation (using a Matrix) of the clip

    • there is another rendering mode : RENDER_MODE_FOR_PRINT. If you need this mode there are some guidelines to use it properly : here are the details.

提交回复
热议问题