11 |
12 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Asutosh11
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://jitpack.io/#Asutosh11/DocumentReader)
2 | [](https://android-arsenal.com/api?level=5)
3 | [](https://android-arsenal.com/details/1/8136)
4 |
5 |
6 | # DocumentReader
7 |
8 | This library reads word documents (.doc and .docx), txt and PDF files, and gives the output content of the document as a String.
9 |
10 | If you have ever tried to read contents of a PDF or MS word document on Android, you know how painful it is.
11 | This library makes your work easy.
12 |
13 |
21 | ```
22 | dependencies {
23 | ....
24 | implementation 'com.github.Asutosh11:DocumentReader:0.12'
25 |
26 | // NOTE: use this only if you get a multidex exception
27 | implementation "androidx.multidex:multidex:2.0.1"
28 | }
29 | ```
30 |
31 | ```
32 | // NOTE: use this only if you get an error like - More than one file was found with OS independent path
33 | packagingOptions {
34 | exclude 'META-INF/DEPENDENCIES'
35 | exclude 'META-INF/INDEX.LIST'
36 | exclude 'META-INF/spring.handlers'
37 | exclude 'META-INF/spring.schemas'
38 | exclude 'META-INF/cxf/bus-extensions.txt'
39 | }
40 | ```
41 |
42 | ```
43 | // NOTE: use this only if you get a multidex exception
44 | defaultConfig {
45 | ...
46 | multiDexEnabled true
47 | }
48 | ```
49 |
50 |
How to use it?
51 |
52 | ```
53 | // Read a pdf file from Uri
54 | val docString : String = DocumentReaderUtil.readPdfFromUri(fileUri, applicationContext)
55 | // Read a pdf file from File
56 | val docString : String = DocumentReaderUtil.readPdfFromFile(file, applicationContext)
57 | ```
58 |
59 | ```
60 | // read a doc file from Uri
61 | val docString : String = DocumentReaderUtil.readWordDocFromUri(fileUri, applicationContext)
62 | // read a doc file from File
63 | val docString : String = DocumentReaderUtil.readWordDocFromFile(file, applicationContext)
64 | ```
65 |
66 | ```
67 | // read a docx file from Uri
68 | val docString : String = DocumentReaderUtil.readWordDocFromUri(fileUri, applicationContext)
69 | // read a docx file from File
70 | val docString : String = DocumentReaderUtil.readWordDocFromFile(file, applicationContext)
71 | ```
72 |
73 | ```
74 | // read a txt file from Uri
75 | val docString : String = DocumentReaderUtil.readTxtFromUri(fileUri, applicationContext)
76 | ```
77 |
78 | ```
79 | /*
80 | Even if you don't know your file type,
81 | this library detects the file mime type and gives you the content of the file as a String
82 | */
83 | val docString : String = when (DocumentReaderUtil.getMimeType(fileUri, applicationContext)) {
84 | "text/plain" -> DocumentReaderUtil.readTxtFromUri(fileUri, applicationContext)
85 | "application/pdf" -> DocumentReaderUtil.readPdfFromUri(fileUri, applicationContext)
86 | "application/msword" -> DocumentReaderUtil.readWordDocFromUri(fileUri, applicationContext)
87 | "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ->
88 | DocumentReaderUtil.readWordDocFromUri(fileUri, applicationContext)
89 | else -> ""
90 | }
91 | ```
92 |
93 |
Thanks
94 | The Apache Tika project
95 | Apache's PdfBox port by TomRoush
96 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | apply plugin: 'com.github.dcendents.android-maven'
3 | group = 'com.github.asutosh11'
4 | apply plugin: 'kotlin-android'
5 | apply plugin: 'kotlin-android-extensions'
6 |
7 | android {
8 | compileSdkVersion 29
9 | buildToolsVersion "29.0.3"
10 |
11 | defaultConfig {
12 | minSdkVersion 19
13 | targetSdkVersion 29
14 | versionCode 1
15 | versionName "1.0"
16 |
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 | }
19 |
20 | buildTypes {
21 | release {
22 | minifyEnabled false
23 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
24 | }
25 | }
26 |
27 | packagingOptions {
28 | exclude 'META-INF/DEPENDENCIES'
29 | exclude 'META-INF/INDEX.LIST'
30 | exclude 'META-INF/spring.handlers'
31 | exclude 'META-INF/spring.schemas'
32 | exclude 'META-INF/cxf/bus-extensions.txt'
33 | }
34 |
35 | repositories {
36 | maven { url 'https://jitpack.io' }
37 | }
38 |
39 | }
40 |
41 | dependencies {
42 | implementation fileTree(dir: 'libs', include: ['*.jar'])
43 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
44 | implementation 'androidx.appcompat:appcompat:1.1.0'
45 | implementation 'androidx.core:core-ktx:1.3.0'
46 | testImplementation 'junit:junit:4.12'
47 | androidTestImplementation 'androidx.test.ext:junit:1.1.1'
48 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
49 |
50 | implementation 'androidx.multidex:multidex:2.0.1'
51 |
52 | implementation (group: 'org.apache.tika', name: 'tika-parsers', version: '1.14'){
53 | exclude group: "org.apache.xmlbeans"
54 | ['org.apache.commons','commons-logging'].each {
55 | exclude group: "$it"
56 | }
57 | }
58 | implementation 'javax.xml.stream:stax-api:1.0'
59 | implementation group: 'org.apache.xmlbeans', name: 'xmlbeans', version: '3.0.1'
60 | implementation 'com.tom_roush:pdfbox-android:1.8.10.1'
61 | }
62 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/asutosh/documentreader/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.asutosh.documentreader
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.asutosh.documentreader", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/main/java/com/asutosh/documentreader/DocumentReaderUtil.kt:
--------------------------------------------------------------------------------
1 | package com.thoughtleaf.textsumarizex
2 |
3 | import android.content.ContentResolver
4 | import android.content.Context
5 | import android.net.Uri
6 | import com.asutosh.documentreader.FilePathHelper
7 | import com.tom_roush.pdfbox.cos.COSDocument
8 | import com.tom_roush.pdfbox.io.RandomAccessFile
9 | import com.tom_roush.pdfbox.pdfparser.PDFParser
10 | import com.tom_roush.pdfbox.pdmodel.PDDocument
11 | import com.tom_roush.pdfbox.text.PDFTextStripper
12 | import com.tom_roush.pdfbox.util.PDFBoxResourceLoader
13 | import org.apache.poi.hwpf.HWPFDocument
14 | import org.apache.poi.hwpf.extractor.WordExtractor
15 | import org.apache.poi.xwpf.usermodel.XWPFDocument
16 | import org.apache.poi.xwpf.usermodel.XWPFParagraph
17 | import java.io.BufferedReader
18 | import java.io.File
19 | import java.io.FileInputStream
20 | import java.io.InputStreamReader
21 |
22 |
23 | class DocumentReaderUtil {
24 |
25 | companion object {
26 |
27 | /**
28 | * @param uri - uri of the file on device
29 | * @param context - context object
30 | */
31 | fun getMimeType(uri: Uri, context: Context?): String? {
32 | val contentResolver: ContentResolver = context?.contentResolver!!
33 | return contentResolver.getType(uri)
34 | }
35 |
36 | /**
37 | * @param uri - uri of the file on device
38 | * @param context - context object
39 | */
40 | fun readPdfFromUri(uri: Uri?, context: Context?): String {
41 | PDFBoxResourceLoader.init(context)
42 | val file = File(context?.let { FilePathHelper(it).getPath(uri!!) }!!)
43 |
44 | val parser = PDFParser(RandomAccessFile(file, "r"))
45 | parser.parse()
46 |
47 | val cosDoc: COSDocument = parser.document
48 |
49 | val pdfStripper = PDFTextStripper()
50 | var document: PDDocument? = null
51 | document = PDDocument(cosDoc)
52 | return pdfStripper.getText(document)
53 | }
54 |
55 | /**
56 | * @param file - the file on device
57 | * @param context - context object
58 | */
59 | fun readPdfFromFile(file: File?, context: Context?): String {
60 | PDFBoxResourceLoader.init(context)
61 |
62 | val parser = PDFParser(RandomAccessFile(file, "r"))
63 | parser.parse()
64 |
65 | val cosDoc: COSDocument = parser.document
66 |
67 | val pdfStripper = PDFTextStripper()
68 | var document: PDDocument? = null
69 | document = PDDocument(cosDoc)
70 | return pdfStripper.getText(document)
71 | }
72 |
73 | /**
74 | * @param uri - uri of the file on device
75 | * @param context - context object
76 | */
77 | fun readTxtFromUri(uri: Uri?, context: Context?): String {
78 |
79 | val inputStream = context?.contentResolver?.openInputStream(uri!!)
80 | val bufferedReader = BufferedReader(InputStreamReader(inputStream!!, "UTF-8"))
81 |
82 | val inputString = bufferedReader.use { it.readText() }
83 | inputStream.close()
84 | bufferedReader.close()
85 |
86 | return inputString
87 | }
88 |
89 | /**
90 | * @param uri - uri of the file on device
91 | * @param context - context object
92 | */
93 | fun readWordDocFromUri(uri: Uri?, context: Context?): String {
94 |
95 | val file = File(context?.let { FilePathHelper(it).getPath(uri!!) }!!)
96 | val fullDocumentString: StringBuilder = StringBuilder()
97 | val fis = FileInputStream(file.absolutePath)
98 |
99 | if (file.extension == "doc") {
100 | val doc = HWPFDocument(fis)
101 | val we = WordExtractor(doc)
102 | val paragraphs: Array = we.paragraphText
103 |
104 | for (para in paragraphs) {
105 | fullDocumentString.append(para)
106 | }
107 | fis.close()
108 |
109 | } else if (file.extension == "docx") {
110 | val document = XWPFDocument(fis)
111 | val paragraphs: List = document.paragraphs
112 |
113 | for (para in paragraphs) {
114 | fullDocumentString.append(para.text)
115 | }
116 | fis.close()
117 | }
118 | return fullDocumentString.toString()
119 | }
120 |
121 | /**
122 | * @param file - the file on device
123 | * @param context - context object
124 | */
125 | fun readWordDocFromFile(file: File?, context: Context?): String {
126 |
127 | val fullDocumentString: StringBuilder = StringBuilder()
128 | val fis = FileInputStream(file?.absolutePath!!)
129 |
130 | if (file.extension == "doc") {
131 | val doc = HWPFDocument(fis)
132 | val we = WordExtractor(doc)
133 | val paragraphs: Array = we.paragraphText
134 |
135 | for (para in paragraphs) {
136 | fullDocumentString.append(para)
137 | }
138 | fis.close()
139 |
140 | } else if (file.extension == "docx") {
141 | val document = XWPFDocument(fis)
142 | val paragraphs: List = document.paragraphs
143 |
144 | for (para in paragraphs) {
145 | fullDocumentString.append(para.text)
146 | }
147 | fis.close()
148 | }
149 | return fullDocumentString.toString()
150 | }
151 |
152 | }
153 |
154 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/asutosh/documentreader/FilePathHelper.kt:
--------------------------------------------------------------------------------
1 | package com.asutosh.documentreader
2 |
3 | import android.annotation.SuppressLint
4 | import android.content.ContentUris
5 | import android.content.Context
6 | import android.database.Cursor
7 | import android.net.Uri
8 | import android.os.Build
9 | import android.os.Environment
10 | import android.provider.DocumentsContract
11 | import android.provider.MediaStore
12 | import android.provider.OpenableColumns
13 | import android.text.TextUtils
14 | import android.util.Log
15 | import java.io.File
16 | import java.io.FileOutputStream
17 |
18 | class FilePathHelper(var context: Context) {
19 |
20 | @SuppressLint("NewApi")
21 | fun getPath(uri: Uri): String? {
22 |
23 | // check here to KITKAT or new version
24 | val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
25 | var selection: String? = null
26 | var selectionArgs: Array? = null
27 |
28 | // DocumentProvider
29 | if (isKitKat) {
30 | // ExternalStorageProvider
31 | if (isExternalStorageDocument(uri)) {
32 | val docId = DocumentsContract.getDocumentId(uri)
33 | val split = docId.split(":").toTypedArray()
34 | val type = split[0]
35 | val fullPath = getPathFromExtSD(split)
36 | return if (fullPath !== "") {
37 | fullPath
38 | } else {
39 | null
40 | }
41 | }
42 | // DownloadsProvider
43 | if (isDownloadsDocument(uri)) {
44 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
45 | val id: String
46 | var cursor: Cursor? = null
47 | try {
48 | cursor = context.contentResolver.query(
49 | uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME),
50 | null, null, null
51 | )
52 | if (cursor != null && cursor.moveToFirst()) {
53 | val fileName = cursor.getString(0)
54 | val path =
55 | Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName
56 | if (!TextUtils.isEmpty(path)) {
57 | return path
58 | }
59 | }
60 | } finally {
61 | cursor?.close()
62 | }
63 | id = DocumentsContract.getDocumentId(uri)
64 | if (!TextUtils.isEmpty(id)) {
65 | if (id.startsWith("raw:")) {
66 | return id.replaceFirst("raw:".toRegex(), "")
67 | }
68 | val contentUriPrefixesToTry =
69 | arrayOf(
70 | "content://downloads/public_downloads",
71 | "content://downloads/my_downloads"
72 | )
73 | for (contentUriPrefix in contentUriPrefixesToTry) {
74 | return try {
75 | val contentUri = ContentUris.withAppendedId(
76 | Uri.parse(contentUriPrefix),
77 | java.lang.Long.valueOf(id)
78 | )
79 | getDataColumn(context, contentUri, null, null)
80 | } catch (e: NumberFormatException) {
81 | //In Android 8 and Android P the id is not a number
82 | uri.path!!.replaceFirst("^/document/raw:".toRegex(), "")
83 | .replaceFirst("^raw:".toRegex(), "")
84 | }
85 | }
86 | }
87 | } else {
88 | val id = DocumentsContract.getDocumentId(uri)
89 | if (id.startsWith("raw:")) {
90 | return id.replaceFirst("raw:".toRegex(), "")
91 | }
92 | try {
93 | contentUri = ContentUris.withAppendedId(
94 | Uri.parse("content://downloads/public_downloads"),
95 | java.lang.Long.valueOf(id)
96 | )
97 | } catch (e: NumberFormatException) {
98 | e.printStackTrace()
99 | }
100 | if (contentUri != null) {
101 | return getDataColumn(context, contentUri, null, null)
102 | }
103 | }
104 | }
105 | // MediaProvider
106 | if (isMediaDocument(uri)) {
107 | val docId = DocumentsContract.getDocumentId(uri)
108 | val split = docId.split(":").toTypedArray()
109 | val type = split[0]
110 | var contentUri: Uri? = null
111 | if ("image" == type) {
112 | contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
113 | } else if ("video" == type) {
114 | contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
115 | } else if ("audio" == type) {
116 | contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
117 | }
118 | selection = "_id=?"
119 | selectionArgs = arrayOf(split[1])
120 | return getDataColumn(context, contentUri, selection, selectionArgs)
121 | }
122 | if (isGoogleDriveUri(uri)) {
123 | return getDriveFilePath(uri)
124 | }
125 | if (isWhatsAppFile(uri)) {
126 | return getFilePathForWhatsApp(uri)
127 | }
128 | if ("content".equals(uri.scheme, ignoreCase = true)) {
129 | if (isGooglePhotosUri(uri)) {
130 | return uri.lastPathSegment
131 | }
132 | if (isGoogleDriveUri(uri)) {
133 | return getDriveFilePath(uri)
134 | }
135 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
136 | copyFileToInternalStorage(uri, "userfiles")
137 | } else {
138 | getDataColumn(context, uri, null, null)
139 | }
140 | }
141 | if ("file".equals(uri.scheme, ignoreCase = true)) {
142 | return uri.path
143 | }
144 | } else {
145 | if (isWhatsAppFile(uri)) {
146 | return getFilePathForWhatsApp(uri)
147 | }
148 | if ("content".equals(uri.scheme, ignoreCase = true)) {
149 | val projection = arrayOf(
150 | MediaStore.Images.Media.DATA
151 | )
152 | var cursor: Cursor? = null
153 | try {
154 | cursor = context.contentResolver.query(
155 | uri,
156 | projection,
157 | selection,
158 | selectionArgs,
159 | null
160 | )
161 | val columnIndex = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
162 | if (cursor.moveToFirst()) {
163 | return cursor.getString(columnIndex)
164 | }
165 | } catch (e: Exception) {
166 | e.printStackTrace()
167 | }
168 | }
169 | }
170 | return null
171 | }
172 |
173 | private fun fileExists(filePath: String): Boolean {
174 | val file = File(filePath)
175 | return file.exists()
176 | }
177 |
178 | private fun getPathFromExtSD(pathData: Array): String {
179 | val type = pathData[0]
180 | val relativePath = "/" + pathData[1]
181 | var fullPath = ""
182 |
183 | /**
184 | * on my Sony devices (4.4.4 & 5.1.1), `type` is a dynamic string
185 | * something like "71F8-2C0A", some kind of unique id per storage
186 | * don't know any API that can get the root path of that storage based on its id.
187 | * so no "primary" type, but let the check here for other devices
188 | */
189 | if ("primary".equals(type, ignoreCase = true)) {
190 | fullPath =
191 | Environment.getExternalStorageDirectory().toString() + relativePath
192 | if (fileExists(fullPath)) {
193 | return fullPath
194 | }
195 | }
196 |
197 | /*
198 | * Environment.isExternalStorageRemovable() is `true` for external and internal storage
199 | * so we cannot relay on it.
200 | * instead, for each possible path, check if file exists
201 | * we'll start with secondary storage as this could be our (physically) removable sd card
202 | */
203 | fullPath = System.getenv("SECONDARY_STORAGE") + relativePath
204 | if (fileExists(fullPath)) {
205 | return fullPath
206 | }
207 | fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath
208 | return if (fileExists(fullPath)) {
209 | fullPath
210 | } else fullPath
211 | }
212 |
213 | /**
214 | * Get the column indexes of the data in the Cursor,
215 | * move to the first row in the Cursor, get the data,
216 | * and display it.
217 | * */
218 | private fun getDriveFilePath(uri: Uri): String {
219 | val returnCursor =
220 | context.contentResolver.query(uri, null, null, null, null)
221 |
222 | val nameIndex = returnCursor!!.getColumnIndex(OpenableColumns.DISPLAY_NAME)
223 | returnCursor.moveToFirst()
224 | val name = returnCursor.getString(nameIndex)
225 | val file = File(context.cacheDir, name)
226 | try {
227 | val inputStream =
228 | context.contentResolver.openInputStream(uri)
229 | val outputStream = FileOutputStream(file)
230 | var read = 0
231 | val maxBufferSize = 1 * 1024 * 1024
232 | val bytesAvailable = inputStream!!.available()
233 | //int bufferSize = 1024;
234 | val bufferSize = Math.min(bytesAvailable, maxBufferSize)
235 | val buffers = ByteArray(bufferSize)
236 | while (inputStream.read(buffers).also { read = it } != -1) {
237 | outputStream.write(buffers, 0, read)
238 | }
239 | Log.e("File Size", "Size " + file.length())
240 | inputStream.close()
241 | outputStream.close()
242 | Log.e("File Path", "Path " + file.path)
243 | Log.e("File Size", "Size " + file.length())
244 | } catch (e: Exception) {
245 | Log.e("Exception", e.message)
246 | }
247 | return file.path
248 | }
249 |
250 | /***
251 | * Used for Android Q+
252 | * @param uri
253 | * @param newDirName if you want to create a directory, you can set this variable
254 | * @return
255 | */
256 | private fun copyFileToInternalStorage(uri: Uri, newDirName: String): String {
257 | val returnCursor = context.contentResolver.query(
258 | uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
259 | null, null, null
260 | )
261 |
262 | /**
263 | * Get the column indexes of the data in the Cursor,
264 | * move to the first row in the Cursor, get the data,
265 | * and display it.
266 | * */
267 | val nameIndex = returnCursor!!.getColumnIndex(OpenableColumns.DISPLAY_NAME)
268 | returnCursor.moveToFirst()
269 | val name = returnCursor.getString(nameIndex)
270 | val output: File
271 | output = if (newDirName != "") {
272 | val dir = File(context.filesDir.toString() + "/" + newDirName)
273 | if (!dir.exists()) {
274 | dir.mkdir()
275 | }
276 | File(context.filesDir.toString() + "/" + newDirName + "/" + name)
277 | } else {
278 | File(context.filesDir.toString() + "/" + name)
279 | }
280 | try {
281 | val inputStream =
282 | context.contentResolver.openInputStream(uri)
283 | val outputStream = FileOutputStream(output)
284 | var read = 0
285 | val bufferSize = 1024
286 | val buffers = ByteArray(bufferSize)
287 | while (inputStream!!.read(buffers).also { read = it } != -1) {
288 | outputStream.write(buffers, 0, read)
289 | }
290 | inputStream.close()
291 | outputStream.close()
292 | } catch (e: Exception) {
293 | Log.e("Exception", e.message)
294 | }
295 | return output.path
296 | }
297 |
298 | private fun getFilePathForWhatsApp(uri: Uri): String {
299 | return copyFileToInternalStorage(uri, "whatsapp")
300 | }
301 |
302 | private fun getDataColumn(
303 | context: Context,
304 | uri: Uri?,
305 | selection: String?,
306 | selectionArgs: Array?
307 | ): String? {
308 | var cursor: Cursor? = null
309 | val column = "_data"
310 | val projection = arrayOf(column)
311 | try {
312 | cursor = context.contentResolver.query(
313 | uri!!, projection,
314 | selection, selectionArgs, null
315 | )
316 | if (cursor != null && cursor.moveToFirst()) {
317 | val index = cursor.getColumnIndexOrThrow(column)
318 | return cursor.getString(index)
319 | }
320 | } finally {
321 | cursor?.close()
322 | }
323 | return null
324 | }
325 |
326 | private fun isExternalStorageDocument(uri: Uri): Boolean {
327 | return "com.android.externalstorage.documents" == uri.authority
328 | }
329 |
330 | private fun isDownloadsDocument(uri: Uri): Boolean {
331 | return "com.android.providers.downloads.documents" == uri.authority
332 | }
333 |
334 | private fun isMediaDocument(uri: Uri): Boolean {
335 | return "com.android.providers.media.documents" == uri.authority
336 | }
337 |
338 | private fun isGooglePhotosUri(uri: Uri): Boolean {
339 | return "com.google.android.apps.photos.content" == uri.authority
340 | }
341 |
342 | fun isWhatsAppFile(uri: Uri): Boolean {
343 | return "com.whatsapp.provider.media" == uri.authority
344 | }
345 |
346 | private fun isGoogleDriveUri(uri: Uri): Boolean {
347 | return "com.google.android.apps.docs.storage" == uri.authority || "com.google.android.apps.docs.storage.legacy" == uri.authority
348 | }
349 |
350 | companion object {
351 | private var contentUri: Uri? = null
352 | }
353 |
354 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Asutosh11/DocumentReader/66cf501b994ae60b8eeb24feca013569d2d47dac/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Asutosh11/DocumentReader/66cf501b994ae60b8eeb24feca013569d2d47dac/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Asutosh11/DocumentReader/66cf501b994ae60b8eeb24feca013569d2d47dac/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Asutosh11/DocumentReader/66cf501b994ae60b8eeb24feca013569d2d47dac/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Asutosh11/DocumentReader/66cf501b994ae60b8eeb24feca013569d2d47dac/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Asutosh11/DocumentReader/66cf501b994ae60b8eeb24feca013569d2d47dac/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Asutosh11/DocumentReader/66cf501b994ae60b8eeb24feca013569d2d47dac/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Asutosh11/DocumentReader/66cf501b994ae60b8eeb24feca013569d2d47dac/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Asutosh11/DocumentReader/66cf501b994ae60b8eeb24feca013569d2d47dac/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Asutosh11/DocumentReader/66cf501b994ae60b8eeb24feca013569d2d47dac/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #6200EE
4 | #3700B3
5 | #03DAC5
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | DocumentReader
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/java/com/asutosh/documentreader/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.asutosh.documentreader
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext.kotlin_version = '1.3.61'
5 | repositories {
6 | google()
7 | jcenter()
8 |
9 | }
10 | dependencies {
11 | classpath 'com.android.tools.build:gradle:3.6.2'
12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
13 | classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
14 | // NOTE: Do not place your application dependencies here; they belong
15 | // in the individual module build.gradle files
16 | }
17 | }
18 |
19 | allprojects {
20 | repositories {
21 | google()
22 | jcenter()
23 |
24 | }
25 | }
26 |
27 | task clean(type: Delete) {
28 | delete rootProject.buildDir
29 | }
30 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Asutosh11/DocumentReader/66cf501b994ae60b8eeb24feca013569d2d47dac/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Jul 26 21:28:41 IST 2020
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name='DocumentReader'
2 | include ':app'
3 |
--------------------------------------------------------------------------------