Skip to Content
NexPDF

Editing pages and documents

Merge, split, insert, delete, rotate, reorder and crop pages, set page backgrounds, and edit text and images with NexPDF for Android.

English

License module

Page and content editing needs the editor module (Startup tier and above). Inserting pictures as pages needs no module.

Page indices start at 0. Every call below is a static method of NexPdfJni that takes doc.handle(). Save with doc.saveBytes(). The reader offers a page editor and content editing to the user.

Merge and split

import com.nexdevit.nexpdf.NexPdfDocument
import com.nexdevit.nexpdf.NexPdfJni

NexPdfDocument.openBytes(aBytes).use { a ->
    NexPdfDocument.openBytes(bBytes).use { b ->
        NexPdfJni.appendDocument(a.handle(), b.handle())   // a now has the pages of a, then b
    }
    val merged = a.saveBytes()

    // extractPages returns a new native handle (0 on failure); free it yourself.
    val part = NexPdfJni.extractPages(a.handle(), intArrayOf(0, 1, 2))
    try {
        val firstThree = NexPdfJni.saveBytes(part)
    } finally {
        NexPdfJni.free(part)
    }
}

Insert, duplicate, delete and reorder

val h = doc.handle()
NexPdfJni.addBlankPage(h)              // appends a blank page
NexPdfJni.duplicatePage(h, 0)          // inserts a copy of page 0 after it
NexPdfJni.movePage(h, 3, 0)            // moves page 3 to the front
NexPdfJni.deletePage(h, 5)
NexPdfJni.reversePages(h)

NexPdfJni.insertImagePages(h, 2, jpegBytes)   // one page per picture, before page 2

Rotate and crop

NexPdfJni.rotatePage(h, 0, 90)                         // multiples of 90 degrees
NexPdfJni.cropPage(h, 1, 36.0, 36.0, 576.0, 756.0)     // new crop box in PDF points

Page backgrounds

NexPdfJni.setPageBackground(h, """{"color":"#fbf4e2","pages":[]}""", null, 0, 0)   // every page
NexPdfJni.removePageBackground(h, null)

Pass RGB pixels (width x height x 3 bytes) with their size to use a picture, and "fit" (cover, stretch or center), "scale" and "opacity" in the options.

Edit page text and images

pageContentJson(handle, page) lists the text lines and images of a page with an id for each:

val items = JSONArray(NexPdfJni.pageContentJson(h, 0))
val line = (0 until items.length()).map { items.getJSONObject(it) }
    .first { it.getString("kind") == "text" && it.optString("text").contains("Draft") }

NexPdfJni.editText(h, 0, line.getString("id"), """{"text":"Final","color":"#111827"}""")
NexPdfJni.addPageText(h, 0, """{"text":"Approved","x":72,"y":60,"size":14,"color":"#16A34A","bold":true}""")

Ids stay valid until the next edit of that page, so read the content again after each change. For images use transformImage(handle, page, id, llx, lly, urx, ury) to move or resize, replaceImage(handle, page, id, rgb, width, height) to swap the picture and deleteContent(handle, page, id) to remove it.

On this page