【问题标题】:Write canvas in pdf and save it in storage android studio, doesn't work用pdf写canvas并将其保存在storage android studio中,不起作用
【发布时间】:2021-10-22 02:35:04
【问题描述】:

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

谁能帮帮我? (我认为我已经拥有访问存储的权限:/)。

这是我的代码 -->

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

【问题讨论】:

    标签: android kotlin pdf canvas local-storage


    【解决方案1】:

    我发现了问题,这里是解决方案:(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()
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-26
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-01
      相关资源
      最近更新 更多