从RecyclerView完整内容创建PDF?

时间:2017-03-07 05:59:13

标签: android pdf printing android-recyclerview

问题已在此处提出:create PDF of RecyclerView in FULL length  我也有同样的问题,因为我还没有找到解决方案,我想生成全长的RecyclerView内容PDF。但是没有找到解决方案。

我已经尝试了所有可用的解决方案以及从RecycleView生成PDF的所有可能方法。

我已经尝试过的解决方案:

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

Take a screenshot of RecyclerView in FULL length

Convert Listview Items into a single Bitmap Image

尝试了上面提到的所有解决方案,但是他们中的任何一个都没有和我一起工作并且得到错误,有时宽度&高度问题或某些时候得到空的白色位图作为输出不知道为什么。

问题:

我有带有HTML内容的RecyclerView以及内容之间的图像。

将以下屏幕视为包含内容的RecyclerView。

enter image description here

将RecyclerView中的内容与上面的图像相同,包含100多个项目。

RecyclerView项目布局:

<?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>

更新

因为我正在处理PDF以从视图生成PDF,并且无法生成PDF所以我发布了这个问题。

但是现在,我找到了一个使用Webview生成PDF的解决方案,你可以看到我对这个问题的回答已被标记为已被接受。

基于我找到的解决方案,我创建了一个库,可以从任何字符串或任何HTML内容生成PDF。

PDF-Generator Library: PDF-Generator

由于

4 个答案:

答案 0 :(得分:0)

这是从视图生成PDF的samble代码

  //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();
    }


}

答案 1 :(得分:0)

经过大量的解决方法和解决方案后,我得到了解决方案,以及实现这一目标的最佳方法,

以html格式在webview中添加您的内容,从webview我们可以直接使用Android的PrintManager类进行打印。

喜欢这样:

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());

上面是打印webview内容的示例代码,使用它我们也可以生成PDF。

有关详细信息和使用,请参阅此Printing HTML Document

感谢。

答案 2 :(得分:0)

viewRecyclerView的实例:

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);

答案 3 :(得分:0)

我一直在这里查看所有答案,但是不幸的是,它们对我没有用。我采用了从StackOverflow创建位图的方法。该方法以回收站视图作为参数,并将其转换为Bitmap,然后由PdfDocument.pageInfo使用该Bitmap使其适合您的需求。我尝试过,它非常适合所有布局,例如相对布局和线性布局。希望这会有所帮助。

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;
    }