Replace Pages
Replace one or more pages with another page in an existing document
REST API
See our public API Reference for Replace Pages
Replace Pages in PDF
The replace pages operation replaces pages in a PDF with pages from other PDF files.
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.replacepages.ReplacePDFPages45 public class ReplacePDFPages {67 // Initialize the logger.8 private static final Logger LOGGER = LoggerFactory.getLogger(ReplacePDFPages.class);910 public static void main(String[] args) {1112 try (InputStream baseInputStream = Files.newInputStream(new File("src/main/resources/baseInput.pdf").toPath());13 InputStream inputStream1 = Files.newInputStream(new File("src/main/resources/replacePagesInput1.pdf").toPath());14 InputStream inputStream2 = Files.newInputStream(new File("src/main/resources/replacePagesInput2.pdf").toPath())) {15 // Initial setup, create credentials instance16 Credentials credentials = new ServicePrincipalCredentials(17 System.getenv("PDF_SERVICES_CLIENT_ID"),18 System.getenv("PDF_SERVICES_CLIENT_SECRET"));1920 // Creates a PDF Services instance21 PDFServices pdfServices = new PDFServices(credentials);2223 // Creates an asset(s) from source file(s) and upload24 Asset baseAsset = pdfServices.upload(baseInputStream, PDFServicesMediaType.PDF.getMediaType());25 Asset asset1 = pdfServices.upload(inputStream1, PDFServicesMediaType.PDF.getMediaType());26 Asset asset2 = pdfServices.upload(inputStream2, PDFServicesMediaType.PDF.getMediaType());2728 PageRanges pageRanges = getPageRangeForFirstFile();2930 // Create parameters for the job31 ReplacePagesParams replacePagesParams = ReplacePagesParams.replacePagesParamsBuilder(baseAsset)32 .addPagesForReplace(asset1, pageRanges, 1) // Add the first asset as input to the params, along with its page ranges and base page33 .addPagesForReplace(asset2, 3) // Add the second asset as input to the params, along with base page34 .build();3536 // Creates a new job instance37 ReplacePagesPDFJob replacePagesPDFJob = new ReplacePagesPDFJob(replacePagesParams);3839 // Submit the job and gets the job result40 String location = pdfServices.submit(replacePagesPDFJob);41 PDFServicesResponse<ReplacePagesResult> pdfServicesResponse = pdfServices.getJobResult(location, ReplacePagesResult.class);4243 // Get content from the resulting asset(s)44 Asset resultAsset = pdfServicesResponse.getResult().getAsset();45 StreamAsset streamAsset = pdfServices.getContent(resultAsset);4647 // Creates an output stream and copy stream asset's content to it48 Files.createDirectories(Paths.get("output/"));49 OutputStream outputStream = Files.newOutputStream(new File("output/replacePagesOutput.pdf").toPath());50 LOGGER.info("Saving asset at output/replacePagesOutput.pdf");51 IOUtils.copy(streamAsset.getInputStream(), outputStream);52 outputStream.close();53 } catch (IOException | ServiceApiException | SDKException | ServiceUsageException e) {54 LOGGER.error("Exception encountered while executing operation", e);55 }56 }5758 private static PageRanges getPageRangeForFirstFile() {59 // Specify pages of the first file for replacing the page of base PDF file60 PageRanges pageRanges = new PageRanges();61 // Add pages 1 to 362 pageRanges.addRange(1, 3);6364 // Add page 465 pageRanges.addSinglePage(4);6667 return pageRanges;68 }69 }
Copied to your clipboard1// Get the samples from https://www.adobe.com/go/pdftoolsapi_net_samples2// Run the sample:3// cd ReplacePDFPages/4// dotnet run ReplacePDFPages.csproj56 namespace ReplacePDFPages7 {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 ReplacePagesOperation replacePagesOperation = ReplacePagesOperation.CreateNew();2829 // Set operation base input from a source file.30 FileRef baseSourceFile = FileRef.CreateFromLocalFile(@"baseInput.pdf");31 replacePagesOperation.SetBaseInput(baseSourceFile);3233 // Create a FileRef instance using a local file.34 FileRef firstInputFile = FileRef.CreateFromLocalFile(@"replacePagesInput1.pdf");35 PageRanges pageRanges = GetPageRangeForFirstFile();3637 // Adds the pages (specified by the page ranges) of the input PDF file for replacing the38 // page of the base PDF file.39 replacePagesOperation.AddPagesForReplace(firstInputFile, pageRanges, 1);4041 // Create a FileRef instance using a local file.42 FileRef secondInputFile = FileRef.CreateFromLocalFile(@"replacePagesInput2.pdf");4344 // Adds all the pages of the input PDF file for replacing the page of the base PDF file.45 replacePagesOperation.AddPagesForReplace(secondInputFile, 3);4647 // Execute the operation.48 FileRef result = replacePagesOperation.Execute(executionContext);4950 // Save the result to the specified location.51 result.SaveAs(Directory.GetCurrentDirectory() + "/output/replacePagesOutput.pdf");52 }53 catch (ServiceUsageException ex)54 {55 log.Error("Exception encountered while executing operation", ex);56 // Catch more errors here . . .57 }5859 private static PageRanges GetPageRangeForFirstFile()60 {61 // Specify pages of the first file for replacing the page of base PDF file.62 PageRanges pageRanges = new PageRanges();63 // Add pages 1 to 3.64 pageRanges.AddRange(1, 3);6566 // Add page 4.67 pageRanges.AddSinglePage(4);6869 return pageRanges;70 }7172 static void ConfigureLogging()73 {74 ILoggerRepository logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());75 XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));76 }77 }78 }
Copied to your clipboard1// Get the samples from http://www.adobe.com/go/pdftoolsapi_node_sample2// Run the sample:3// node src/replacepages/replace-pdf-pages.js45const {6 ServicePrincipalCredentials,7 PDFServices,8 MimeType,9 PageRanges,10 InsertPagesResult,11 ReplacePagesJob,12 ReplacePagesParams,13 SDKError,14 ServiceUsageError,15 ServiceApiError16} = require("@adobe/pdfservices-node-sdk");17const fs = require("fs");1819(async () => {20 let baseReadStream;21 let readStream1;22 let readStream2;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 readStream1 = fs.createReadStream("./replacePagesInput1.pdf");36 readStream2 = fs.createReadStream("./replacePagesInput2.pdf");37 const [baseAsset, asset1, asset2] = await pdfServices.uploadAssets({38 streamAssets: [{39 readStream: baseReadStream,40 mimeType: MimeType.PDF41 }, {42 readStream: readStream1,43 mimeType: MimeType.PDF44 }, {45 readStream: readStream2,46 mimeType: MimeType.PDF47 }]48 });4950 // Create parameters for the job51 const params = new ReplacePagesParams(baseAsset)52 // Add the first asset as input to the params, along with its page ranges and base page53 .addPagesForReplace({54 asset: asset1,55 pageRanges: getPageRangesForFirstFile(),56 basePage: 157 })58 // Add the second asset as input to the params, along with base page59 .addPagesForReplace({60 asset: asset2,61 basePage: 362 });6364 // Create a new job instance65 const job = new ReplacePagesJob({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 = "./replacePagesOutput.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 readStream1?.destroy();93 readStream2?.destroy();94 }95})();9697function getPageRangesForFirstFile() {98 // Specify pages of the first file for replacing the page of base PDF file99 const pageRanges = new PageRanges();100 // Add pages 1 to 3101 pageRanges.addRange(1, 3);102 // Add page 4103 pageRanges.addSinglePage(4);104 return pageRanges;105}
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": 224 }25 ]26 },27 {28 "assetID": "urn:aaid:AS:UE1:23c30ee0-2e4d-46d6-87f2-087832fca718",29 "pageRanges": [30 {31 "start": 332 }33 ]34 }35 ]36}'