Android - 将额外的 pdf 页面附加到 PrintedPdfDocument

时间:2021-04-01 08:59:36

标签: android pdf pdfdocument

在我的应用程序中,我将一些部分打印为用户的 pdf。我通过使用 PrintedPdfDocument 来做到这一点。

代码如下所示:

    // create a new document
    val printAttributes = PrintAttributes.Builder()
            .setMediaSize(mediaSize)
            .setColorMode(PrintAttributes.COLOR_MODE_COLOR)
            .setMinMargins(PrintAttributes.Margins.NO_MARGINS)
            .build()
    val document = PrintedPdfDocument(context, printAttributes)

    // add pages
    for ((n, pdfPageView) in pdfPages.withIndex()) {
        val page = document.startPage(n)
        Timber.d("Printing page " + (n + 1))
        pdfPageView.draw(page.canvas)
        document.finishPage(page)
    }

    // write the document content
    try {
        val out: OutputStream = FileOutputStream(outputFile)
        document.writeTo(out)
        out.close()
        Timber.d("PDF written to $outputFile")
    } catch (e: IOException) {
        return
    }

一切正常。但是现在我想在最后添加另一个页面。唯一的例外是这将是从资产中预先生成的 pdf 文件。 我只需要附加它所以不需要额外的渲染等。

有没有办法通过 Android SDK 中的 PdfDocument 类来做到这一点?

https://developer.android.com/reference/android/graphics/pdf/PdfDocument#finishPage(android.graphics.pdf.PdfDocument.Page)

我认为这可能是一个类似的问题:how can i combine multiple pdf to convert single pdf in android?

但这是真的吗?答案没有被接受,已经3岁了。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

好的,我要在这里回答我自己的问题。

看起来选项不多。至少我找不到任何本土的东西。 Android 框架中有一些pdf 库,但它们似乎都只支持创建新页面,但不支持对现有文档进行操作。

所以这就是我所做的:

首先,似乎没有任何好的 Android 库。我在这里找到了一个为Android准备的Apache PDF-Box。将此添加到您的 Gradle 文件中:

implementation 'com.tom_roush:pdfbox-android:1.8.10.3'

您现在可以在代码中导入

import com.tom_roush.pdfbox.multipdf.PDFMergerUtility

我添加方法的地方

val ut = PDFMergerUtility()
ut.addSource(file)

val assetManager: AssetManager = context.assets
var inputStream: InputStream? = null
try {
    inputStream = assetManager.open("appendix.pdf")
    ut.addSource(inputStream)
} catch (e: IOException) {
    ...
}

// Write the destination file over the original document
ut.destinationFileName = file.absolutePath
ut.mergeDocuments(true)

通过这种方式,从资产加载附录页面并附加到文档的末尾。 然后它会被写回与之前相同的文件。

相关问题