Editing pages and documents
Merge, split, insert, delete, rotate, reorder and crop pages, set page backgrounds, and edit text and images in the browser with NexPDF for the web.
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. Get the result with doc.toBytes() or doc.toBlob(), or
doc.raw.saveLinearized() for a "Fast Web View" file.
Merge and split
const a = await nex.PdfDocument.fromUrl('/a.pdf');
const b = await nex.PdfDocument.fromUrl('/b.pdf');
a.merge(b); // a now has the pages of a, then b
const merged = a.toBlob();
const firstThree = new nex.PdfDocument(a.raw.extractPages([0, 1, 2]));
const part1 = firstThree.toBlob();Insert, duplicate, delete and reorder
doc.raw.addBlankPage(); // appends a blank page
doc.raw.duplicatePage(0); // inserts a copy of page 0 after it
doc.raw.movePage(3, 0); // moves page 3 to the front
doc.raw.deletePage(5);
doc.raw.reversePages();
const jpg = new Uint8Array(await photo.arrayBuffer());
doc.raw.insertImagePages(2, jpg); // one page per picture, before page 2Rotate and crop
doc.raw.rotatePage(0, 90); // multiples of 90 degrees
doc.raw.cropPage(1, 36, 36, 576, 756); // new crop box in PDF pointsPage backgrounds
doc.setBackground({ color: '#fbf4e2', pages: [] }); // every page
doc.raw.removePageBackground(null);Pass a picture as RGB pixels (width x height x 3 bytes), setBackground(options, { rgb, width, height }),
and fit (cover, stretch or center), scale and opacity in the options.
Edit page text and images
doc.raw.pageContentJson(page) lists the text lines and images of a page with an id for each:
const items = JSON.parse(doc.raw.pageContentJson(0));
const line = items.find((i) => i.kind === 'text' && i.text.includes('Draft'));
doc.raw.editText(0, line.id, JSON.stringify({ text: 'Final', color: '#111827' }));
doc.raw.addPageText(0, JSON.stringify({ 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, all on doc.raw.
Related
- Document structure: metadata, bookmarks, page labels and attachments
- Compare and optimise: compare versions and make files smaller
- Opening and saving: copy a document before editing