【问题标题】:How to store a pdf file in downloads folder如何将pdf文件存储在下载文件夹中
【发布时间】:2021-04-15 19:20:04
【问题描述】:

我做了一个应用程序,它通过相机捕捉图像并将它们转换为 pdf 文件。现在的问题是,根据 android 11 中的最新存储更新,pdf 正在存储在我的应用数据中,我们无法在应用数据之外创建新文件夹。所以现在我想将我的 pdf 文件存储到共享存储下的下载文件夹中,这样如果我卸载应用程序就不会删除它。这是我将 pdf 文件存储在应用程序数据中的代码:

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

【问题讨论】:

  • 是的..你正在存储..现在..有什么问题?
  • qus 是我如何将它存储在下载中,这样当我卸载应用程序时它不会删除 Pdf 文件。
  • 你的代码没问题。您可以使用相同的代码。您只需要使用不同的路径。下载文件夹的路径。
  • 我想我误解了 SAF 的概念。但我只是想把它保存在下载中,你能指导我吗?我编辑了问题的主题。
  • I just want to save it in downloads ?什么是下载?只有一个下载文件夹。我已经指导你了。使用下载文件夹的路径而不是 getExternalFilesDir。就是这样。

标签: java android kotlin pdf-generation android-11


【解决方案1】:

试试这个

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

【讨论】:

    猜你喜欢
    • 2021-08-28
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多