Listview to pdf in android

2020-03-06 03:39发布

问题:

I have a custom listview and I want to make pdf from the whole listview. I refered many posts and implemented below code which converts my listview to pdf. But problem is its not containing the whole listview item. Only first few items are available in the pdf.

My function to convert listview to pdf is

fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String state = Environment.getExternalStorageState();
            if (!Environment.MEDIA_MOUNTED.equals(state)) {

            }
            File pdfDir = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), "MyProject");
            if (!pdfDir.exists()){
                pdfDir.mkdir();
            }
            Bitmap screen =  getWholeListViewItemsToBitmap();
            File pdfFile = new File(pdfDir, "myPdfFile_new.pdf");

            try {
                Document document = new Document();
                PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
                document.open();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                screen.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();
                addImage(document,byteArray);
                document.close();
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    });

addImage method

private static void addImage(Document document,byte[] byteArray)
{
    Image image = null;
    try
    {
        image = Image.getInstance(byteArray);
    }
    catch (BadElementException e)
    {
        e.printStackTrace();
    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    try
    {
        document.add(image);
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

method to get list items

public Bitmap getWholeListViewItemsToBitmap() {

    ListView listview    = StockReportActivity.category_list;
    ListAdapter adapter  = listview.getAdapter();
    int itemscount       = adapter.getCount();
    int allitemsheight   = 0;
    List<Bitmap> bmps    = new ArrayList<Bitmap>();

    for (int i = 0; i < itemscount; i++) {

        View childView      = adapter.getView(i, null, listview);
        childView.measure(View.MeasureSpec.makeMeasureSpec(listview.getWidth(), View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        childView.layout(0, 0, childView.getMeasuredWidth(), childView.getMeasuredHeight());
        childView.setDrawingCacheEnabled(true);
        childView.buildDrawingCache();
        bmps.add(childView.getDrawingCache());
        allitemsheight+=childView.getMeasuredHeight();
    }
    Bitmap bigbitmap    = Bitmap.createBitmap(listview.getMeasuredWidth(), allitemsheight, Bitmap.Config.ARGB_8888);
    Canvas bigcanvas    = new Canvas(bigbitmap);
    Paint paint = new Paint();
    int iHeight = 0;
    for (int i = 0; i < bmps.size(); i++) {
        Bitmap bmp = bmps.get(i);
        bigcanvas.drawBitmap(bmp, 0, iHeight, paint);
        iHeight+=bmp.getHeight();
        bmp.recycle();
        bmp=null;
    }
     return bigbitmap;
    }

My listview contains large number of items in it, so how can i convert the whole listview to pdf. All your suggestions are appreciated

回答1:

You can get the number of items displayed on screen in recyclerView, so create bitmap for first set of views, after that you can dynamically scroll to item below the last item displayed (i.e noOfItemDisplayed+1), again get bitmap, likewise all get all bitmaps into ArrayList<Bitmap> from which you can create pdf file, refer to code below to create pdf from arraylist of bitmaps:

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void createPdf() throws IOException {

    PdfDocument document = new PdfDocument();
    PdfDocument.Page page = null;
    // crate a page description
    for (int i = 0; i < bitmaps.size(); i++) {
        Bitmap bitmap = bitmaps.get(i);
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(1400, 1979, i).create();

        // start a page
        page = document.startPage(pageInfo);
        if (page == null) {
            return;
        }
        Canvas canvas = page.getCanvas();
        canvas.drawBitmap(bitmap, 0, 0, null);
        document.finishPage(page);
    }

    // finish the page


    // write the document content
    fileHandler = new FileHandler(this, getString(R.string.app_name));
    File pdf = fileHandler.getNewFileToWrite(AppConstants.FileExtensions.PDF); //crete and get file

    try {
        document.writeTo(new FileOutputStream(pdf));
    } catch (IOException e) {
        logger.error(e);
    }

    // close the document
    document.close();

}