Insert Pages
Insert one or more pages into an existing document
REST API
See our public API Reference for Insert Pages
Insert Pages in PDF
The insert operation inserts additional pages from different PDFs into an existing PDF.
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.insertpages.InsertPDFPages45 public class InsertPDFPages {67 // Initialize the logger.8 private static final Logger LOGGER = LoggerFactory.getLogger(InsertPDFPages.class);910 public static void main(String[] args) {11 try (InputStream baseInputStream = Files.newInputStream(new File("src/main/resources/baseInput.pdf").toPath());12 InputStream firstInputStreamToInsert = Files.newInputStream(new File("src/main/resources/firstFileToInsertInput.pdf").toPath());13 InputStream secondInputStreamToInsert = Files.newInputStream(new File("src/main/resources/secondFileToInsertInput.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 Asset baseAsset = pdfServices.upload(baseInputStream, PDFServicesMediaType.PDF.getMediaType());24 Asset firstAssetToInsert = pdfServices.upload(firstInputStreamToInsert, PDFServicesMediaType.PDF.getMediaType());25 Asset secondAssetToInsert = pdfServices.upload(secondInputStreamToInsert, PDFServicesMediaType.PDF.getMediaType());2627 PageRanges pageRanges = getPageRangeForFirstFile();2829 // Create parameters for the job30 InsertPagesParams insertPagesParams = InsertPagesParams.insertPagesParamsBuilder(baseAsset)31 .addPagesToInsertAt(firstAssetToInsert, pageRanges, 2) // Add the first asset as input to the params, along with its page ranges and base page32 .addPagesToInsertAt(secondAssetToInsert, 3) // Add the seccond asset as input to the params, along with base page33 .build();3435 // Creates a new job instance36 InsertPagesPDFJob insertPagesJob = new InsertPagesPDFJob(insertPagesParams);3738 // Submit the job and gets the job result39 String location = pdfServices.submit(insertPagesJob);40 PDFServicesResponse<InsertPagesResult> pdfServicesResponse = pdfServices.getJobResult(location, InsertPagesResult.class);4142 // Get content from the resulting asset(s)43 Asset resultAsset = pdfServicesResponse.getResult().getAsset();44 StreamAsset streamAsset = pdfServices.getContent(resultAsset);4546 // Creates an output stream and copy stream asset's content to it47 Files.createDirectories(Paths.get("output/"));48 OutputStream outputStream = Files.newOutputStream(new File("output/insertPagesOutput.pdf").toPath());49 LOGGER.info("Saving asset at output/insertPagesOutput.pdf");50 IOUtils.copy(streamAsset.getInputStream(), outputStream);51 outputStream.close();52 } catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {53 LOGGER.error("Exception encountered while executing operation", e);54 }55 }5657 private static PageRanges getPageRangeForFirstFile() {58 // Specify which pages of the first file are to be inserted in the base file59 PageRanges pageRanges = new PageRanges();60 // Add pages 1 to 361 pageRanges.addRange(1, 3);6263 // Add page 4.64 pageRanges.addSinglePage(4);6566 return pageRanges;67 }68 }
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd InsertPDFPages/4// dotnet run InsertPDFPages.csproj56 namespace InsertPDFPages7 {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.24 ExecutionContext executionContext = ExecutionContext.Create(credentials);2526 // Create a new operation instance27 InsertPagesOperation insertPagesOperation = InsertPagesOperation.CreateNew();2829 // Set operation base input from a source file.30 FileRef baseSourceFile = FileRef.CreateFromLocalFile(@"baseInput.pdf");31 insertPagesOperation.SetBaseInput(baseSourceFile);3233 // Create a FileRef instance using a local file.34 FileRef firstFileToInsert = FileRef.CreateFromLocalFile(@"firstFileToInsertInput.pdf");35 PageRanges pageRanges = GetPageRangeForFirstFile();3637 // Adds the pages (specified by the page ranges) of the input PDF file to be inserted at38 // the specified page of the base PDF file.39 insertPagesOperation.AddPagesToInsertAt(firstFileToInsert, pageRanges, 2);4041 // Create a FileRef instance using a local file.42 FileRef secondFileToInsert = FileRef.CreateFromLocalFile(@"secondFileToInsertInput.pdf");4344 // Adds all the pages of the input PDF file to be inserted at the specified page of the45 // base PDF file.46 insertPagesOperation.AddPagesToInsertAt(secondFileToInsert, 3);4748 // Execute the operation.49 FileRef result = insertPagesOperation.Execute(executionContext);5051 // Save the result to the specified location.52 result.SaveAs(Directory.GetCurrentDirectory() + "/output/insertPagesOutput.pdf");53 }54 catch (ServiceUsageException ex)55 {56 log.Error("Exception encountered while executing operation", ex);57 // Catch more errors here . . .58 }5960 private static PageRanges GetPageRangeForFirstFile()61 {62 // Specify which pages of the first file are to be inserted in the base file.63 PageRanges pageRanges = new PageRanges();64 // Add pages 1 to 3.65 pageRanges.AddRange(1, 3);6667 // Add page 4.68 pageRanges.AddSinglePage(4);6970 return pageRanges;71 }7273 static void ConfigureLogging()74 {75 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());76 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));77 }78 }79 }
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/insertpages/insert-pdf-pages.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 MimeType,9 PageRanges,10 InsertPagesParams,11 InsertPagesJob,12 InsertPagesResult,13 SDKError,14 ServiceUsageError,15 ServiceApiError16} = require("@adobe/pdfservices-node-sdk");17const fs = require("fs");1819(async () => {20 let baseReadStream;21 let firstReadStreamToInsert;22 let secondReadStreamToInsert;23 try {24 // Initial setup, create credentials instance25 const credentials = new ServicePrincipalCredentials({26 clientId: process.env.PDF_SERVICES_CLIENT_ID,27 clientSecret: process.env.PDF_SERVICES_CLIENT_SECRET28 });2930 // Creates a PDF Services instance31 const pdfServices = new PDFServices({credentials});3233 // Creates an asset(s) from source file(s) and upload34 baseReadStream = fs.createReadStream("./baseInput.pdf");35 firstReadStreamToInsert = fs.createReadStream("./firstFileToInsertInput.pdf");36 secondReadStreamToInsert = fs.createReadStream("./secondFileToInsertInput.pdf");37 const [baseAsset, firstAssetToInsert, secondAssetToInsert] = await pdfServices.uploadAssets({38 streamAssets: [{39 readStream: baseReadStream,40 mimeType: MimeType.PDF41 }, {42 readStream: firstReadStreamToInsert,43 mimeType: MimeType.PDF44 }, {45 readStream: secondReadStreamToInsert,46 mimeType: MimeType.PDF47 }]48 });4950 // Create parameters for the job51 const params = new InsertPagesParams(baseAsset)52 // Add the first asset as input to the params, along with its page ranges and base page53 .addPagesToInsertAt({54 inputAsset: firstAssetToInsert,55 pageRanges: getPageRangesForFirstFile(),56 basePage: 257 })58 // Add the second asset as input to the params, along with base page59 .addPagesToInsertAt({60 inputAsset: secondAssetToInsert,61 basePage: 362 });6364 // Create a new job instance65 const job = new InsertPagesJob({params});6667 // Submit the job and get the job result68 const pollingURL = await pdfServices.submit({job});69 const pdfServicesResponse = await pdfServices.getJobResult({70 pollingURL,71 resultType: InsertPagesResult72 });7374 // Get content from the resulting asset(s)75 const resultAsset = pdfServicesResponse.result.asset;76 const streamAsset = await pdfServices.getContent({asset: resultAsset});7778 // Creates an output stream and copy result asset's content to it79 const outputFilePath = "./insertPagesOutput.pdf";80 console.log(`Saving asset at ${outputFilePath}`);8182 const outputStream = fs.createWriteStream(outputFilePath);83 streamAsset.readStream.pipe(outputStream);84 } catch (err) {85 if (err instanceof SDKError || err instanceof ServiceUsageError || err instanceof ServiceApiError) {86 console.log("Exception encountered while executing operation", err);87 } else {88 console.log("Exception encountered while executing operation", err);89 }90 } finally {91 baseReadStream?.destroy();92 firstReadStreamToInsert?.destroy();93 secondReadStreamToInsert?.destroy();94 }95})();
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-2e4d-46d6-87f2-087832fca718",12 "pageRanges": [13 {14 "start": 1,15 "end": 116 }17 ]18 },19 {20 "assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718",21 "pageRanges": [22 {23 "start": 424 }25 ]26 },27 {28 "assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718",29 "pageRanges": [30 {31 "start": 132 }33 ]34 },35 {36 "assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718",37 "pageRanges": [38 {39 "start": 240 }41 ]42 }43 ]44}'