pdf - 使用 Uri 通过 Kotlin 解析 pdf?

标签 pdf kotlin uri pdfbox

我在 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/

相关文章:

pdf - JPG 到 PDF 转换,如何适应整页

android - 如何在 Kotlin 的枚举中检索用 vararg 声明的参数的值

android - 在 Android View 中检测后退按钮按下

android - NoSuchMethodError使用Kotlin与新的Android数据绑定(bind)

c# - 在 C# 中创建文件 Uri

delphi - 如何让 FastReport 生成可在 iOS 上查看的 PDF?

php - 给定的流在 FPDI 中不可查找

java - 是否可以从 Base64 字符串创建 pdf 文件?

url - 不是 URL 的 URI 示例?

java - 尝试从 Android 应用程序将录制的视频上传到服务器时出现 FileNotFoundException