Issue
i have a probleme, i want to create a pdf and save him in download path on the phone, but it seems like there is an error and i don't know how to figure it out.
Can anyone help me please ? (I already have the permission for access storage, i think :/ ).
This is my code -->
fun createPdf
fun createPdf(
text: String,
context: Context
) {
val myPDFdocument = PdfDocument()
val myPaint = Paint()
val myPageInfo1 = PdfDocument.PageInfo.Builder(1240, 1754, 1).create()
val myPage1 = myPDFdocument.startPage(myPageInfo1)
val canvas = myPage1.canvas
canvas.drawText(text, 40F, 50F, myPaint)
myPDFdocument.finishPage(myPage1)
val file = File(context.externalCacheDir!!.absolutePath, "/FirstPdf.pdf")
try {
myPDFdocument.writeTo(FileOutputStream(file))
} catch (e: IOException) {
e.printStackTrace()
}
myPDFdocument.close()
}
Solution
I found the problem, here is the solution : (Principaly for android 11)
fun createPdf
val imageCollection =
MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val contentValues = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, "${commande}.pdf")
put(MediaStore.Downloads.MIME_TYPE, "application/pdf")
put(MediaStore.Downloads.IS_PENDING, 1)
}
val itemUri = resolver.insert(imageCollection, contentValues)
try {
Toast.makeText(context, "salut toi", Toast.LENGTH_SHORT).show()
resolver.insert(imageCollection, contentValues)?.also { uri ->
resolver.openOutputStream(uri).use { outputStream ->
myPDFdocument.writeTo(outputStream)
}
}
contentValues.clear()
contentValues.put(MediaStore.Downloads.IS_PENDING, 0)
resolver.update(itemUri!!, contentValues, null, null)
myPDFdocument.close()
} catch (e: IOException) {
e.printStackTrace()
}
Answered By - Mehdi.ncb
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.