我正在嘗試將 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()
}
uj5u.com熱心網友回復:
試試下面的代碼希望這對你有用。除了代碼之外,您還需要創建標簽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>
將<provider/>標簽放入您的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"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/346233.html
