将字节数组转换为pdf文件然后保存
Converting a byte array to a pdf file then saving it
我正在使用 Kotlin Android 应用访问 API 端点。在这个 API 调用中,我返回一个字节数组。我希望看到的是一种将字节数组转换为 pdf 文件并将其保存在手机下载文件夹中的方法。
private suspend fun getIDCard(sessionID: String?, carriermemid: String?): ByteArray? {
var results: String = ""
val postData = "{\"sessionid\": \" $sessionID\"}"
val outputStreamWriter: OutputStreamWriter
var byteArray: ByteArray? = null
val url: URL = URL(idURL + carriermemid)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
try {
conn.setRequestProperty(apiConfig.typeKey, apiConfig.typeValueJSON)
conn.setRequestProperty("Accept", "application/json")
conn.setRequestProperty("sessionid", sessionID)
conn.requestMethod = apiConfig.methodGet
val responseCode: Int = conn.responseCode
println("Response Code :: $responseCode")
//returning 404
return if (responseCode == HttpURLConnection.HTTP_OK) {// connection ok
var out: ByteArrayOutputStream? = ByteArrayOutputStream()
val `in`: InputStream = conn.inputStream
var bytesRead: Int
val buffer = ByteArray(1024)
while (`in`.read(buffer).also { bytesRead = it } > 0) {
out!!.write(buffer, 0, bytesRead)
}
out!!.close()
byteArray = out.toByteArray()
return byteArray
} else {
return byteArray
}
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
conn.disconnect()
}
return byteArray
}
这将获取Android下载目录并将字节数组写入PDF文件(假设字节数组包含PDF)。将 File.createTempFile 更改为您喜欢的任何文件(您不需要创建临时文件):
fun writeBytesAsPdf(bytes : ByteArray) {
val path = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
var file = File.createTempFile("my_file",".pdf", path)
var os = FileOutputStream(file);
os.write(bytes);
os.close();
}
您还必须将 android.permission.WRITE_EXTERNAL_STORAGE 添加到清单中。
查看,您可以使用:
private const val BUFFER_SIZE = 4 * 1024
private fun copyStreamToFile(inputStream: InputStream, outputFile: File) {
inputStream.use { input ->
val outputStream = FileOutputStream(outputFile)
outputStream.use { output ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
val byteCount = input.read(buffer)
if (byteCount < 0) break
output.write(buffer, 0, byteCount)
}
output.flush()
}
}
}
或
private fun InputStream.saveToFile(file: String) = use { input ->
File(file).outputStream().use { output ->
input.copyTo(output)
}
}
您还应该创建文件。
private fun createFile(context: Context, name: String): File? {
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path
var file = File("$storageDir/$name.pdf")
return storageDir?.let { file }
}
所以这最终解决了这个问题。差点忘了post这个。是 resolveinfo 列表和我授予权限的方式让我通过了,但这里是
try {
val pdfbyte = viewModel.getPDFImage()
val path =
requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
.toString() + File.separator
val fileName = "my_idcard.pdf"
val storageDir =
requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path
var file = File("$storageDir/$fileName")
var os = FileOutputStream(file);
os.write(pdfbyte);
os.close();
val intent = Intent(Intent.ACTION_VIEW)
val uri: Uri = FileProvider.getUriForFile(
requireContext(),
BuildConfig.APPLICATION_ID + ".provider",
file
)
intent.setDataAndType(uri, "application/pdf")
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
val resInfoList: List<ResolveInfo> = requireActivity().getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
for (resolveInfo in resInfoList) {
val packageName = resolveInfo.activityInfo.packageName
requireActivity().grantUriPermission(
packageName,
uri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
)
}
startActivity(intent)
} catch (e: ActivityNotFoundException) {
println("*************************NO PDF**************************")
}
我正在使用 Kotlin Android 应用访问 API 端点。在这个 API 调用中,我返回一个字节数组。我希望看到的是一种将字节数组转换为 pdf 文件并将其保存在手机下载文件夹中的方法。
private suspend fun getIDCard(sessionID: String?, carriermemid: String?): ByteArray? {
var results: String = ""
val postData = "{\"sessionid\": \" $sessionID\"}"
val outputStreamWriter: OutputStreamWriter
var byteArray: ByteArray? = null
val url: URL = URL(idURL + carriermemid)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
try {
conn.setRequestProperty(apiConfig.typeKey, apiConfig.typeValueJSON)
conn.setRequestProperty("Accept", "application/json")
conn.setRequestProperty("sessionid", sessionID)
conn.requestMethod = apiConfig.methodGet
val responseCode: Int = conn.responseCode
println("Response Code :: $responseCode")
//returning 404
return if (responseCode == HttpURLConnection.HTTP_OK) {// connection ok
var out: ByteArrayOutputStream? = ByteArrayOutputStream()
val `in`: InputStream = conn.inputStream
var bytesRead: Int
val buffer = ByteArray(1024)
while (`in`.read(buffer).also { bytesRead = it } > 0) {
out!!.write(buffer, 0, bytesRead)
}
out!!.close()
byteArray = out.toByteArray()
return byteArray
} else {
return byteArray
}
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
conn.disconnect()
}
return byteArray
}
这将获取Android下载目录并将字节数组写入PDF文件(假设字节数组包含PDF)。将 File.createTempFile 更改为您喜欢的任何文件(您不需要创建临时文件):
fun writeBytesAsPdf(bytes : ByteArray) {
val path = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
var file = File.createTempFile("my_file",".pdf", path)
var os = FileOutputStream(file);
os.write(bytes);
os.close();
}
您还必须将 android.permission.WRITE_EXTERNAL_STORAGE 添加到清单中。
查看
private const val BUFFER_SIZE = 4 * 1024
private fun copyStreamToFile(inputStream: InputStream, outputFile: File) {
inputStream.use { input ->
val outputStream = FileOutputStream(outputFile)
outputStream.use { output ->
val buffer = ByteArray(BUFFER_SIZE)
while (true) {
val byteCount = input.read(buffer)
if (byteCount < 0) break
output.write(buffer, 0, byteCount)
}
output.flush()
}
}
}
或
private fun InputStream.saveToFile(file: String) = use { input ->
File(file).outputStream().use { output ->
input.copyTo(output)
}
}
您还应该创建文件。
private fun createFile(context: Context, name: String): File? {
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path
var file = File("$storageDir/$name.pdf")
return storageDir?.let { file }
}
所以这最终解决了这个问题。差点忘了post这个。是 resolveinfo 列表和我授予权限的方式让我通过了,但这里是
try {
val pdfbyte = viewModel.getPDFImage()
val path =
requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
.toString() + File.separator
val fileName = "my_idcard.pdf"
val storageDir =
requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path
var file = File("$storageDir/$fileName")
var os = FileOutputStream(file);
os.write(pdfbyte);
os.close();
val intent = Intent(Intent.ACTION_VIEW)
val uri: Uri = FileProvider.getUriForFile(
requireContext(),
BuildConfig.APPLICATION_ID + ".provider",
file
)
intent.setDataAndType(uri, "application/pdf")
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
val resInfoList: List<ResolveInfo> = requireActivity().getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
for (resolveInfo in resInfoList) {
val packageName = resolveInfo.activityInfo.packageName
requireActivity().grantUriPermission(
packageName,
uri,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
)
}
startActivity(intent)
} catch (e: ActivityNotFoundException) {
println("*************************NO PDF**************************")
}