Android实现系统打印功能

所属分类: 软件编程 / Android 阅读数: 41
收藏 0 赞 0 分享

本文实例为大家分享了Android实现系统打印的具体代码,供大家参考,具体内容如下

一、打印图片

使用PrintHelper类,如:

private void doPhotoPrint() {
 PrintHelper photoPrinter = new PrintHelper(getActivity());
 photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
 Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
   R.drawable.droids);
 photoPrinter.printBitmap("droids.jpg - test print", bitmap);
}

可以在应用的菜单栏中调用该方法,当printBitmap()方法调用时,Android系统的打印界面
会弹出,用户可以设置一些参数,然后进行打印或取消。

二、打印自定义文档

1.连接到PrintManager类:

private void doPrint() {
 // Get a PrintManager instance
 PrintManager printManager = (PrintManager) getActivity()
   .getSystemService(Context.PRINT_SERVICE);
 
 // Set job name, which will be displayed in the print queue
 String jobName = getActivity().getString(R.string.app_name) + " Document";
 
 // Start a print job, passing in a PrintDocumentAdapter implementation
 // to handle the generation of a print document
 printManager.print(jobName, new MyPrintDocumentAdapter(getActivity()),
   null); //
}

注:print函数第二个参数为继承了抽象类PrintDocumentAdapter 的适配器类,第三个参数为 PrintAttributes对象,

可以用来设置一些打印时的属性。

2.创建打印适配器类

打印适配器与Android系统的打印框架进行交互,处理打印的生命周期方法。打印过程主要有以下生命周期方法:

  • onStart():当打印过程开始的时候调用;
  • onLayout():当用户更改打印设置导致打印结果改变时调用,如更改纸张尺寸,纸张方向等;
  • onWrite():当将要打印的结果写入到文件中时调用,该方法在每次onLayout()调用后会调用一次或多次;
  • onFinish():当打印过程结束时调用。

注:关键方法有onLayout()和onWrite(),这些方法默认都是在主线程中调用,因此如果打印过程比较耗时,应该在后台线程中进行。

3.覆盖onLayout()方法

在onLayout()方法中,你的适配器需要告诉系统框架文本类型,总页数等信息,如:

@Override
public void onLayout(PrintAttributes oldAttributes,
      PrintAttributes newAttributes,
      CancellationSignal cancellationSignal,
      LayoutResultCallback callback,
      Bundle metadata) {
 // Create a new PdfDocument with the requested page attributes
 mPdfDocument = new PrintedPdfDocument(getActivity(), newAttributes);
 
 // Respond to cancellation request
 if (cancellationSignal.isCancelled() ) {
  callback.onLayoutCancelled();
  return;
 }
 
 // Compute the expected number of printed pages
 int pages = computePageCount(newAttributes);
 
 if (pages > 0) {
  // Return print information to print framework
  PrintDocumentInfo info = new PrintDocumentInfo
    .Builder("print_output.pdf")
    .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
    .setPageCount(pages);
    .build();
  // Content layout reflow is complete
  callback.onLayoutFinished(info, true);
 } else {
  // Otherwise report an error to the print framework
  callback.onLayoutFailed("Page count calculation failed.");
 }
}

注:onLayout()方法的执行有完成,取消,和失败三种结果,你必须通过调用 PrintDocumentAdapter.LayoutResultCallback类的适当回调方法表明执行结果, onLayoutFinished()方法的布尔型参数指示布局内容是否已经改变。

onLayout()方法的主要任务就是计算在新的设置下,需要打印的页数,如通过打印的方向决定页数:
private int computePageCount(PrintAttributes printAttributes) {
 int itemsPerPage = 4; // default item count for portrait mode
 
 MediaSize pageSize = printAttributes.getMediaSize();
 if (!pageSize.isPortrait()) {
  // Six items per page in landscape orientation
  itemsPerPage = 6;
 }
 
 // Determine number of print items
 int printItemCount = getPrintItemCount();
 
 return (int) Math.ceil(printItemCount / itemsPerPage);
}

4.覆盖onWrite()方法

当需要将打印结果输出到文件中时,系统会调用onWrite()方法,该方法的参数指明要打印的页以及结果写入的文件,你的方法实现需要将页面的内容写入到一个多页面的PDF文档中,当这个过程完成时,需要调用onWriteFinished() 方法,如:

@Override
public void onWrite(final PageRange[] pageRanges,
     final ParcelFileDescriptor destination,
     final CancellationSignal cancellationSignal,
     final WriteResultCallback callback) {
 // Iterate over each page of the document,
 // check if it's in the output range.
 for (int i = 0; i < totalPages; i++) {
  // Check to see if this page is in the output range.
  if (containsPage(pageRanges, i)) {
   // If so, add it to writtenPagesArray. writtenPagesArray.size()
   // is used to compute the next output page index.
   writtenPagesArray.append(writtenPagesArray.size(), i);
   PdfDocument.Page page = mPdfDocument.startPage(i);
 
   // check for cancellation
   if (cancellationSignal.isCancelled()) {
    callback.onWriteCancelled();
    mPdfDocument.close();
    mPdfDocument = null;
    return;
   }
 
   // Draw page content for printing
   drawPage(page);
 
   // Rendering is complete, so page can be finalized.
   mPdfDocument.finishPage(page);
  }
 }
 
 // Write PDF document to file
 try {
  mPdfDocument.writeTo(new FileOutputStream(
    destination.getFileDescriptor()));
 } catch (IOException e) {
  callback.onWriteFailed(e.toString());
  return;
 } finally {
  mPdfDocument.close();
  mPdfDocument = null;
 }
 PageRange[] writtenPages = computeWrittenPages();
 // Signal the print framework the document is complete
 callback.onWriteFinished(writtenPages);
 
 ...
}

drawPage()方法实现:

private void drawPage(PdfDocument.Page page) {
 Canvas canvas = page.getCanvas();
 
 // units are in points (1/72 of an inch)
 int titleBaseLine = 72;
 int leftMargin = 54;
 
 Paint paint = new Paint();
 paint.setColor(Color.BLACK);
 paint.setTextSize(36);
 canvas.drawText("Test Title", leftMargin, titleBaseLine, paint);
 
 paint.setTextSize(11);
 canvas.drawText("Test paragraph", leftMargin, titleBaseLine + 25, paint);
 
 paint.setColor(Color.BLUE);
 canvas.drawRect(100, 100, 172, 172, paint);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

使用ViewPager实现android软件使用向导功能实现步骤

现在的大部分android软件,都是使用说明,就是第一次使用该软件时,会出现向导,可以左右滑动,然后就进入应用的主界面了,下面我们就实现这个功能
收藏 0 赞 0 分享

android在异步任务中关闭Cursor的代码方法

android在异步任务中如何关闭Cursor?在我们开发应用的时候,很多时候会遇到这种问题,下面我们就看看代码如何实现
收藏 0 赞 0 分享

Android自定义桌面功能代码实现

android自定义桌面其实很简单,看一个例子就明白了
收藏 0 赞 0 分享

android将图片转换存到数据库再从数据库读取转换成图片实现代码

有时候我们想把图片存入到数据库中,尽管这不是一种明智的选择,但有时候还是不得以会用到,下面说说将图片转换成byte[]数组存入到数据库中去,并从数据库中取出来转换成图像显示出来
收藏 0 赞 0 分享

TextView显示系统时间(时钟功能带秒针变化

用System.currentTimeMillis()可以获取系统当前的时间,我们可以开启一个线程,然后通过handler发消息,来实时的更新TextView上显示的系统时间,可以做一个时钟的功能
收藏 0 赞 0 分享

Android用ListView显示SDCard文件列表的小例子

本文简单实现了用ListView显示SDCard文件列表,目录的回退等功能暂不讨论,获取文件列表,files即为所选择目录下的所有文件列表
收藏 0 赞 0 分享

Android拦截外拨电话程序示例

这篇文章主要介绍了Android拦截外拨电话的示例,大家参考使用吧
收藏 0 赞 0 分享

通过Html网页调用本地安卓(android)app程序代码

如何使用html网页和本地app进行传递数据呢?经过研究,发现还是有方法的,总结了一下,大致有一下几种方式
收藏 0 赞 0 分享

android Textview文字监控(Textview使用方法)

以手机号充值为例,当用户输入最后一位数时候,进行汇率的变换,本文就实现类似这样的功能
收藏 0 赞 0 分享

Android ListView长按弹出菜单二种实现方式示例

这篇文章主要介绍了Android ListView长按弹出菜单的方法,大家参考实现
收藏 0 赞 0 分享
查看更多