Insert a page into a PDF document
Insert one or more pages into an existing document
See our public API Reference and quickly try our APIs using the Postman collections
REST API
Node js
.Net
Java
Python
Copied to your clipboard// Please refer our Rest API docs for more information// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDFcurl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \--header 'x-api-key: {{Placeholder for client_id}}' \--header 'Content-Type: application/json' \--header 'Authorization: Bearer {{Placeholder for token}}' \--data-raw '{"assets": [{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 1,"end": 1}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 4}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 1}]},{"assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718","pageRanges": [{"start": 2}]}]}'// Legacy API can be found here// https://documentcloud.adobe.com/document-services/index.html#post-combinePDF
Copied to your clipboard// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample// Run the sample:// node src/insertpages/insert-pdf-pages.jsconst {ServicePrincipalCredentials,PDFServices,MimeType,PageRanges,InsertPagesParams,InsertPagesJob,InsertPagesResult,SDKError,ServiceUsageError,ServiceApiError} = require("@adobe/pdfservices-node-sdk");const fs = require("fs");(async () => {let baseReadStream;let firstReadStreamToInsert;let secondReadStreamToInsert;try {// Initial setup, create credentials instanceconst credentials = new ServicePrincipalCredentials({clientId: process.env.PDF_SERVICES_CLIENT_ID,clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET});// Creates a PDF Services instanceconst pdfServices = new PDFServices({credentials});// Creates an asset(s) from source file(s) and uploadbaseReadStream = fs.createReadStream("./baseInput.pdf");firstReadStreamToInsert = fs.createReadStream("./firstFileToInsertInput.pdf");secondReadStreamToInsert = fs.createReadStream("./secondFileToInsertInput.pdf");const [baseAsset, firstAssetToInsert, secondAssetToInsert] = await pdfServices.uploadAssets({streamAssets: [{readStream: baseReadStream,mimeType: MimeType.PDF}, {readStream: firstReadStreamToInsert,mimeType: MimeType.PDF}, {readStream: secondReadStreamToInsert,mimeType: MimeType.PDF}]});// Create parameters for the jobconst params = new InsertPagesParams(baseAsset)// Add the first asset as input to the params, along with its page ranges and base page.addPagesToInsertAt({inputAsset: firstAssetToInsert,pageRanges: getPageRangesForFirstFile(),basePage: 2})// Add the second asset as input to the params, along with base page.addPagesToInsertAt({inputAsset: secondAssetToInsert,basePage: 3});// Create a new job instanceconst job = new InsertPagesJob({params});// Submit the job and get the job resultconst pollingURL = await pdfServices.submit({job});const pdfServicesResponse = await pdfServices.getJobResult({pollingURL,resultType: InsertPagesResult});// Get content from the resulting asset(s)const resultAsset = pdfServicesResponse.result.asset;const streamAsset = await pdfServices.getContent({asset: resultAsset});// Creates an output stream and copy result asset's content to itconst outputFilePath = "./insertPagesOutput.pdf";console.log(`Saving asset at ${outputFilePath}`);const outputStream = fs.createWriteStream(outputFilePath);streamAsset.readStream.pipe(outputStream);} catch (err) {if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {console.log("Exception encountered while executing operation", err);} else {console.log("Exception encountered while executing operation", err);}} finally {baseReadStream?.destroy();firstReadStreamToInsert?.destroy();secondReadStreamToInsert?.destroy();}})();
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples// Run the sample:// cd InsertPDFPages/// dotnet run InsertPDFPages.csprojnamespace InsertPDFPages{class Program{private static readonly ILog log = LogManager.GetLogger(typeof(Program));static void Main(){// Configure the loggingConfigureLogging();try{// Initial setup, create credentials instance.Credentials credentials = Credentials.ServicePrincipalCredentialsBuilder().WithClientId("PDF_SERVICES_CLIENT_ID").WithClientSecret("PDF_SERVICES_CLIENT_SECRET").Build();// Create an ExecutionContext using credentials.ExecutionContext executionContext = ExecutionContext.Create(credentials);// Create a new operation instanceInsertPagesOperation insertPagesOperation = InsertPagesOperation.CreateNew();// Set operation base input from a source file.FileRef baseSourceFile = FileRef.CreateFromLocalFile(@"baseInput.pdf");insertPagesOperation.SetBaseInput(baseSourceFile);// Create a FileRef instance using a local file.FileRef firstFileToInsert = FileRef.CreateFromLocalFile(@"firstFileToInsertInput.pdf");PageRanges pageRanges = GetPageRangeForFirstFile();// Adds the pages (specified by the page ranges) of the input PDF file to be inserted at the specified page of the base PDF file.insertPagesOperation.AddPagesToInsertAt(firstFileToInsert, pageRanges, 2);// Create a FileRef instance using a local file.FileRef secondFileToInsert = FileRef.CreateFromLocalFile(@"secondFileToInsertInput.pdf");// Adds all the pages of the input PDF file to be inserted at the specified page of the base PDF file.insertPagesOperation.AddPagesToInsertAt(secondFileToInsert, 3);// Execute the operation.FileRef result = insertPagesOperation.Execute(executionContext);// Save the result to the specified location.result.SaveAs(Directory.GetCurrentDirectory() + "/output/insertPagesOutput.pdf");}catch (ServiceUsageException ex){log.Error("Exception encountered while executing operation", ex);// Catch more errors here . . .}private static PageRanges GetPageRangeForFirstFile(){// Specify which pages of the first file are to be inserted in the base file.PageRanges pageRanges = new PageRanges();// Add pages 1 to 3.pageRanges.AddRange(1, 3);// Add page 4.pageRanges.AddSinglePage(4);return pageRanges;}static void ConfigureLogging(){ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));}}}
Copied to your clipboard// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples// Run the sample:// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.insertpages.InsertPDFPagespublic class InsertPDFPages {// Initialize the logger.private static final Logger LOGGER = LoggerFactory.getLogger(InsertPDFPages.class);public static void main(String[] args) {try (InputStream baseInputStream = Files.newInputStream(new File("src/main/resources/baseInput.pdf").toPath());InputStream firstInputStreamToInsert = Files.newInputStream(new File("src/main/resources/firstFileToInsertInput.pdf").toPath());InputStream secondInputStreamToInsert = Files.newInputStream(new File("src/main/resources/secondFileToInsertInput.pdf").toPath())) {// Initial setup, create credentials instanceCredentials credentials = new ServicePrincipalCredentials(System.getenv("PDF_SERVICES_CLIENT_ID"),System.getenv("PDF_SERVICES_CLIENT_SECRET"));// Creates a PDF Services instancePDFServices pdfServices = new PDFServices(credentials);// Creates an asset(s) from source file(s) and uploadAsset baseAsset = pdfServices.upload(baseInputStream, PDFServicesMediaType.PDF.getMediaType());Asset firstAssetToInsert = pdfServices.upload(firstInputStreamToInsert, PDFServicesMediaType.PDF.getMediaType());Asset secondAssetToInsert = pdfServices.upload(secondInputStreamToInsert, PDFServicesMediaType.PDF.getMediaType());PageRanges pageRanges = getPageRangeForFirstFile();// Create parameters for the jobInsertPagesParams insertPagesParams = InsertPagesParams.insertPagesParamsBuilder(baseAsset).addPagesToInsertAt(firstAssetToInsert, pageRanges, 2) // Add the first asset as input to the params, along with its page ranges and base page.addPagesToInsertAt(secondAssetToInsert, 3) // Add the seccond asset as input to the params, along with base page.build();// Creates a new job instanceInsertPagesPDFJob insertPagesJob = new InsertPagesPDFJob(insertPagesParams);// Submit the job and gets the job resultString location = pdfServices.submit(insertPagesJob);PDFServicesResponse<InsertPagesResult> pdfServicesResponse = pdfServices.getJobResult(location, InsertPagesResult.class);// Get content from the resulting asset(s)Asset resultAsset = pdfServicesResponse.getResult().getAsset();StreamAsset streamAsset = pdfServices.getContent(resultAsset);// Creates an output stream and copy stream asset's content to itFiles.createDirectories(Paths.get("output/"));OutputStream outputStream = Files.newOutputStream(new File("output/insertPagesOutput.pdf").toPath());LOGGER.info("Saving asset at output/insertPagesOutput.pdf");IOUtils.copy(streamAsset.getInputStream(), outputStream);outputStream.close();} catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {LOGGER.error("Exception encountered while executing operation", e);}}private static PageRanges getPageRangeForFirstFile() {// Specify which pages of the first file are to be inserted in the base filePageRanges pageRanges = new PageRanges();// Add pages 1 to 3pageRanges.addRange(1, 3);// Add page 4.pageRanges.addSinglePage(4);return pageRanges;}}
Copied to your clipboard# Get the samples from https://github.com/adobe/pdfservices-python-sdk-samples# Run the sample:# python src/insertpages/insert_pdf_pages.py# Initialize the loggerlogging.basicConfig(level=logging.INFO)class InsertPDFPages:def __init__(self):try:base_file = open("baseInput.pdf", "rb")base_input_stream = base_file.read()base_file.close()first_file_to_insert = open("firstFileToInsertInput.pdf", "rb")first_input_stream_to_insert = first_file_to_insert.read()first_file_to_insert.close()second_file_to_insert = open("secondFileToInsertInput.pdf", "rb")second_input_stream_to_insert = second_file_to_insert.read()second_file_to_insert.close()# Initial setup, create credentials instancecredentials = ServicePrincipalCredentials(client_id=os.getenv("PDF_SERVICES_CLIENT_ID"),client_secret=os.getenv("PDF_SERVICES_CLIENT_SECRET"),)# Creates a PDF Services instancepdf_services = PDFServices(credentials=credentials)# Creates an asset(s) from source file(s) and uploadbase_asset = pdf_services.upload(input_stream=base_input_stream, mime_type=PDFServicesMediaType.PDF)first_asset_to_insert = pdf_services.upload(input_stream=first_input_stream_to_insert,mime_type=PDFServicesMediaType.PDF,)second_asset_to_insert = pdf_services.upload(input_stream=second_input_stream_to_insert,mime_type=PDFServicesMediaType.PDF,)page_ranges = self.get_page_range_for_first_file()# Create parameters for the jobinsert_pages_params = InsertPagesParams(base_asset=base_asset)# Add the first asset as input to the params, along with its page ranges and base pageinsert_pages_params.add_pages_to_insert(input_asset=first_asset_to_insert, page_ranges=page_ranges, base_page=2)# Add the second asset as input to the params, along with base pageinsert_pages_params.add_pages_to_insert(input_asset=second_asset_to_insert, base_page=3)# Creates a new job instanceinsert_pages_job = InsertPagesJob(insert_pages_params=insert_pages_params)# Submit the job and gets the job resultlocation = pdf_services.submit(insert_pages_job)pdf_services_response = pdf_services.get_job_result(location, InsertPagesResult)# Get content from the resulting asset(s)result_asset: CloudAsset = pdf_services_response.get_result().get_asset()stream_asset: StreamAsset = pdf_services.get_content(result_asset)# Creates an output stream and copy stream asset's content to itoutput_file_path = "insertpagesOutput.pdf"with open(output_file_path, "wb") as file:file.write(stream_asset.get_input_stream())except (ServiceApiException, ServiceUsageException, SdkException) as e:logging.exception(f"Exception encountered while executing operation: {e}")@staticmethoddef get_page_range_for_first_file() -> PageRanges:# Specify which pages of the first file are to be included in the combined filepage_ranges_for_first_file = PageRanges()# Add pages 1 to 3page_ranges_for_first_file.add_range(1, 3)# Add single page 1page_ranges_for_first_file.add_single_page(1)return page_ranges_for_first_fileif __name__ == "__main__":InsertPDFPages()