Editing pages and documents
Merge, split, insert, delete, rotate, reorder and crop pages, set page backgrounds, and edit text and images with NexPDF for Python.
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, linearized=True) for a
"Fast Web View" file.
Merge and split
import nexpdf
with nexpdf.Document.open("a.pdf") as a, nexpdf.Document.open("b.pdf") as b:
a.append_document(b) # a now has the pages of a, then b
a.save("merged.pdf")
with nexpdf.Document.open("merged.pdf") as doc:
with doc.extract_pages([0, 1, 2]) as first_three:
first_three.save("part1.pdf")Insert, duplicate, delete and reorder
doc.add_blank_page() # appends a blank page
doc.duplicate_page(0) # inserts a copy of page 0 after it
doc.move_page(3, 0) # moves page 3 to the front
doc.delete_page(5)
doc.reverse_pages()
with open("scan.jpg", "rb") as f:
doc.insert_image_pages(2, f.read()) # one page per picture, before page 2Rotate and crop
doc.rotate_page(0, 90) # multiples of 90 degrees
doc.crop_page(1, 36, 36, 576, 756) # new crop box in PDF pointsPage backgrounds
doc.set_page_background('{"color":"#fbf4e2","pages":[]}', b"", 0, 0) # every page
doc.remove_page_background(None)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
page_content_json(page) lists the text lines and images of a page with an id for each:
items = nexpdf.loads(doc.page_content_json(0))
line = next(i for i in items if i["kind"] == "text" and "Draft" in i["text"])
doc.edit_text(0, line["id"], '{"text":"Final","color":"#111827"}')
doc.add_page_text(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 transform_image(page, id, llx, lly, urx, ury) to move or resize,
replace_image(page, id, rgb, width, height) to swap the picture and delete_content(page, id) to
remove it.
Related
- Document structure: metadata, bookmarks, page labels and attachments
- Compare and optimise: compare versions and make files smaller