0

in my App I print some parts to a pdf for the user. I do this by using a PrintedPdfDocument.

The code looks in short like this:

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

It all works fine. However now I want to add another page at the end. Only exception is that this will be a pre-generated pdf file from the assets. I only need to append it so no additional rendering etc. should be necessary.

Is there any way of doing this via the PdfDocument class from the Android SDK?

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

I assumed it might be a similar question like this here: how can i combine multiple pdf to convert single pdf in android?

But is this true? The answer was not accepted and is 3 years old. Any suggestions?

Tobias Reich
  • 4,414
  • 2
  • 42
  • 77

1 Answers1

0

Alright, I gonna answer my own question here.

It looks like there are not many options. At least I couldn't find anything native. There are some pdf libraries in the Android framework but they all seem to support only creating new pages but no operations on existing documents.

So this is what I did:

First of all there don't seem to be any good Android libraries. I found that one here which prepared the Apache PDF-Box for Android. Add this to your Gradle file:

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

In code you can now import

import com.tom_roush.pdfbox.multipdf.PDFMergerUtility

Where I added a method

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)

That way the appendix page is loaded from the assets and appended at the end of the document. It then gets written back to the same file as it was before.

Tobias Reich
  • 4,414
  • 2
  • 42
  • 77