We are using HP printer .
We are using Android devices to print the PDF documrnt..
Below is the code block
MyActivity.java
PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE);
String jobName = "application_name" + " Document";
printManager.print(jobName, new PrintDocumentAdapter(mContext, mFilePathFile), null);
PrintDocumentAdapter.java
public class PrintDocumentAdapter extends PrintDocumentAdapter {
//All Variables
public PrintDocumentAdapter(Context context, File pdfFile1) {
this.context = context;
pdfFile = pdfFile1;
}
@Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
@Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes,
CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle metadata) {
myPdfDocument = new PrintedPdfDocument(context, newAttributes);
//totalpages = computePDFPageCount(pdfFile);
try {
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));
totalpages = renderer.getPageCount();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
if (totalpages > 0) {
PrintDocumentInfo.Builder builder = new PrintDocumentInfo.Builder(pdfFile.getName()).setContentType(
PrintDocumentInfo.CONTENT_TYPE_PHOTO).setPageCount(totalpages);
PrintDocumentInfo info = builder.build();
callback.onLayoutFinished(info, true);
} else {
callback.onLayoutFailed("Page count is zero.");
}
}
@Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal,
WriteResultCallback callback) {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(pdfFile);
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
// mPrintCompleteService.onMessage(Constants.PRINTER_STATUS_CANCELLED);
} catch (Exception e) {
// Catch exception
// mPrintCompleteService.onMessage(Constants.PRINTER_STATUS_CANCELLED);
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
// mPrintCompleteService.onMessage(Constants.PRINTER_STATUS_CANCELLED);
}
}
cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
@Override
public void onCancel() {
// mPrintCompleteService.onMessage(Constants.PRINTER_STATUS_CANCELLED);
}
});
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
super.onFinish();
}
}
For reference
developer.android.com/intl/zh-tw/referen...DocumentAdapter.html
.