2

Question is already asked here : create PDF of RecyclerView in FULL length And I also have same Question as i haven't found solution yet, I want to Generate PDF of RecyclerView Content with full length. but did't found solution.

I have already tried all the available solutions and all the possible ways to generate PDF from RecycleView.

Solutions which i have already tried :

https://gist.github.com/PrashamTrivedi/809d2541776c8c141d9a

Take a screenshot of RecyclerView in FULL length

Convert Listview Items into a single Bitmap Image

Have tried all solutions which mentioned above but any of them not working with me and getting error, sometime width & height issue or sometime getting empty white bitmap as output don't know why.

Problem :

I have RecyclerView with HTML Content as well as Images in between contents.

Consider Following Screen as RecyclerView with content.

enter image description here

having content in RecyclerView same as above image with 100+ items.

RecyclerView Item Layout :

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<com.facebook.drawee.view.SimpleDraweeView
    android:id="@+id/leftImage"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_weight="1"
    android:adjustViewBounds="true"
    android:maxHeight="350dp"
    fresco:actualImageScaleType="fitCenter"
    fresco:placeholderImage="@color/white" />

<jp.wasabeef.richeditor.RichEditor
    android:id="@+id/editor"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/margin10dp"
    android:layout_marginRight="@dimen/margin10dp"
    android:layout_weight="1"
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false" />

<com.facebook.drawee.view.SimpleDraweeView
    android:id="@+id/rightImage"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_weight="1"
    android:adjustViewBounds="true"
    android:maxHeight="350dp"
    fresco:actualImageScaleType="fitCenter"
    fresco:placeholderImage="@color/white" />
</LinearLayout>

Update

As I was working on PDF to generate PDF from views, and was not able to generate PDF so I have posted this question.

But Now, I found a solution to generate PDF by using Webview you can see my answer on this question has marked as accepted.

Based on solution what I found, I have created a library to generate PDF from any String or Any HTML Content.

PDF-Generator Library: PDF-Generator

Thanks

Uttam Panchasara
  • 5,735
  • 5
  • 25
  • 41

4 Answers4

5

I was looking at all the answers here, but unfortunately, they didn't work for me. I took the method for creating Bitmap from StackOverflow. The method takes the recycler view as an argument and converts it into a Bitmap which is then used by the PdfDocument.pageInfo to make it work for your needs. I tried it and it works perfectly for all the layouts such as relative layout and linear layout. Hope this will help.

Bitmap recycler_view_bm =     getScreenshotFromRecyclerView(mRecyclerView);

        try {

            pdfFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(pdfFile);

            PdfDocument document = new PdfDocument();
            PdfDocument.PageInfo pageInfo = new
                    PdfDocument.PageInfo.Builder(recycler_view_bm.getWidth(), recycler_view_bm.getHeight(), 1).create();
            PdfDocument.Page page = document.startPage(pageInfo);
            recycler_view_bm.prepareToDraw();
            Canvas c;
            c = page.getCanvas();
           c.drawBitmap(recycler_view_bm,0,0,null);
            document.finishPage(page);
            document.writeTo(fOut);
            document.close();
            Snackbar snackbar = Snackbar
                    .make(equipmentsRecordActivityLayout, "PDF generated successfully.", Snackbar.LENGTH_LONG)
                    .setAction("Open", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                          openPDFRecord(pdfFile);
                        }
                    });

            snackbar.show();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public Bitmap getScreenshotFromRecyclerView(RecyclerView view) {
        RecyclerView.Adapter adapter = view.getAdapter();
        Bitmap bigBitmap = null;
        if (adapter != null) {
            int size = adapter.getItemCount();
            int height = 0;
            Paint paint = new Paint();
            int iHeight = 0;
            final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

            // Use 1/8th of the available memory for this memory cache.
            final int cacheSize = maxMemory / 8;
            LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
            for (int i = 0; i < size; i++) {
                RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
                adapter.onBindViewHolder(holder, i);
                holder.itemView.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(), holder.itemView.getMeasuredHeight());
                holder.itemView.setDrawingCacheEnabled(true);
                holder.itemView.buildDrawingCache();
                Bitmap drawingCache = holder.itemView.getDrawingCache();
                if (drawingCache != null) {

                    bitmaCache.put(String.valueOf(i), drawingCache);
                }

                height += holder.itemView.getMeasuredHeight();
            }

            bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);
            Canvas bigCanvas = new Canvas(bigBitmap);
            bigCanvas.drawColor(Color.WHITE);

            for (int i = 0; i < size; i++) {
                Bitmap bitmap = bitmaCache.get(String.valueOf(i));
                bigCanvas.drawBitmap(bitmap, 0f, iHeight, paint);
                iHeight += bitmap.getHeight();
                bitmap.recycle();
            }

        }
        return bigBitmap;
    }
usman malik
  • 91
  • 1
  • 3
1

Here is a samble code of generating a PDF from a view

  //create bitmap from view and returns it
private Bitmap getBitmapFromView(View view) {
    ScrollView hsv = (ScrollView) findViewById(R.id.scrollViewP);
    HorizontalScrollView horizontal = (HorizontalScrollView) findViewById(R.id.hsv);
    int totalHeight = hsv.getChildAt(0).getHeight();
    int totalWidth = horizontal.getChildAt(0).getWidth();
    Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth, totalHeight,Bitmap.Config.ARGB_8888);
    //Bind a canvas to it
    Canvas canvas = new Canvas(returnedBitmap);
    //Get the view's background
    Drawable bgDrawable =view.getBackground();
    if (bgDrawable!=null) {
        //has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    }   else{
        //does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    }
    // draw the view on the canvas
    view.draw(canvas);
    //return the bitmap
    return returnedBitmap;
}
private static void addImage(Document document,byte[] byteArray)
{
    Image image = null;
    try
    {
        image = Image.getInstance(byteArray);
    }
    catch (BadElementException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (MalformedURLException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // image.scaleAbsolute(150f, 150f);
    try
    {
        document.add(image);
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
public void CreatePDF()
{

    File folder = new File(Environment.getExternalStorageDirectory()+File.separator+"PDF Folder");
    folder.mkdirs();

   Date date = new Date() ;
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);

   final File myFile = new File(folder + timeStamp + ".pdf");
    try {
        OutputStream output  = new FileOutputStream(myFile);
        Document document = new Document(PageSize.A4);
        try{
            PdfWriter.getInstance(document, output);
            document.open();
          LinearLayout view2 = (LinearLayout)findViewById(R.id.MainLayout);

            view2.setDrawingCacheEnabled(true);
            Bitmap screen2= getBitmapFromView(view2);
            ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
            screen2.compress(Bitmap.CompressFormat.JPEG,100, stream2);
            byte[] byteArray2 = stream2.toByteArray();
            addImage(document,byteArray2);

                document.close();
                AlertDialog.Builder builder =  new AlertDialog.Builder(PaySlip.this, R.style.AppCompatAlertDialogStyle);
                builder.setTitle("Success")
                        .setMessage("enter code herePDF File Generated Successfully.")
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton)
                            {
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setDataAndType(Uri.fromFile(myFile), "application/pdf");
                                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                startActivity(intent);
                            }

                        }).show();

            //document.add(new Paragraph(mBodyEditText.getText().toString()));
        }catch (DocumentException e)
        {
            //loading.dismiss();
            e.printStackTrace();
        }

    }catch (FileNotFoundException e)
    {
       // loading.dismiss();
      e.printStackTrace();
    }


}
Nyagaka Enock
  • 444
  • 1
  • 10
  • 20
1

Where view is the instance of RecyclerView:

view.measure(
             View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
             View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

myBitmap = Bitmap.createBitmap(view.getWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
eoinzy
  • 2,152
  • 4
  • 36
  • 67
0

After lots of workaround and solutions i got solution, and Best approach to achieve this,

Add your content in webview in html form, From webview we can directly do print using Android's PrintManager class.

Like this :

String documentName = "yourDocumentName"; // you can provide any name

// Get a PrintManager instance
PrintManager printManager = (PrintManager) context.getSystemService(PRINT_SERVICE);

// Get a print adapter instance
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(documentName);

PrintJob printJob = printManager.print(documentName, printAdapter, new PrintAttributes.Builder().build());

Above is sample code to do print of webview content, using this we can also generate PDF too.

For more info and use refer this Printing HTML Document

Thanks.

Uttam Panchasara
  • 5,735
  • 5
  • 25
  • 41
  • Is this really an answer to your question? How do we convert a recycler view content to PDF? The library you have provided only talks about string or HTML content, right? How do we convert our recycler view content to HTML in the first place? – Aldrin Joe Mathew Jul 02 '19 at 07:30
  • I did not get the solution to convert the recycled view content to HTML, so found the alternate solution, and I converted my whole content into HTML and than generated the PDF. And so I created a library for same. – Uttam Panchasara Jul 02 '19 at 07:44