Move PDF Pages programmatically via Python

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:

  1. Create a Document class object with the source PDF file.
  2. Create a Document class object with the destination PDF file.
  3. Get Page from the the PageCollection collection’s.
  4. add() page to the destination document.
  5. Save the output PDF using the save() method.
  6. delete() page in source document.
  7. 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

  1. Create a Document class object with the source PDF file.
  2. Create a Document class object with the destination PDF file.
  3. Define an array with page numbers to be moved.
  4. Run loop through array:
    1. Get Page from the the PageCollection collection’s.
    2. add() page to the destination document.
  5. Save the output PDF using the save() method.
  6. delete() page in source document using array.
  7. 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

  1. Create a Document class object with the source PDF file.
  2. Get Page from the the PageCollection collection’s.
  3. add() page to the new location (for example to end).
  4. delete() page in previous location.
  5. 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)