Combine PDF Files
Combine two or more documents into a single PDF file
REST API
See our public API Reference for Combine PDF
Combine Files
This sample combines up to 20 PDF files into a single PDF file.
Please refer the API usage guide to understand how to use our APIs.
Java
.NET
Node JS
REST API
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples2// Run the sample:3// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.combinepdf.CombinePDF45 public class CombinePDF {67 // Initialize the logger.8 private static final Logger LOGGER = LoggerFactory.getLogger(CombinePDF.class);910 public static void main(String[] args) {11 try (InputStream inputStream1 = Files.newInputStream(new File("src/main/resources/combineFilesInput1.pdf").toPath());12 InputStream inputStream2 = Files.newInputStream(new File("src/main/resources/combineFilesInput2.pdf").toPath())) {13 // Initial setup, create credentials instance14 Credentials credentials = new ServicePrincipalCredentials(15 System.getenv("PDF_SERVICES_CLIENT_ID"),16 System.getenv("PDF_SERVICES_CLIENT_SECRET"));1718 // Creates a PDF Services instance19 PDFServices pdfServices = new PDFServices(credentials);2021 // Creates an asset(s) from source file(s) and upload22 List<StreamAsset> streamAssets = new ArrayList<>();23 streamAssets.add(new StreamAsset(inputStream1, PDFServicesMediaType.PDF.getMediaType()));24 streamAssets.add(new StreamAsset(inputStream2, PDFServicesMediaType.PDF.getMediaType()));25 List<Asset> assets = pdfServices.uploadAssets(streamAssets);2627 // Create parameters for the job28 CombinePDFParams combinePDFParams = CombinePDFParams.combinePDFParamsBuilder()29 .addAsset(assets.get(0))30 .addAsset(assets.get(1))31 .build();3233 // Creates a new job instance34 CombinePDFJob combinePDFJob = new CombinePDFJob(combinePDFParams);3536 // Submit the job and gets the job result37 String location = pdfServices.submit(combinePDFJob);38 PDFServicesResponse<CombinePDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CombinePDFResult.class);3940 // Get content from the resulting asset(s)41 Asset resultAsset = pdfServicesResponse.getResult().getAsset();42 StreamAsset streamAsset = pdfServices.getContent(resultAsset);4344 // Creates an output stream and copy stream asset's content to it45 Files.createDirectories(Paths.get("output/"));46 OutputStream outputStream = Files.newOutputStream(new File("output/combineFilesOutput.pdf").toPath());47 LOGGER.info("Saving asset at output/combineFilesOutput.pdf");48 IOUtils.copy(streamAsset.getInputStream(), outputStream);49 outputStream.close();50 } catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {51 LOGGER.error("Exception encountered while executing operation", e);52 }53 }54 }55
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd CombinePDF/4// dotnet run CombinePDF.csproj56 namespace CombinePDF7 {8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));11 static void Main()12 {13 //Configure the logging14 ConfigureLogging();15 try16 {17 // Initial setup, create credentials instance.18 Credentials credentials = Credentials.ServicePrincipalCredentialsBuilder()19 .WithClientId("PDF_SERVICES_CLIENT_ID")20 .WithClientSecret("PDF_SERVICES_CLIENT_SECRET")21 .Build();2223 //Create an ExecutionContext using credentials and create a new operation instance.24 ExecutionContext executionContext = ExecutionContext.Create(credentials);25 CombineFilesOperation combineFilesOperation = CombineFilesOperation.CreateNew();2627 // Add operation input from source files.28 FileRef combineSource1 = FileRef.CreateFromLocalFile(@"combineFilesInput1.pdf");29 FileRef combineSource2 = FileRef.CreateFromLocalFile(@"combineFilesInput2.pdf");30 combineFilesOperation.AddInput(combineSource1);31 combineFilesOperation.AddInput(combineSource2);3233 // Execute the operation.34 FileRef result = combineFilesOperation.Execute(executionContext);3536 // Save the result to the specified location.37 result.SaveAs(Directory.GetCurrentDirectory() + "/output/combineFilesOutput.pdf");3839 }40 catch (ServiceUsageException ex)41 {42 log.Error("Exception encountered while executing operation", ex);43 }44 // Catch more errors here. . .45 }4647 static void ConfigureLogging()48 {49 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());50 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));51 }52 }53 }
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/combinepdf/combine-pdf.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 MimeType,9 CombinePDFJob,10 CombinePDFParams,11 CombinePDFResult,12 SDKError,13 ServiceUsageError,14 ServiceApiError15} = require("@adobe/pdfservices-node-sdk");16const fs = require("fs");1718(async () => {19 let readStream1;20 let readStream2;21 try {22 // Initial setup, create credentials instance23 const credentials = new ServicePrincipalCredentials({24 clientId: process.env.PDF_SERVICES_CLIENT_ID,25 clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET26 });2728 // Creates a PDF Services instance29 const pdfServices = new PDFServices({credentials});3031 // Creates an asset(s) from source file(s) and upload32 readStream1 = fs.createReadStream("./combineFilesInput1.pdf");33 readStream2 = fs.createReadStream("./combineFilesInput2.pdf");34 const [inputAsset1, inputAsset2] = await pdfServices.uploadAssets({35 streamAssets: [{36 readStream: readStream1,37 mimeType: MimeType.PDF38 }, {39 readStream: readStream2,40 mimeType: MimeType.PDF41 }]42 });4344 // Create parameters for the job45 const params = new CombinePDFParams()46 .addAsset(inputAsset1)47 .addAsset(inputAsset2);4849 // Create a new job instance50 const job = new CombinePDFJob({params});5152 // Submit the job and get the job result53 const pollingURL = await pdfServices.submit({job});54 const pdfServicesResponse = await pdfServices.getJobResult({55 pollingURL,56 resultType: CombinePDFResult57 });5859 // Get content from the resulting asset(s)60 const resultAsset = pdfServicesResponse.result.asset;61 const streamAsset = await pdfServices.getContent({asset: resultAsset});6263 // Creates an output stream and copy result asset's content to it64 const outputFilePath = "./combineFilesOutput.pdf";65 console.log(`Saving asset at ${outputFilePath}`);6667 const outputStream = fs.createWriteStream(outputFilePath);68 streamAsset.readStream.pipe(outputStream);69 } catch (err) {70 if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {71 console.log("Exception encountered while executing operation", err);72 } else {73 console.log("Exception encountered while executing operation", err);74 }75 } finally {76 readStream1?.destroy();77 readStream2?.destroy();78 }79})();
Copied to your clipboard1// Please refer our REST API docs for more information2// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDF34curl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \5--header 'x-api-key: {{Placeholder for client_id}}' \6--header 'Content-Type: application/json' \7--header 'Authorization: Bearer {{Placeholder for token}}' \8--data-raw '{9 "assets": [10 {11 "assetID": "urn:aaid:AS:UE1:23c30ee0-2c4d-46d6-87f2-087832fca718"12 },13 {14 "assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718"15 }16 ]17}'
Combine pages from multiple files
This combine sample combines specific pages from up to 20 different PDF files into a single PDF file. Optional arguments allow specifying page ranges for each file to combine in the output file.
Please refer the API usage guide to understand how to use our APIs.
Java
.NET
Node JS
REST API
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples2// Run the sample:3// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.combinepdf.CombinePDFWithPageRanges45 public class CombinePDFWithPageRanges {67 // Initialize the logger.8 private static final Logger LOGGER = LoggerFactory.getLogger(CombinePDFWithPageRanges.class);910 public static void main(String[] args) {1112 try (InputStream inputStream1 = Files.newInputStream(new File("src/main/resources/combineFileWithPageRangeInput1.pdf").toPath());13 InputStream inputStream2 = Files.newInputStream(new File("src/main/resources/combineFileWithPageRangeInput2.pdf").toPath())) {14 // Initial setup, create credentials instance15 Credentials credentials = new ServicePrincipalCredentials(16 System.getenv("PDF_SERVICES_CLIENT_ID"),17 System.getenv("PDF_SERVICES_CLIENT_SECRET"));1819 // Creates a PDF Services instance20 PDFServices pdfServices = new PDFServices(credentials);2122 // Creates an asset(s) from source file(s) and upload23 List<StreamAsset> streamAssets = new ArrayList<>();24 streamAssets.add(new StreamAsset(inputStream1, PDFServicesMediaType.PDF.getMediaType()));25 streamAssets.add(new StreamAsset(inputStream2, PDFServicesMediaType.PDF.getMediaType()));26 List<Asset> assets = pdfServices.uploadAssets(streamAssets);2728 PageRanges pageRangesForFirstFile = getPageRangeForFirstFile();29 PageRanges pageRangesForSecondFile = getPageRangeForSecondFile();3031 // Create parameters for the job32 CombinePDFParams combinePDFParams = CombinePDFParams.combinePDFParamsBuilder()33 .addAsset(assets.get(0), pageRangesForFirstFile) // Add the first asset as input to the params, along with its page ranges34 .addAsset(assets.get(1), pageRangesForSecondFile) // Add the second asset as input to the params, along with its page ranges35 .build();3637 // Creates a new job instance38 CombinePDFJob combinePDFJob = new CombinePDFJob(combinePDFParams);3940 // Submit the job and gets the job result41 String location = pdfServices.submit(combinePDFJob);42 PDFServicesResponse<CombinePDFResult> pdfServicesResponse = pdfServices.getJobResult(location, CombinePDFResult.class);4344 // Get content from the resulting asset(s)45 Asset resultAsset = pdfServicesResponse.getResult().getAsset();46 StreamAsset streamAsset = pdfServices.getContent(resultAsset);4748 // Creates an output stream and copy stream asset's content to it49 Files.createDirectories(Paths.get("output/"));50 OutputStream outputStream = Files.newOutputStream(new File("output/combineFilesWithPageOptionsOutput.pdf").toPath());51 LOGGER.info("Saving asset at output/combineFilesWithPageOptionsOutput.pdf");52 IOUtils.copy(streamAsset.getInputStream(), outputStream);53 outputStream.close();54 } catch (ServiceApiException | IOException | SDKException | ServiceUsageException ex) {55 LOGGER.error("Exception encountered while executing operation", ex);56 }57 }5859 private static PageRanges getPageRangeForSecondFile() {60 // Specify which pages of the second file are to be included in the combined file61 PageRanges pageRangesForSecondFile = new PageRanges();62 // Add all pages including and after page 363 pageRangesForSecondFile.addAllFrom(3);64 return pageRangesForSecondFile;65 }6667 private static PageRanges getPageRangeForFirstFile() {68 // Specify which pages of the first file are to be included in the combined file69 PageRanges pageRangesForFirstFile = new PageRanges();70 // Add page 171 pageRangesForFirstFile.addSinglePage(1);72 // Add page 273 pageRangesForFirstFile.addSinglePage(2);74 // Add pages 3 to 475 pageRangesForFirstFile.addRange(3, 4);76 return pageRangesForFirstFile;77 }78 }
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd CombinePDFWithPageRanges/4// dotnet run CombinePDFWithPageRanges.csproj56 namespace CombinePDFWithPageRanges7 {8 class Program9 {10 private static readonly ILog log = LogManager.GetLogger(typeof(Program));11 static void Main()12 {13 //Configure the logging14 ConfigureLogging();15 try16 {1718 // Initial setup, create credentials instance.19 Credentials credentials = Credentials.ServicePrincipalCredentialsBuilder()20 .WithClientId("PDF_SERVICES_CLIENT_ID")21 .WithClientSecret("PDF_SERVICES_CLIENT_SECRET")22 .Build();2324 //Create an ExecutionContext using credentials and create a new operation instance.25 ExecutionContext executionContext = ExecutionContext.Create(credentials);26 CombineFilesOperation combineFilesOperation = CombineFilesOperation.CreateNew();2728 // Create a FileRef instance from a local file.29 FileRef firstFileToCombine = FileRef.CreateFromLocalFile(@"combineFileWithPageRangeInput1.pdf");30 PageRanges pageRangesForFirstFile = GetPageRangeForFirstFile();31 // Add the first file as input to the operation, along with its page range.32 combineFilesOperation.AddInput(firstFileToCombine, pageRangesForFirstFile);3334 // Create a second FileRef instance using a local file.35 FileRef secondFileToCombine = FileRef.CreateFromLocalFile(@"combineFileWithPageRangeInput2.pdf");36 PageRanges pageRangesForSecondFile = GetPageRangeForSecondFile();37 // Add the second file as input to the operation, along with its page range.38 combineFilesOperation.AddInput(secondFileToCombine, pageRangesForSecondFile);3940 // Execute the operation.41 FileRef result = combineFilesOperation.Execute(executionContext);4243 // Save the result to the specified location.44 result.SaveAs(Directory.GetCurrentDirectory() + "/output/combineFilesOutput.pdf");4546 }47 catch (ServiceUsageException ex)48 {49 log.Error("Exception encountered while executing operation", ex);50 }51 // Catch more errors here. . .52 }5354 private static PageRanges GetPageRangeForSecondFile()55 {56 // Specify which pages of the second file are to be included in the combined file.57 PageRanges pageRangesForSecondFile = new PageRanges();58 // Add all pages including and after page 5.59 pageRangesForSecondFile.AddAllFrom(5);60 return pageRangesForSecondFile;61 }6263 private static PageRanges GetPageRangeForFirstFile()64 {65 // Specify which pages of the first file are to be included in the combined file.66 PageRanges pageRangesForFirstFile = new PageRanges();67 // Add page 2.68 pageRangesForFirstFile.AddSinglePage(2);69 // Add page 3.70 pageRangesForFirstFile.AddSinglePage(3);71 // Add pages 5 to 7.72 pageRangesForFirstFile.AddRange(5, 7);73 return pageRangesForFirstFile;74 }7576 static void ConfigureLogging()77 {78 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());79 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));80 }81 }82 }
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/combinepdf/combine-pdf-with-page-ranges.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 MimeType,9 CombinePDFParams,10 CombinePDFJob,11 CombinePDFResult,12 PageRanges,13 SDKError,14 ServiceUsageError,15 ServiceApiError16} = require("@adobe/pdfservices-node-sdk");17const fs = require("fs");1819(async () => {20 let readStream1;21 let readStream2;22 try {23 // Initial setup, create credentials instance24 const credentials = new ServicePrincipalCredentials({25 clientId: process.env.PDF_SERVICES_CLIENT_ID,26 clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET27 });2829 // Creates a PDF Services instance30 const pdfServices = new PDFServices({credentials});3132 // Creates an asset(s) from source file(s) and upload33 readStream1 = fs.createReadStream("./combineFilesInput1.pdf");34 readStream2 = fs.createReadStream("./combineFilesInput2.pdf");35 const [inputAsset1, inputAsset2] = await pdfServices.uploadAssets({36 streamAssets: [{37 readStream: readStream1,38 mimeType: MimeType.PDF39 }, {40 readStream: readStream2,41 mimeType: MimeType.PDF42 }]43 });4445 // Create a CombinePDFParams instance46 const params = new CombinePDFParams()47 .addAsset(inputAsset1, getPageRangesForFirstFile())48 .addAsset(inputAsset2, getPageRangesForSecondFile());4950 // Create a new job instance51 const job = new CombinePDFJob({params});5253 // Submit the job and get the job result54 const pollingURL = await pdfServices.submit({job});55 const pdfServicesResponse = await pdfServices.getJobResult({56 pollingURL,57 resultType: CombinePDFResult58 });5960 // Get content from the resulting asset(s)61 const resultAsset = pdfServicesResponse.result.asset;62 const streamAsset = await pdfServices.getContent({asset: resultAsset});6364 // Creates an output stream and copy result asset's content to it65 const outputFilePath = "./combineFilesOutput.pdf";66 console.log(`Saving asset at ${outputFilePath}`);6768 const outputStream = fs.createWriteStream(outputFilePath);69 streamAsset.readStream.pipe(outputStream);70 } catch (err) {71 if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {72 console.log("Exception encountered while executing operation", err);73 } else {74 console.log("Exception encountered while executing operation", err);75 }76 } finally {77 readStream1?.destroy();78 readStream2?.destroy();79 }80})();8182const getPageRangesForFirstFile = () => {83 // Specify which pages of the first file are to be included in the combined file.84 const pageRangesForFirstFile = new PageRanges();85 // Add page 1.86 pageRangesForFirstFile.addSinglePage(1);87 // Add page 2.88 pageRangesForFirstFile.addSinglePage(2);89 // Add pages 3 to 4.90 pageRangesForFirstFile.addRange(3, 4);91 return pageRangesForFirstFile;92};9394const getPageRangesForSecondFile = () => {95 // Specify which pages of the second file are to be included in the combined file.96 const pageRangesForSecondFile = new PageRanges();97 // Add all pages including and after page 3.98 pageRangesForSecondFile.addAllFrom(3);99 return pageRangesForSecondFile;100};
Copied to your clipboard1// Please refer our REST API docs for more information2// https://developer.adobe.com/document-services/docs/apis/#tag/Combine-PDF34curl --location --request POST 'https://pdf-services.adobe.io/operation/combinepdf' \5--header 'x-api-key: {{Placeholder for client_id}}' \6--header 'Content-Type: application/json' \7--header 'Authorization: Bearer {{Placeholder for token}}' \8--data-raw '{9 "assets": [10 {11 "assetID": "urn:aaid:AS:UE1:23c30ee0-2c4d-46d6-87f2-087832fca718",12 "pageRanges": [13 {14 "start": 1,15 "end": 316 }17 ]18 },19 {20 "assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718",21 "pageRanges": [22 {23 "start": 2,24 "end": 425 }26 ]27 }28 ]29}'