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 iOS (Swift).

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 write(to:) or saveBytes(), or saveLinearized() for a "Fast Web View" file. The reader offers page editing and content editing to the user.

Merge and split

import NexPdf

let a = try NexPdfDocument.open(url: aURL)
let b = try NexPdfDocument.open(url: bURL)
try a.appendDocument(other: b)                       // a now has the pages of a, then b
try a.write(to: mergedURL)

let firstThree = try a.extractPages(indices: [0, 1, 2])
try firstThree.write(to: part1URL)

Insert, duplicate, delete and reorder

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

try doc.insertImagePages(index: 2, data: jpegData)   // one page per picture, before page 2

Rotate and crop

try doc.rotatePage(pageIndex: 0, degrees: 90)                       // multiples of 90 degrees
try doc.cropPage(pageIndex: 1, llx: 36, lly: 36, urx: 576, ury: 756) // new crop box in PDF points

Page backgrounds

try doc.setPageBackground(optionsJson: #"{"color":"#fbf4e2","pages":[]}"#, rgb: Data(), width: 0, height: 0)
try doc.removePageBackground()

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:

let items = NexPdf.json(try doc.pageContentJson(page: 0)) as? [[String: Any]] ?? []
if let line = items.first(where: { $0["kind"] as? String == "text" && ($0["text"] as? String ?? "").contains("Draft") }),
   let id = line["id"] as? String {
    try doc.editText(page: 0, id: id, changeJson: #"{"text":"Final","color":"#111827"}"#)
}
try doc.addPageText(page: 0, json: #"{"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