Move PDF Pages programmatically via Python
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 Python. 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.
- Get Page from the the PageCollection collection’s.
- add() page to the destination document.
- Save the output PDF using the save() method.
- delete() page in source document.
- Save the source PDF using the save() method.
The following code snippet shows you how to move one page.
import aspose.pdf as ap
srcDocument = ap.Document(src_file_name)
dstDocument = ap.Document(dst_File_name)
page = srcDocument.pages[2]
dstDocument.pages.add(page)
# Save output file
dstDocument.save(dst_File_name_new)
srcDocument.pages.delete(2)
srcDocument.save(src_file_name_new)
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 an array with page numbers to be moved.
- Run loop through array:
- Get Page from the the PageCollection collection’s.
- 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.
import aspose.pdf as ap
srcDocument = ap.Document(input_pdf)
dstDocument = ap.Document()
pages = [1, 3]
for page_index in pages:
page = srcDocument.pages[page_index]
dstDocument.pages.add(page)
# Save output files
dstDocument.save(output_pdf_1)
srcDocument.pages.delete(pages)
srcDocument.save(output_pdf_2)
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 (for example to end).
- delete() page in previous location.
- Save the output PDF using the save() method.
import aspose.pdf as ap
srcDocument = ap.Document(input_pdf)
page = srcDocument.pages[2]
srcDocument.pages.add(page)
srcDocument.pages.delete(2)
# Save output file
srcDocument.save(output_pdf)