在pdf中编写画布并将其保存在存储android工作室中,不起作用



我有一个问题,我想创建一个PDF并保存在手机上的下载路径,但似乎有一个错误,我不知道如何解决。

有谁能帮帮我吗?(我已经有访问存储的权限,我想:/).

这是我的代码——>

有趣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()
}

我发现了问题,这里是解决方案:(主要针对android 11)

有趣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()
}

最新更新