Move PDF Pages
Contents
[
Hide
]
Moving a Page from one PDF Document to Another
This topic explains how to move page from one PDF document to the end of another document using PHP. To move an page we should:
- Create a Document class object with the source PDF file
- Create a Document class object with the destination PDF file
- Add the page to the output document. Save the output file
- Delete the page from the input document. Save the modified input document
- Close the documents
- Save, and close the output document
The following code snippet shows you how to move one page.
// Open document
$document = new Document($inputFile1);
$dstDocument = new Document($outputFile);
$page = $document->getPages()->get_Item(2);
$dstDocument->getPages()->add($page);
// Save output file
$dstDocument->save($srcFileName);
$document->getPages()->delete(2);
$document->save($dstFileName);
$document->close();
$dstDocument->close();
// Save output document
$document->save($outputFile);
$document->close();
Moving bunch of Pages from one PDF Document to Another
- Create a Document class object with the source PDF file.
- Create a Document class object with the destination PDF file.
- Define the pages to be copied from the input document to the output document
- Run loop through array:
- Get the page at the specified index from the input document.
- Add page to the destination document.
- Save the output PDF using the Save method.
- Delete page in source document using array.
- Save the source PDF using the Save method.
The following code snippet shows you how to insert an empty page at the end of a PDF file.
// Open document
$document = new Document($inputFile1);
$dstDocument = new Document($outputFile);
$pages = [1, 3 ];
foreach ($pages as $pageIndex) {
$page = $document->getPages()->get_Item($pageIndex);
$dstDocument->getPages()->add(page);
}
// Save output files
$dstDocument->save($srcFileName);
$document->getPages()->delete($pages);
$document->save(dstFileName);
$document->close();
$dstDocument->close();
Moving a Page in new location in the current PDF Document
- Create a Document class object with the source PDF file.
- Get Page from the the pageCollection collection’s.
- Add page to the new location.
- Delete the page at index 2.
- Save the output PDF using the save method.
// Open document
$document = new Document($inputFile);
$pageCollection = $document->getPages();
$page = $pageCollection->get_Item(2);
$pageCollection->add(page);
$pageCollection->delete(2);
// Save output file
$document->save($outputFile);
$document->close();