Android Studio RecylerView到pdf

uemypmqf  于 12个月前  发布在  Android
关注(0)|答案(1)|浏览(180)

你好,我是新的Android工作室我做了recylerview的交易细节.我需要为这个recylerview项目创建PDF.示例:我有24 recylerview中的cardviews所以需要创建PDF与每页4 cardviews只.所以总的来说,我需要得到PDF为6页.如何做到这一点.提前感谢. This is sample image of my view
我在下面传递代码

recyclerView.measure(View.MeasureSpec.makeMeasureSpec(recyclerView.getWidth(),View.MeasureSpec.EXACTLY),View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED));
               Bitmap bm=Bitmap.createBitmap(recyclerView.getWidth(),recyclerView.getMeasuredHeight(),Bitmap.Config.ARGB_8888);



     String mpath2="/mnt/sdcard/mathanpaymentpdf";

     File imageFile = new File(mpath2);
     PDFHelper pdfHelper = new PDFHelper(imageFile,this);
               pdfHelper.saveImageToPDF(recyclerView,bm,"mathan"+System.currentTimeMillis());

    public class PDFHelper {

    private File mFolder;
    private File mFile;
    private Context mContext;

    public PDFHelper(File folder, Context context) {

        this.mContext = context;
        this.mFolder = folder;

        if(!mFolder.exists())
            mFolder.mkdirs();
    }

    public void saveImageToPDF(View title, Bitmap bitmap, String filename) {

        mFile = new File(mFolder, filename + ".pdf");
        if (!mFile.exists()) {
            int height = title.getHeight() + bitmap.getHeight();
            PdfDocument document = new PdfDocument();
            PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), height, 1).create();
            PdfDocument.Page page = document.startPage(pageInfo);
            Canvas canvas = page.getCanvas();
            title.draw(canvas);

            canvas.drawBitmap(bitmap, null, new Rect(0, title.getHeight(), bitmap.getWidth(),bitmap.getHeight()), null);

            document.finishPage(page);

            try {
                mFile.createNewFile();
                OutputStream out = new FileOutputStream(mFile);
                document.writeTo(out);
                document.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    }

字符串
这是尝试我得到PDF在一个单一的页面上只有只是我需要分成多个页面。

注意:我需要java代码,而不是Kotlin

laximzn5

laximzn51#

我使用itext库解决了这个问题

implementation 'com.itextpdf:itextpdf:5.0.6'

字符串
然后调用RecylerView

public void generatePDF(RecyclerView view) {

        RecyclerView.Adapter adapter = view.getAdapter();
        int sie2=adapter.getItemCount();
        if (sie2 == 0) {
            Toast.makeText(this,"No Transactions",Toast.LENGTH_LONG).show();
        }else{
        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);

            Document document=new Document();

            final File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MAT"+System.currentTimeMillis()+".pdf");
            try {
                PdfWriter.getInstance(document, new FileOutputStream(file));
            } catch (DocumentException | FileNotFoundException e) {
                e.printStackTrace();
            }

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

                try {
                    //Adding the content to the document
                    Bitmap bmp = bitmaCache.get(String.valueOf(i));
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    com.itextpdf.text.Image image= com.itextpdf.text.Image.getInstance(stream.toByteArray());
                    //Image image = Image.getInstance(stream.toByteArray());
                    float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
                            - document.rightMargin() - 50) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
                    image.scalePercent(scaler);
                    image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER | com.itextpdf.text.Image.ALIGN_TOP);
                    if (!document.isOpen()) {
                        document.open();
                    }
                    document.add(image);

                } catch (Exception ex) {
                    Log.e("TAG-ORDER PRINT ERROR", ex.getMessage());
                }
            }

            if (document.isOpen()) {
                document.close();
            }
            // Set on UI Thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivityAdminMain.this);
                    builder.setTitle("Success")
                            .setMessage("PDF File Generated Successfully.")
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .setPositiveButton("Open", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                //    dialog.dismiss();
                                    Intent target = new Intent(Intent.ACTION_VIEW);
                                    target.setDataAndType(Uri.fromFile(file), "application/pdf");
                                    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

                                    Intent intent56 = Intent.createChooser(target, "Open File");
                                    try {
                                        startActivity(intent56);
                                    } catch (ActivityNotFoundException e) {
                                        Toast.makeText(MainActivityAdminMain.this,"No PDF Viewer Installed.",Toast.LENGTH_LONG).show();

                                    }
                                }

                            }).show();
                }
            });

        }}

    }


100%工作..这有助于任何人需要

相关问题