我正在从事热敏打印机项目,在该项目中,我使用Android Print Service从第三方应用程序中打印帐单。因为我必须打印为原始文本,所以我需要使用PrintJob从iTextPdf中提取文本。
到目前为止,一切都还不错,当时我在某些设备上看到了Crashlytics中的错误( stacktrace bellow )。每15个打印会话一次,他们就会遇到问题。甚至不确定我如何复制此错误,或者为什么不是每次都发生。
Caused by java.io.IOException: read failed: EBADF (Bad file number)
at libcore.io.IoBridge.read + 435(IoBridge.java:435)
at java.io.FileInputStream.read + 179(FileInputStream.java:179)
at java.io.InputStream.read + 162(InputStream.java:162)
at com.itextpdf.text.io.StreamUtil.inputStreamToArray(StreamUtil.java)
at com.itextpdf.text.io.RandomAccessSourceFactory.createSource(RandomAccessSourceFactory.java)
at com.itextpdf.text.pdf.PdfReader.(Unknown Source)
at com.itextpdf.text.pdf.PdfReader.(Unknown Source)
at sk.blockomat.vrp.pdf.PdfHelper$Companion.extractText(PdfHelper.java)
at sk.blockomat.vrp.services.CustomPrinterService.extractPrintJobText(CustomPrinterService.java)
at sk.blockomat.vrp.services.CustomPrinterService.onPrintJobQueued(CustomPrinterService.java)
at android.printservice.PrintService$ServiceHandler.handleMessage + 516(PrintService.java:516)
at android.os.Handler.dispatchMessage + 102(Handler.java:102)
at android.os.Looper.loop + 136(Looper.java:136)
at android.app.ActivityThread.main + 5584(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke + 515(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run + 1268(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main + 1084(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(NativeStart.java)
这是我用于PrintJob文本提取的代码:
override fun onPrintJobQueued(job: PrintJob) {
//mark job as started
job.start()
//transform print job to text
var text = extractPrintJobText(job)
//print text
...
}
private fun extractPrintJobText(job: PrintJob): String {
val descriptor = job.document.data!!.fileDescriptor
//this stream look some way corrupted
val stream = FileInputStream(descriptor)
if(!stream.fd.valid()) {
//I never saw this warning, so I expect every stream is valid
logger.logWarning(TAG, "Stream fd is not valid!")
}
return extractText(stream)
}
这是我遇到错误的应用程序的一部分。
fun extractText(stream: InputStream): String {
//line where I somethimes get EBADF (bad file number) error
val pdfReader = PdfReader(stream)
return extractText(pdfReader)
}
private fun extractText(pdfReader: PdfReader): String {
val pages = pdfReader.numberOfPages
var parsedText = ""
try {
for (i in 0 until pages) {
//Extracting the content from the different pages
parsedText += PdfTextExtractor.getTextFromPage(pdfReader, i + 1).trim() + "\n"
}
return parsedText
} finally {
pdfReader.close()
}
}