【发布时间】:2020-04-08 21:44:35
【问题描述】:
在我的 NativeScript-Vue 应用程序中,我需要将 PDF 文档打印到蓝牙打印机并接收打印成功或取消的回调。插件 nativescript-printer 在 iOS 上完美处理它,但在 Android 上它不会返回回调 (the feature is not implemented)。该插件使用PrintHelper类,它有一个回调,在成功和取消时都会被调用,没有参数和返回。
似乎唯一的解决方案是通过PrintManager 类实现打印。一些来源:
- Printing custom documents | Android Developers
- An Android Custom Document Printing Tutorial
- Printing PDF directly using PrintManager Android 4.4
- How to Print PDF using Android 4.4 Printing framework(很多人赞成,这似乎是最好的答案)
所以这就是我尝试过的。 onWrite 和 onLayout 工作,但永远不会调用 onStart 和 onFinish(这是我的目标)。
import * as application from "tns-core-modules/application";
function printPdf(pdfFilePath) { // path: "/data/user/0/com.myapp.test/cache/pdf/document1.pdf"
let printManager = application.android.foregroundActivity.getSystemService(android.content.Context.PRINT_SERVICE);
let jobName = "PrintPdf";
let PrintPDFAdapter = android.print.PrintDocumentAdapter.extend({
onStart() {
console.log("on start);
},
onWrite(pages, destination, cancellationSignal, callback) {
let input;
let output;
try {
input = new java.io.FileInputStream(new java.io.File(pdfFilePath));
output = new java.io.FileOutputStream(destination.getFileDescriptor());
let buf = new Array.create("byte", 1024);
let bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
callback.onWriteFinished(new android.print.PageRange(0, 0));
} catch (e){
console.error(e);
} finally {
try {
input.close();
output.close();
} catch (e) {
console.error(e);
}
}
},
onLayout(oldAttributes, newAttributes, cancellationSignal, callback, extras){
try {
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
let pdi = new android.print.PrintDocumentInfo.Builder("print_output.pdf").setContentType(android.print.PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();
callback.onLayoutFinished(pdi, true);
} catch (e) {
console.error(e);
}
},
onFinish() {
console.log("on finish");
}
});
let pda = new PrintPDFAdapter();
printManager.print(jobName, pda, null);
}
【问题讨论】:
-
你没有创建Adapter实例,试试
printManager.print(jobName, new pda(), null); -
更新问题。它可以工作,但永远不会调用
onFinish()和onStart()。
标签: android nativescript