Edit in GitHubLog an issue

Insert Pages

Insert Pages in PDF#

The insert operation inserts additional pages from different PDFs into an existing PDF.

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.insertpages.InsertPDFPages
4
5 public class InsertPDFPages {
6
7 // Initialize the logger.
8 private static final Logger LOGGER = LoggerFactory.getLogger(InsertPDFPages.class);
9
10 public static void main(String[] args) {
11 try {
12 // Initial setup, create credentials instance.
13 Credentials credentials = Credentials.serviceAccountCredentialsBuilder()
14 .fromFile("pdfservices-api-credentials.json")
15 .build();
16
17 // Create an ExecutionContext using credentials and create a new operation instance.
18 ExecutionContext executionContext = ExecutionContext.create(credentials);
19 InsertPagesOperation insertPagesOperation = InsertPagesOperation.createNew();
20
21 // Set operation base input from a source file.
22 FileRef baseSourceFile = FileRef.createFromLocalFile("src/main/resources/baseInput.pdf");
23 insertPagesOperation.setBaseInput(baseSourceFile);
24
25 // Create a FileRef instance using a local file.
26 FileRef firstFileToInsert = FileRef.createFromLocalFile("src/main/resources/firstFileToInsertInput.pdf");
27 PageRanges pageRanges = getPageRangeForFirstFile();
28
29 // Adds the pages (specified by the page ranges) of the input PDF file to be inserted at
30 // the specified page of the base PDF file.
31 insertPagesOperation.addPagesToInsertAt(firstFileToInsert, pageRanges, 2);
32
33 // Create a FileRef instance using a local file.
34 FileRef secondFileToInsert = FileRef.createFromLocalFile("src/main/resources/secondFileToInsertInput.pdf");
35
36 // Adds all the pages of the input PDF file to be inserted at the specified page of the
37 // base PDF file.
38 insertPagesOperation.addPagesToInsertAt(secondFileToInsert, 3);
39
40 // Execute the operation.
41 FileRef result = insertPagesOperation.execute(executionContext);
42
43 // Save the result to the specified location.
44 result.saveAs("output/insertPagesOutput.pdf");
45
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 which pages of the first file are to be inserted in the base 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.