android系统打印功能实现,Android实现系统打印功能
本文实例为各位提供了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.");
}
}
注:该方法在执行时可能返回完成、取消或失败的状态,请适当调用 PrintDocumentAdapter.LayoutResultCallback类的方法以反映该操作的结果状态。The boolean parameter of the onLayoutFinished() method indicates whether the layout content has changed.
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);
}
以上就是本文的主要内容概括,请各位学友认真阅读并掌握相关知识;同时我们也在不断努力为大家提供更多优质的学习资源和支持,请各位多多关注并积极分享给更多需要的朋友!
