Edit in GitHubLog an issue

Replace Pages

Replace Pages in PDF#

The replace pages operation replaces pages in a PDF with pages from other PDF files.

Copied to your clipboard
1// Get the samples from https://www.adobe.com/go/pdftoolsapi_java_samples
2// Run the sample:
3// mvn -f pom.xml exec:java -Dexec.mainClass=com.adobe.pdfservices.operation.samples.replacepages.ReplacePDFPages
4
5 public class ReplacePDFPages {
6
7 // Initialize the logger.
8 private static final Logger LOGGER = LoggerFactory.getLogger(ReplacePDFPages.class);
9
10 public static void main(String[] args) {
11
12 try {
13 // Initial setup, create credentials instance.
14 Credentials credentials = Credentials.serviceAccountCredentialsBuilder()
15 .fromFile("pdfservices-api-credentials.json")
16 .build();
17
18 // Create an ExecutionContext using credentials and create a new operation instance.
19 ExecutionContext executionContext = ExecutionContext.create(credentials);
20 ReplacePagesOperation replacePagesOperation = ReplacePagesOperation.createNew();
21
22 // Set operation base input from a source file.
23 FileRef baseSourceFile = FileRef.createFromLocalFile("src/main/resources/baseInput.pdf");
24 replacePagesOperation.setBaseInput(baseSourceFile);
25
26 // Create a FileRef instance using a local file.
27 FileRef firstInputFile = FileRef.createFromLocalFile("src/main/resources/replacePagesInput1.pdf");
28 PageRanges pageRanges = getPageRangeForFirstFile();
29
30 // Adds the pages (specified by the page ranges) of the input PDF file for replacing the
31 // page of the base PDF file.
32 replacePagesOperation.addPagesForReplace(firstInputFile, pageRanges, 1);
33
34
35 // Create a FileRef instance using a local file.
36 FileRef secondInputFile = FileRef.createFromLocalFile("src/main/resources/replacePagesInput2.pdf");
37
38 // Adds all the pages of the input PDF file for replacing the page of the base PDF file.
39 replacePagesOperation.addPagesForReplace(secondInputFile, 3);
40
41 // Execute the operation
42 FileRef result = replacePagesOperation.execute(executionContext);
43
44 // Save the result at the specified location
45 result.saveAs("output/replacePagesOutput.pdf");
46 } catch (IOException | ServiceApiException | SdkException | ServiceUsageException e) {
47 LOGGER.error("Exception encountered while executing operation", e);
48 }
49 }
50
51 private static PageRanges getPageRangeForFirstFile() {
52 // Specify pages of the first file for replacing the page of base PDF file.
53 PageRanges pageRanges = new PageRanges();
54 // Add pages 1 to 3.
55 pageRanges.addRange(1, 3);
56
57 // Add page 4.
58 pageRanges.addSinglePage(4);
59
60 return pageRanges;
61 }
62 }
Was this helpful?
  • Privacy
  • Terms of Use
  • Do not sell my personal information
  • AdChoices
Copyright © 2022 Adobe. All rights reserved.