Home > other >  Convert base64 string to pdf
Convert base64 string to pdf

Time:10-29

I'm trying to convert from a base64 string to pdf and then open that pdf file in the app.

My problem is that i don't know how to create the file with the path after I decode the base64 stringm, and then use the path to open the file with pdf reader

Until now I have this code:

  private fun pdfConverter(file: DtoSymptomPdf?) {
    val dwldsPath: File = File(Environment.getExternalStorageDirectory().absolutePath   "/"   file?.filename   ".pdf")
    val pdfAsBytes: ByteArray = android.util.Base64.decode(file?.file, 0)
    val os = FileOutputStream(dwldsPath, false)
    os.write(pdfAsBytes)
    os.flush()
    os.close()
}

CodePudding user response:

Try the below code hope this will work for you. Apart from the code, you need to create file_provider_paths.xml and add <provider/> tag into your AndroidManifest.xml

file_provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external_files"
        path="." />
</paths>

Create file_provider_paths.xml and put the above code into file_provider_paths.xml file

AndroidManifest.xml

    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true"
        tools:replace="android:authorities">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_provider_paths"
            tools:replace="android:resource" />
    </provider>

Put the <provider/> tag into your AndroidManifest.xml

MainActivity.kt

fun generatePDFFromBase64(base64: String, fileName: String) {
    try {
        val decodedBytes: ByteArray = Base64.decode(base64, Base64.DEFAULT)
        val fos = FileOutputStream(getFilePath(fileName))
        fos.write(decodedBytes)
        fos.flush()
        fos.close()

        openDownloadedPDF(fileName)
    } catch (e: IOException) {
        Log.e("TAG", "Faild to generate pdf from base64: ${e.localizedMessage}")
    }
}

private fun openDownloadedPDF(fileName: String) {
    val file = File(getFilePath(fileName))

    if (file.exists()) {
        val fileProviderAuthority = "{APPLICATION_ID}.fileprovider"
        val path: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            FileProvider.getUriForFile(context, mFileProviderAuthority, file)
        } else {
            Uri.fromFile(file)
        }

        val intent = Intent(Intent.ACTION_VIEW)
        intent.setDataAndType(path, "application/pdf")
        intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_GRANT_READ_URI_PERMISSION
        val chooserIntent = Intent.createChooser(intent, "Open with")
        try {
            startActivity(chooserIntent)
        } catch (e: ActivityNotFoundException) {
            Log.e("TAG", "Failed to open PDF  ${e.localizedMessage}")
        }
    }
}

fun getFilePath(filename: String): String {
    val file =
        File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path)
    if (!file.exists()) {
        file.mkdirs()
    }
    return file.absolutePath.toString()   "/"   filename   ".pdf"
}
  • Related