首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从RecyclerView的全部内容创建PDF?

从RecyclerView的全部内容创建PDF?
EN

Stack Overflow用户
提问于 2017-03-07 05:59:13
回答 4查看 9.7K关注 0票数 2

这里已经提出了问题:创建完整长度的RecyclerView PDF和我也有相同的问题,因为我还没有找到解决方案,--我想生成完整长度的RecyclerView内容的PDF。,但没有找到解决方案。

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

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

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

完整地拍摄RecyclerView的截图

将Listview项转换为单个位图图像

已经尝试过上面提到的所有解决方案,但是它们中的任何一个都没有与我一起工作,并且会出现错误,有时会出现宽度和高度问题,有时会出现空的白色位图,因为输出不知道为什么。

问题:

我有RecyclerView的内容以及图片之间的内容。

考虑使用内容为.的屏幕作为RecyclerView

在RecyclerView中具有与上面的图像相同的100+项的内容。

RecyclerView项目布局:

代码语言:javascript
运行
复制
<?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-生成器库: PDF-生成器

谢谢

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-05-29 05:33:16

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

将内容以html形式添加到webview中,通过webview,我们可以直接使用Android的PrintManager类进行打印。

像这样的 :

代码语言:javascript
运行
复制
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。

有关更多信息并使用此打印HTML文档

谢谢。

票数 0
EN

Stack Overflow用户

发布于 2019-12-30 00:12:16

我在这里看了所有的答案,但不幸的是,它们对我不起作用。我采用了从StackOverflow创建位图的方法。该方法以回收者视图为参数,并将其转换为位图,然后由PdfDocument.pageInfo使用它来满足您的需要。我试过了,它非常适合所有的布局,比如相对布局和线性布局。希望这能帮上忙。

代码语言:javascript
运行
复制
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;
    }
票数 4
EN

Stack Overflow用户

发布于 2017-03-07 07:06:42

下面是从视图生成PDF的示例代码

代码语言:javascript
运行
复制
  //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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42641215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档