-1

如何在 android 中使用预定义的PDF 框架打印 PDF ?

如何Print-Spooler Api用于打印 PDF 文件

4

1 回答 1

0

这段代码对我有用

val printManager = this.getSystemService(Context.PRINT_SERVICE) as PrintManager
            val jobName = this.getString(R.string.app_name) + " Document"
            try{
                printManager.print(jobName, pda, null)
            }
            catch(ex:RuntimeException)
            {
                Toast.makeText(this,"Can't print pdf file",Toast.LENGTH_SHORT).show()
            }

打印文档适配器.kt

  var pda: PrintDocumentAdapter = object : PrintDocumentAdapter() {
    
            override fun onWrite(
                    pages: Array<PageRange>,
                    destination: ParcelFileDescriptor,
                    cancellationSignal: CancellationSignal,
                    callback: WriteResultCallback
            ) {
                var input: InputStream? = null
                var output: OutputStream? = null
                try {
                    input = uri?.let { contentResolver.openInputStream(it) }
    
                    output = FileOutputStream(destination.fileDescriptor)
                    val buf = ByteArray(1024)
                    var bytesRead: Int
                    if (input != null) {
                        while (input.read(buf).also { bytesRead = it } > 0) {
                            output.write(buf, 0, bytesRead)
                        }
                    }
                    callback.onWriteFinished(arrayOf(PageRange.ALL_PAGES))
                } catch (ee: FileNotFoundException) {
                    //Code to Catch FileNotFoundException
                } catch (e: Exception) {
                   //Code to Catch exception
                } finally {
                    try {
                        input!!.close()
                        output!!.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
    
            override fun onLayout(
                    oldAttributes: PrintAttributes,
                    newAttributes: PrintAttributes,
                    cancellationSignal: CancellationSignal,
                    callback: LayoutResultCallback,
                    extras: Bundle
            ) {
                if (cancellationSignal.isCanceled) {
                    callback.onLayoutCancelled()
                    return
                }
                val pdi = PrintDocumentInfo.Builder("Name of file")
                    .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build()
                callback.onLayoutFinished(pdi, true)
            }
        }
于 2021-09-20T16:39:18.147 回答