Editing pages and documents
Merge, split, insert, delete, rotate, reorder and crop pages, set page backgrounds, and edit text and images with NexPDF for .NET.
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. SaveBytes() returns the file in memory.
Merge and split
using (var a = NexPdfDocument.Open("a.pdf"))
using (var b = NexPdfDocument.Open("b.pdf"))
{
a.AppendDocument(b); // a now has the pages of a, then b
a.Save("merged.pdf");
}
using var doc = NexPdfDocument.Open("merged.pdf");
using (var firstThree = doc.ExtractPages(new uint[] { 0, 1, 2 }))
firstThree.Save("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, File.ReadAllBytes("scan.jpg")); // one page per picture, before page 2Rotate and crop
doc.RotatePage(0, 90); // multiples of 90 degrees
doc.CropPage(1, 36, 36, 576, 756); // new crop box in PDF pointsPage backgrounds
doc.SetPageBackground("""{"color":"#fbf4e2","pages":[]}""", Array.Empty<byte>(), 0, 0); // every page
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:
using System.Text.Json.Nodes;
var line = JsonNode.Parse(doc.PageContentJson(0))!.AsArray()
.First(i => i!["kind"]!.GetValue<string>() == "text" && i["text"]!.GetValue<string>().Contains("Draft"))!;
doc.EditText(0, line["id"]!.GetValue<string>(), """{"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.
Related
- Document structure: metadata, bookmarks, page labels and attachments
- Compare and optimise: compare versions and make files smaller