How to Print PDF Using Android 4.4 Printing Framework

How to Print PDF using Android 4.4 Printing framework

After spend some hours on google i found the solution.

PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
String jobName = this.getString(R.string.app_name) + " Document";
printManager.print(jobName, pda, null);

PrintDocumentAdapter pda = new PrintDocumentAdapter(){

@Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
InputStream input = null;
OutputStream output = null;

try {

input = new FileInputStream(file to print);
output = new FileOutputStream(destination.getFileDescriptor());

byte[] buf = new byte[1024];
int bytesRead;

while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}

callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});

} catch (FileNotFoundException ee){
//Catch exception
} catch (Exception e) {
//Catch exception
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

@Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){

if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}

PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("Name of file").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();

callback.onLayoutFinished(pdi, true);
}
};

Android implementation for PDF printing in NativeScript

printManager.print() returns a PrintJob object, which has the current print state exposed. It's not nice, but this is my workaround:

function printPDF(pdfFilePath) {

// above code

let printJob = printManager.print(jobName, pda, null);

let onFinish = function(status) {
resolve(status);
clearInterval(interval);
}
let interval = setInterval(() => {
let state = printJob.getInfo().getState();
console.log(state);
if (state === 6) onFinish("print failed");
if (state === 7) onFinish("print cancelled");
if (state === 5) onFinish("print completed");
}, 500);
}

I might implement a timeout on the interval in the case the PrintJob state gets stuck on queued or blocked.

Android print framework - Silent print custom pdf to predetermined printer

AFAIK you cannot silent print the document in Android. There is an open issue on AOSP issue tracker.
https://code.google.com/p/android/issues/detail?id=160908.



Related Topics



Leave a reply



Submit