How to copy Pages from one PDF document to another in Python

Today we are going to set up a system for transferring pages from one PDF document into a different one. To do this, we will be taking what is a relatively straightforward task and making it even easier. Through use of an API, this is going to take mere minutes, you’ll see.

Our first step is to use pip install for the setup of our API client using this command:

pip install cloudmersive-convert-api-client

Next comes our function call, using this code here:

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_convert_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_convert_api_client.EditPdfApi(cloudmersive_convert_api_client.ApiClient(configuration))source_file = '/path/to/file' # file | Source PDF file to copy pages from.destination_file = '/path/to/file' # 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 anotherapi_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)

And there you have it, we’re basically done already. We can specify the range of pages to be copied as well as the destination in the second file. So easy, right? This is just a small taste of what Cloudmersive APIs can do to speed up your workflow.

Image for post
Image for post

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store