How to Add Pages from One PDF to Another in Python
2 min readJan 4, 2023
Having the flexibility to mix and match PDF contents can make your file processing workflow that much more efficient. Using the below API solution, you can quickly copy a specific range of pages from one PDF document file into another with ease — and with only a few lines of copy & paste, ready-to-run Python code. You’ll just need to specify the following details before making your call:
- sourceFile & destinationFile
- pageStartSource (first page from sourceFile to begin copying from)
- pageEndSource (final page from sourceFile to begin copying from)
- pageInsertBeforeDestination (destinationFile page; sourceFile page range will be added before this value)
- API key (required to complete API call; you can get one for free here with a limit of 800 API calls per month)
To begin making your API call, first run the below command to install the Python SDK:
pip install cloudmersive-convert-api-client
Next, copy in the remaining code examples, starting with the imports:
from __future__ import print_function
import time
import cloudmersive_convert_api_client
from cloudmersive_convert_api_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: Apikey
configuration = cloudmersive_convert_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'
# create an instance of the API class
api_instance = cloudmersive_convert_api_client.EditPdfApi(cloudmersive_convert_api_client.ApiClient(configuration))
source_file = '/path/to/inputfile' # file | Source PDF file to copy pages from.
destination_file = '/path/to/inputfile' # file | Destination PDF file to copy pages into.
page_start_source = 56 # int | Page number (1 based) to start copying pages from (inclusive) in the Source file.
page_end_source = 56 # int | Page number (1 based) to stop copying pages pages from (inclusive) in the Source file.
page_insert_before_desitnation = 56 # int | Page number (1 based) to insert the pages before in the Destination file.
try:
# Insert, copy pages from one PDF document into another
api_response = api_instance.edit_pdf_insert_pages(source_file, destination_file, page_start_source, page_end_source, page_insert_before_desitnation)
pprint(api_response)
except ApiException as e:
print("Exception when calling EditPdfApi->edit_pdf_insert_pages: %s\n" % e)