使用 Uri 使用 Kotlin 解析 pdf?
Parsing pdf with Kotlin using a Uri?
我在 Android Studio 中编写 Kotlin 代码。用户从 phone 中选择一个文件(我需要以字符串形式访问内容)。我得到一个 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 时 phone 冻结:
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)
我在 Android Studio 中编写 Kotlin 代码。用户从 phone 中选择一个文件(我需要以字符串形式访问内容)。我得到一个 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 时 phone 冻结:
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)