Android – downloading the PDF from Dropbox to the phone from the given URI in Base64 will cause unreadable PDF corruption
You are reading PDF input bytes (hexadecimal) and storing them in the wrong format (text). For example, all valid PDF files should start with bytes 25 50 44 46. Your alltext content fragment starts with% PDF,% PDF is the converted ASCII / UTF text representation of these bytes
Question: all this is good because we can convert text characters back to their respective byte values, right? No, not all byte values can be recovered correctly from the text format
Example 1: can convert
input bytes : 25 50 44 46
as text : % P D F
into bytes : 25 50 44 46
Example #2: unable to convert (original data cannot be recovered because these bytes have no text characters)
input bytes : 25 C4 E5 F2 E5 EB A7 F3 A0 D0
as text : % � � � � � � � � �
into bytes : 25 00 00 00 00 00 00 00 00 00
Solution:
Try the following similar method. You need logic, as described in the code comments
import java.io.File
import java.io.InputStream
fun main(args: Array<String>)
{
//# setup access to your file...
var inFile :InputStream = File("your-file-path-here.pdf")
var fileSize :Int = File(path).length()
//# read file bytes into a bytes Array...
var inStream :InputStream = inFile.inputStream()
var inBytes :ByteArray = inStream.readBytes()
//# Make as String (of hex values)...
//var hexString :String = ""
val hexString = ""
for (b in inBytes) { hexString = String.format("%02X",b) }
//# check values as hex... should print: 25
//print(hexString) //Could be long print-out for a big file
//# Make Base64 string...
val base64 = Base64.getEncoder().encodeToString(inBytes)
}
(option 1)
Try to convert the hexstring in the above example code to Base64 (Note: it has now been added as Val Base64)
(option 2)
Use the simple... To directly read the file bytes as a Base64 string
val bytes = File(filePath).readBytes()
val base64 = Base64.getEncoder().encodeToString(bytes)