【问题标题】:Convert base64 string to pdf将base64字符串转换为pdf
【发布时间】:2021-12-13 16:43:06
【问题描述】:

我正在尝试将 base64 字符串转换为 pdf,然后在应用中打开该 pdf 文件。

我的问题是我解码base64 stringm后不知道如何用路径创建文件,然后用pdf阅读器用路径打开文件

到目前为止,我有这个代码:

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

【问题讨论】:

  • 您无法在现代 Android 设备上写入外部存储的根目录。写信给getExternalFilesDir()Context 上的一个方法),然后使用FileProvider 获取UriACTION_VIEW 一起使用。

标签: android kotlin pdf


【解决方案1】:

试试下面的代码,希望这对你有用。除了代码,您需要创建file_provider_paths.xml 并将<provider/> 标签添加到您的AndroidManifest.xml

file_provider_paths.xml

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

创建file_provider_paths.xml并将上述代码放入file_provider_paths.xml文件中

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>

&lt;provider/&gt; 标签放入您的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"
}

【讨论】:

  • 这可行,但如果我使用 getFilesDir() 将其存储在内部存储中,我也可以这样做?
  • 我不确定,但getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) 对我有用。无论如何它会给你内部存储下载文件夹路径。您可以使用getFilesDir() 尝试一次
猜你喜欢
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多