Editing pages and documents
Merge, split, insert, delete, rotate, reorder and crop pages, set page backgrounds, and edit text and images with NexPDF for Rust.
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. Editing methods take &mut self. Save with doc.save(path), or
doc.save_linearized_to(path) for a "Fast Web View" file.
Merge and split
use nexpdf_sdk::Document;
fn main() -> nexpdf_sdk::Result<()> {
let mut a = Document::open("a.pdf")?;
let b = Document::open("b.pdf")?;
a.append_document(&b)?; // a now has the pages of a, then b
a.save("merged.pdf")?;
let doc = Document::open("merged.pdf")?;
let first_three = doc.extract_pages(&[0, 1, 2])?; // a new Document
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()?;
doc.insert_image_pages(2, &std::fs::read("scan.jpg")?)?; // one page per picture, before page 2Rotate and crop
doc.rotate_page(0, 90)?; // multiples of 90 degrees
doc.crop_page(1, 36.0, 36.0, 576.0, 756.0)?; // new crop box in PDF pointsPage backgrounds
doc.set_page_background(r##"{"color":"#fbf4e2","pages":[]}"##, &[], 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:
let items = doc.page_content_json_value(0)?; // `serde` feature
let line = items
.as_array()
.into_iter()
.flatten()
.find(|i| i["kind"] == "text" && i["text"].as_str().is_some_and(|t| t.contains("Draft")));
if let Some(id) = line.and_then(|l| l["id"].as_str()) {
doc.edit_text(0, id, r##"{"text":"Final","color":"#111827"}"##)?;
}
doc.add_page_text(0, r##"{"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