Parsing pdf with Kotlin using a Uri?

Viewed 641

I write Kotlin code in Android Studio. The user chooses a file from the phone (I need to access the content as a string). There I get a Uri?. With that Uri? I can extract text from .csv and .txt files:

if (typeOfFile == ".txt" || typeOfFile == ".csv") {
            try {
                val ins: InputStream? = contentResolver?.openInputStream(uriFromSelectedFile)
                val reader = BufferedReader(ins!!.reader())
                textIWant = reader.readText()

...

Getting the file type also works fine, but when it comes to opening pdf files, nothing seems to work. I tried using PDFBox from Apache in various ways. The pdf I try to open is a simple onePager and contains only extractable text (can be copied) like this pdf.

This is one of the things I tried, the phone freezes when the file to open is a pdf:

if (typeOfFile == ".pdf") {
            try {
                val myPDDocument:PDDocument = PDDocument(COSDocument(ScratchFile(File(uriFromSelectedFile.path))))
                textIWant = PDFTextStripper().getText(myPDDocument)

...

I´ve been trying for days. Does anyone know, how it works in Kotlin?

1 Answers

It worked using tom_roush.pdfbox and a companion object:

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
    }
}

Calling the parse function of the companion object:

val fis: InputStream = contentResolver?.openInputStream(uriFromSelectedFile)!!
textIWant = parse(fis)
Related