我在 Android Studio 中编写 Kotlin 代码。用户从手机中选择一个文件(我需要以字符串形式访问内容)。我在那里得到一个 Uri?和那个乌里?我可以从 .csv 和 .txt 文件中提取文本:
if (typeOfFile == ".txt" || typeOfFile == ".csv") {
try {
val ins: InputStream? = contentResolver?.openInputStream(uriFromSelectedFile)
val reader = BufferedReader(ins!!.reader())
textIWant = reader.readText()
...
获取文件类型也可以正常工作,但在打开 pdf 文件时,似乎没有任何作用。我尝试以各种方式使用 Apache 的 PDFBox。我尝试打开的pdf是一个简单的onePager,仅包含可提取的文本(可以复制)like this pdf .
这是我尝试过的事情之一,当要打开的文件是 pdf 时,手机会卡住:
if (typeOfFile == ".pdf") {
try {
val myPDDocument:PDDocument = PDDocument(COSDocument(ScratchFile(File(uriFromSelectedFile.path))))
textIWant = PDFTextStripper().getText(myPDDocument)
...
我已经尝试了好几天了。有谁知道它在 Kotlin 中是如何工作的?
最佳答案
它使用 tom_roush.pdfbox 和一个伴随对象工作:
import com.tom_roush.pdfbox.text.PDFTextStripper
class MainActivity : AppCompatActivity() {
companion object PdfParser {
fun parse(fis: InputStream): String {
var content = ""
com.tom_roush.pdfbox.pdmodel.PDDocument.load(fis).use { pdfDocument ->
if (!pdfDocument.isEncrypted) {
content = PDFTextStripper().getText(pdfDocument)
}
}
return content
}
}
调用伴生对象的解析函数:
val fis: InputStream = contentResolver?.openInputStream(uriFromSelectedFile)!!
textIWant = parse(fis)
关于pdf - 使用 Uri 通过 Kotlin 解析 pdf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63105192/