android实现pdf打印,[NativeScript中用于PDF打印的Android实现

袁成化
2023-12-01

在我的NativeScript-Vue应用程序中,我需要将PDF文档打印到蓝牙打印机上,并接收回调,无论打印成功还是取消。插件nativescript-printer在iOS上可以完美处理,但在Android上不会返回回调(the feature is not implemented)。该插件使用PrintHelper类,该类具有一个回调,该回调在成功和取消时都会被调用,没有参数和返回值。

似乎唯一的解决方案是通过类PrintManager实现打印。一些来源:

所以这就是我尝试过的。 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);

}

 类似资料: