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 Java.

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. Save with doc.save(path), or doc.save(path, true) for a "Fast Web View" file. saveBytes() returns the file in memory.

Merge and split

try (NexPdfDocument a = NexPdfDocument.open(Path.of("a.pdf"));
     NexPdfDocument b = NexPdfDocument.open(Path.of("b.pdf"))) {
    a.appendDocument(b);          // a now has the pages of a, then b
    a.save(Path.of("merged.pdf"));
}

try (NexPdfDocument doc = NexPdfDocument.open(Path.of("merged.pdf"));
     NexPdfDocument firstThree = doc.extractPages(new int[] {0, 1, 2})) {
    firstThree.save(Path.of("part1.pdf"));
}

Insert, duplicate, delete and reorder

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

doc.insertImagePages(2, Files.readAllBytes(Path.of("scan.jpg")));   // one page per picture, before page 2

Rotate and crop

doc.rotatePage(0, 90);                   // multiples of 90 degrees
doc.cropPage(1, 36, 36, 576, 756);       // new crop box in PDF points

Page backgrounds

doc.setPageBackground("{\"color\":\"#fbf4e2\",\"pages\":[]}", new byte[0], 0, 0);   // every page
doc.removePageBackground(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(page) lists the text lines and images of a page with an id for each (parsed here with Jackson, one JSON library among many):

ObjectMapper json = new ObjectMapper();
String id = null;
for (JsonNode item : json.readTree(doc.pageContentJson(0))) {
    if (item.get("kind").asText().equals("text") && item.get("text").asText().contains("Draft")) {
        id = item.get("id").asText();
        break;
    }
}

doc.editText(0, id, "{\"text\":\"Final\",\"color\":\"#111827\"}");
doc.addPageText(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(page, id, llx, lly, urx, ury) to move or resize, replaceImage(page, id, rgb, width, height) to swap the picture and deleteContent(page, id) to remove it.

On this page