I have made an application which capture images through camera and convert them into pdf file. Now the problem is that the pdf is getting stored in my app data as according to latest storage update in android 11 we can't make new folder outside the app data. So now I want to store my pdf file into Downloads folder which comes under shared storage so that it doesn't delete if I uninstall the app. Here is the code through which I was storing the pdf file in app's data:
private fun CreatePdf(list: ArrayList<Bitmap>){
val file: File?=getOutputFile()
if (file != null) {
try {
val fileOutputStream = FileOutputStream(file)
val document = PDDocument()
for(i in 0 until list.size) {
val page = PDPage(A4)
document.addPage(page)
val contentStream = PDPageContentStream(document, page)
val ximage = JPEGFactory.createFromImage(document, list[i], 1f)
contentStream.drawImage(ximage, 0f, 0f)
contentStream.close()
}
document.save(fileOutputStream)
document.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
private fun getOutputFile(): File?{
val root: File = File(getExternalFilesDir(null),"my file")
var isFolderCreated = true
if (!root.exists()) {
isFolderCreated = root.mkdir()
}
return if (isFolderCreated) {
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
val imageFileName = "PDF_$timeStamp"
File(root, "$imageFileName.pdf")
} else {
Toast.makeText(this, "Folder is not created", Toast.LENGTH_SHORT).show()
null
}
}
try this
var relativePath = Environment.DIRECTORY_DOWNLOADS
if (hasSubFolder) {
relativePath += File.separator + yourSubFolderName
}
val fileName: String = yourFileName
val values = ContentValues()
values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
values.put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath)
val cr = context.contentResolver
val uri = cr.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
uri?.let {
val outputStream = cr.openOutputStream(uri)
document.save(outputStream)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.