欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现系统打印功能

程序员文章站 2022-04-30 22:47:50
本文实例为大家分享了android实现系统打印的具体代码,供大家参考,具体内容如下 一、打印图片 使用printhelper类,如: private...

本文实例为大家分享了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);
}

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