Adding Pages in PDF with Python
Aspose.PDF for Python via .NET API provides full flexibility to work with pages in a PDF document using Python. It maintains all the pages of a PDF document in PageCollection that can be used to work with PDF pages.
Aspose.PDF for Python via .NET lets you insert a page to a Document at any location in the file as well as add pages to the end of a PDF file. This section shows how to add pages to a PDF using Python.
Add or Insert Page in a PDF File
Aspose.PDF for Python via .NET lets you insert a page to a Document at any location in the file as well as add pages to the end of a PDF file.
Insert Empty Page in a PDF File
To insert an empty page in a PDF file:
- Open an existing
Documentusing appropriate methods. - Insert a new empty page at a specific index using the
PageCollectioninsert()method. - Save the modified
Documentto the desired output path.
Insert an empty page into an existing PDF file at a specified position:
import os
import aspose.pdf as ap
# Global configuration
DATA_DIR = "your path here"
def insert_empty_page(input_file_name, output_file_name):
document = ap.Document(input_file_name)
document.pages.insert(2)
document.save(output_file_name)
Add an Empty Page at the End of a PDF File
Sometimes, you want to ensure that a document ends on an empty page. This topic explains how to insert an empty page at the end of the PDF document.
To insert an empty page at the end of a PDF file:
- Open an existing
Documentusing appropriate methods. - Add a new empty page to the end of the document using the
PageCollectionadd()method. - Save the updated
Document.
The following code snippet shows you how to insert an empty page at the end of a PDF file.
import os
import aspose.pdf as ap
# Global configuration
DATA_DIR = "your path here"
def add_empty_page_to_end(input_file_name, output_file_name):
# Open document
document = ap.Document(input_file_name)
# Insert an empty page at the end of a PDF file
document.pages.add()
# Save output file
document.save(output_file_name)
Add a Page from Another PDF Document
With Aspose.PDF for Python library, you create a new Document, add an initial page, and then import a page from another PDF into it.
- Create a new
Document. - Add a new blank
Pageand write some text on it usingTextFragment. - Open another existing
Document. - Copy a
Pagefrom that document. - Paste the copied page into your main document using
PageCollection. - Save the combined file.
import os
import aspose.pdf as ap
# Global configuration
DATA_DIR = "your path here"
def add_page_from_another_document(input_file_name, output_file_name):
# Open document
document = ap.Document()
page = document.pages.add()
text_fragment = ap.text.TextFragment("This is first page!")
page.paragraphs.add(text_fragment)
another_document = ap.Document(input_file_name)
document.pages.add(another_document.pages[1])
# Save output file
document.save(output_file_name)