How to merge multiple PDF Documents together in Python
2 min readApr 25, 2020
Prepare yourself for the easiest tutorial you’ve ever read. With a little helping hand from an API, we will be setting up our PDF merging with virtually no effort whatsoever. Time to dive in.
We can install our client with pip install, like so:
pip install cloudmersive-convert-api-client
Following our installation, we will be able to call our PDF mergin function, shown below.
from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom cloudmersive_convert_api_client.rest 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.MergeDocumentApi(cloudmersive_convert_api_client.ApiClient(configuration))input_file1 = '/path/to/file' # file | First input file to perform the operation on.input_file2 = '/path/to/file' # file | Second input file to perform the operation on.input_file3 = '/path/to/file' # file | Third input file to perform the operation on. (optional)input_file4 = '/path/to/file' # file | Fourth input file to perform the operation on. (optional)input_file5 = '/path/to/file' # file | Fifth input file to perform the operation on. (optional)input_file6 = '/path/to/file' # file | Sixth input file to perform the operation on. (optional)input_file7 = '/path/to/file' # file | Seventh input file to perform the operation on. (optional)input_file8 = '/path/to/file' # file | Eighth input file to perform the operation on. (optional)input_file9 = '/path/to/file' # file | Ninth input file to perform the operation on. (optional)input_file10 = '/path/to/file' # file | Tenth input file to perform the operation on. (optional)try:# Merge Multple PDF Files Togetherapi_response = api_instance.merge_document_pdf_multi(input_file1, input_file2, input_file3=input_file3, input_file4=input_file4, input_file5=input_file5, input_file6=input_file6, input_file7=input_file7, input_file8=input_file8, input_file9=input_file9, input_file10=input_file10)pprint(api_response)except ApiException as e:print("Exception when calling MergeDocumentApi->merge_document_pdf_multi: %s\n" % e)
As you can see, you may merge up to ten files with one call, and the process may then be chained repeatedly on as many files as you like, with the order preserved.