Editing pages and documents
Merge, split, insert, delete, rotate, reorder and crop pages, set page backgrounds, and edit text and images with NexPDF for PHP.
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() and saveLinearized() return the bytes instead.
Merge and split
use Nexdevit\NexPdf\Document;
$a = Document::open('a.pdf');
$b = Document::open('b.pdf');
$a->appendDocument($b); // $a now has the pages of a, then b
$a->save('merged.pdf');
$doc = Document::open('merged.pdf');
$firstThree = $doc->extractPages([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_get_contents('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":[]}', '', 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:
$items = json_decode($doc->pageContentJson(0), true);
foreach ($items as $item) {
if ($item['kind'] === 'text' && str_contains($item['text'], 'Draft')) {
$doc->editText(0, $item['id'], '{"text":"Final","color":"#111827"}');
break;
}
}
$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