在Android中使用来自Recyclerview(内部的整个项目)的iText创建PDF文件? [英] Creating PDF file using iText from a Recyclerview (Entire items inside) in Android?

查看:123
本文介绍了在Android中使用来自Recyclerview(内部的整个项目)的iText创建PDF文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在尝试使用图书馆



案例2:当用户多次向上和向下滚动





在上图中,您可以注意到 Apple 已被复制



感谢任何帮助

解决方案

经过数小时的追踪和错误我找到了答案。我正在分享代码片段,因为它可能对其他人有帮助

  public void generatePDF(RecyclerView view){ 

RecyclerView.Adapter adapter = view.getAdapter();
位图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);

//使用此内存缓存的1/8可用内存。
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();
位图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);

凭证凭证=新凭证(PageSize.A4);
final文件file = new File(getStorageDir(PDF),print.pdf);
try {
PdfWriter.getInstance(document,new FileOutputStream(file));
} catch(DocumentException | FileNotFoundException e){
e.printStackTrace();
}

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

try {
//将内容添加到文档
位图bmp = bitmaCache.get(String.valueOf(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG,100,stream);
Image image = Image.getInstance(stream.toByteArray());
image.scalePercent(70);
image.setAlignment(Image.MIDDLE);
if(!document.isOpen()){
document.open();
}
document.add(image);

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

if(document.isOpen()){
document.close();
}
//在UI线程上设置
runOnUiThread(new Runnable(){
@Override
public void run(){

AlertDialog.Builder builder = new AlertDialog.Builder(Index.this);
builder.setTitle(Success)
.setMessage(PDF文件生成成功。)
.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(file),application / pdf);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(意图);
}

})。show();
}
});

}

}


Hi i was trying to create a PDF output file from a Recyclerview using the library iText . After hours of struggle i was able to create PDF from recylerview .

Following is are classes which i used to create PDF

Codes from Main Class

     private void getPrint() {


    ArrayList<View> viewArrayList = mAdapter.getPrintView(); // A function from Adapter class which returns ArrayList of VIEWS
    Document document = new Document(PageSize.A4);
    final File file = new File(getStorageDir("PDF"), "print.pdf");
    try {
        PdfWriter.getInstance(document, new FileOutputStream(file));
    } catch (DocumentException | FileNotFoundException e) {
        e.printStackTrace();
    }

    for (int im = 0; im < viewArrayList.size(); im++) {
        // Iterate till the last of the array list and add each view individually to the document.
        try {
            viewArrayList.get(im).buildDrawingCache();         //Adding the content to the document
            Bitmap bmp = viewArrayList.get(im).getDrawingCache();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            Image image = Image.getInstance(stream.toByteArray());
            image.scalePercent(70);
            image.setAlignment(Image.MIDDLE);
            if (!document.isOpen()) {
                document.open();
            }
            document.add(image);

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

    if (document.isOpen()) {
        document.close();
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(Index.this);
    builder.setTitle("Success")
            .setMessage("PDF 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(file), "application/pdf");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    startActivity(intent);
                }

            }).show();

}

Common RecyclerView Adapter Class

    public class RecyclerAdapter<T, VM extends ViewDataBinding> extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private final Context context;
private ArrayList<T> items;
private int layoutId;
private RecyclerCallback<VM, T> bindingInterface;
private static ArrayList<View> mPrintView = new ArrayList<>();

public RecyclerAdapter(Context context, ArrayList<T> items, int layoutId, RecyclerCallback<VM, T> bindingInterface) {
    this.items = items;
    this.context = context;
    this.layoutId = layoutId;
    this.bindingInterface = bindingInterface;
}

public class RecyclerViewHolder extends RecyclerView.ViewHolder {

    VM binding;

    public RecyclerViewHolder(View view) {
        super(view);
        binding = DataBindingUtil.bind(view);
    }

    public void bindData(T model) {
        bindingInterface.bindData(binding, model);
        binding.executePendingBindings();
    }

}

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent,
                                             int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(layoutId, parent, false);
    return new RecyclerViewHolder(v);
}

@Override
public void onBindViewHolder(RecyclerAdapter.RecyclerViewHolder holder, int position) {
    T item = items.get(position);
    Log.e("PRINT ", holder.binding.getRoot().getId() + "");
    mPrintView.add(holder.binding.getRoot());
    holder.bindData(item);

}

@Override
public int getItemCount() {
    if (items == null) {
        return 0;
    }
    return items.size();
}

public static ArrayList<View> getPrintView() {
    return mPrintView;
}

}

I am using an Arraylist called mPrintView to save views inside RecylerView . Problem arises when a USER scroll the recylerview UP and DOWM multiple time the data inside ArrayList becomes duplicated

Following are the images of results which i got after PDF convertion

Case 1 : When user scrolled only single time

Case 2 : When user Scroll UP and DOWN multiple time

In the above image you can notice that the Apple has been duplicated

Any help is appreciated

解决方案

After hours of trail and error i found the answer . I am sharing the code snippets as it may be helpful for some else

     public void generatePDF(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);

        Document document = new Document(PageSize.A4);
        final File file = new File(getStorageDir("PDF"), "print.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);
                Image image = Image.getInstance(stream.toByteArray());
                image.scalePercent(70);
                image.setAlignment(Image.MIDDLE);
                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() {

                AlertDialog.Builder builder = new AlertDialog.Builder(Index.this);
                builder.setTitle("Success")
                        .setMessage("PDF 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(file), "application/pdf");
                                intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                startActivity(intent);
                            }

                        }).show();
            }
        });

    }

}

这篇关于在Android中使用来自Recyclerview(内部的整个项目)的iText创建PDF文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆