Android实现实现PDF预览打印功能预览打印功能
主要为大家详细介绍了Android实现PDF预览打印功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
最近在做一个项目,需要用到android手机连接打印机进行打印的功能,目前在网上找到的教程介绍的都是蓝牙连接热敏打印
机(pos机大小的打印机)和蓝牙打印机,如果连接日常所见到的网络打印机,进行打印,很显然这些教程是做不到的。
由于android没有提供任何标准,都是自家封的API,参考了WPS的APP的打印功能,决定按照WPS的方案来写,需要安装打
印服务插件,比如PrinterShare以及三星、HP提供的自家打印服务插件。
一、连接打印管理者一、连接打印管理者
当程序需要直接管理打印进程时,在收到用户的打印请求之后,第一步就是连接Android的打印框架,以及操作
PrintManager类的实例。这个类允许你实例化一个打印工作并开始打印的生命过程。下面的代码展示了如何获得一个打印管理
者和启动打印进程。
private void onPrintPdf() {
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
PrintAttributes.Builder builder = new PrintAttributes.Builder();
builder.setColorMode(PrintAttributes.COLOR_MODE_COLOR);
printManager.print("test pdf print", new MyPrintAdapter(this,filePath), builder.build());
}
二、创建打印适配器二、创建打印适配器
打印适配器会与Android的打印框架相连接,并会处理打印过程的每一个步骤。这个过程要求用户在创建文档打印之前选
择打印机及相关的打印选项。这些过程会影响最终的输出结果,就像用户选择了不同打印能力,不同的页面尺寸,不同的页面
方向一样。随着这些选项的设置,打印框架会要求适配器展示并生成一个打印文稿,为最终的打印做准备。一旦用户按下了打
印按钮,打印框架会拿到最终的打印文档然后交付给打印提供者以便打印。
package com.android.guocheng.printdemo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfDocument.PageInfo;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintDocumentInfo;
import android.print.pdf.PrintedPdfDocument;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by guocheng on 2017/6/13.
*/
public class MyPrintAdapter extends PrintDocumentAdapter {
private Context context;
private int pageHeight;
private int pageWidth;
private PdfDocument mPdfDocument;
private int totalpages = 1;
private String pdfPath;
private List<Bitmap> mlist;
public MyPrintAdapter(Context context,String pdfPath) {
this.context = context;
this.pdfPath = pdfPath;
}
@Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal,
LayoutResultCallback callback,
Bundle metadata) {
评论0