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 PDF 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 PDF 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 PDF document using ‘ap.Document()’.
- Insert a new empty page at a specific index using ‘document.pages.insert(index)’.
- Save the modified document using ‘document.save()’ to 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 PDF document using ‘ap.Document()’.
- Add a new empty page to the end of the document using ‘document.pages.add()’.
- Save the updated PDF file using ‘document.save()’.
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 PDF, add an initial page, and then import a page from another PDF into it.
- Create a new PDF document.
- Add a new blank page and write some text on it.
- Open another existing PDF - ‘input_file_name’.
- Copy a page from that document.
- Paste the copied page into your main document.
- Save the combined file as ‘output_file_name’.
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)