将base64字符串转换为pdf



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

我的问题是,我不知道如何创建路径后,我解码base64字符串的文件,然后使用路径打开文件与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()
}

尝试下面的代码,希望这将为您工作。除了代码,您还需要创建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, fileProviderAuthority, 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"
}

最新更新