简体   繁体   English

使用 Kotlin 在 Android 中创建 PDF 文件

[英]Creating a PDF file in Android using Kotlin

I'm trying to build an Android app that generates a simple PDF documents.我正在尝试构建一个生成简单 PDF 文档的 Android 应用程序。

I wrote this function:我写了这个函数:

    @RequiresApi(Build.VERSION_CODES.KITKAT)
    fun createDocument(text: String) {
        val pdf = PdfDocument()
        val page = pdf.startPage(PdfDocument.PageInfo.Builder(
            100, 100, 1).create())
        val canvas = page.canvas
        val paint = Paint()

        try {
            canvas.drawText(text,20F,30F,paint)
            pdf.finishPage(page)

            val fileName = "doc${System.currentTimeMillis()}.pdf"
            val file = File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), fileName)

            pdf.writeTo(file.outputStream())
            pdf.close()

            Toast.makeText(applicationContext, "$fileName has been created", Toast.LENGTH_SHORT).show()
        }
        catch (e: Exception) {
            Toast.makeText(applicationContext, "Error: ${e.toString()}", Toast.LENGTH_SHORT).show()
        }
    }

When I'm running this code I see the toast message but no file is created, what am I doing wrong?当我运行此代码时,我看到 toast 消息但没有创建文件,我做错了什么?

As CommonsWare and blackapps noted, the document is actually created and saved but in a different location than the one I've looked at.正如CommonsWareblackapps 所指出的,该文档实际上是创建和保存的,但与我查看的位置不同。

The document location is <device-sd> /Android/data/ <app.id> /files/Documents/ <document-name>文档位置为<device-sd> /Android/data/ <app.id> /files/Documents/ <document-name>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM