Quickstart for PDF Extract API (Java)
To get started using Adobe PDF Extract API, let's walk through a simple scenario - taking an input PDF document and running PDF Extract API against it. Once the PDF has been extracted, we'll parse the results and report on any major headers in the document. In this guide, we will walk you through the complete process for creating a program that will accomplish this task.
Prerequisites
To complete this guide, you will need:
- Java - Java 8 or higher is required.
- Maven
- An Adobe ID. If you do not have one, the credential setup will walk you through creating one.
- A way to edit code. No specific editor is required for this guide.
Step One: Getting credentials
1) To begin, open your browser to https://acrobatservices.adobe.com/dc-integration-creation-app-cdn/main.html?api=pdf-extract-api. If you are not already logged in to Adobe.com, you will need to sign in or create a new user. Using a personal email account is recommend and not a federated ID.
2) After registering or logging in, you will then be asked to name your new credentials. Use the name, "New Project".
3) Change the "Choose language" setting to "Java".
4) Also note the checkbox by, "Create personalized code sample." This will include a large set of samples along with your credentials. These can be helpful for learning more later.
5) Click the checkbox saying you agree to the developer terms and then click "Create credentials."
6) After your credentials are created, they are automatically downloaded:
Step Two: Setting up the project
1) In your Downloads folder, find the ZIP file with your credentials: PDFServicesSDK-JavaSamples.zip. If you unzip that archive, you will find a README file, your private key, and a folder of samples:
2) We need two things from this download. The private.key
file (as shown in the screenshot above, and the pdfservices-api-credentials.json
file found in the samples directory:
Note that that private key is also found in this directory so feel free to copy them both from here.
3) Take these two files and place them in a new directory.
4) In this directory, create a new file named pom.xml
and copy the following contents:
Copied to your clipboard1<?xml version="1.0" encoding="UTF-8"?>23<project xmlns="http://maven.apache.org/POM/4.0.0"4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"5 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">6 <modelVersion>4.0.0</modelVersion>78 <groupId>com.adobe.documentservices</groupId>9 <artifactId>pdfservices-sdk-extract-guide</artifactId>10 <version>1</version>1112 <name>PDF Services Java SDK Samples</name>1314 <properties>15 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>16 <maven.compiler.source>1.8</maven.compiler.source>17 <maven.compiler.target>1.8</maven.compiler.target>18 <pdfservices.sdk.version>2.2.2</pdfservices.sdk.version>19 </properties>2021 <dependencies>2223 <dependency>24 <groupId>com.adobe.documentservices</groupId>25 <artifactId>pdfservices-sdk</artifactId>26 <version>${pdfservices.sdk.version}</version>27 </dependency>2829 <!-- log4j2 dependency to showcase the use of log4j2 with slf4j API-->30 <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->31 <dependency>32 <groupId>org.apache.logging.log4j</groupId>33 <artifactId>log4j-slf4j-impl</artifactId>34 <version>2.17.1</version>35 </dependency>36 </dependencies>3738 <build>39 <plugins>40 <plugin>41 <groupId>org.apache.maven.plugins</groupId>42 <artifactId>maven-compiler-plugin</artifactId>43 <version>3.8.0</version>44 <configuration>45 <source>${maven.compiler.source}</source>46 <target>${maven.compiler.target}</target>47 </configuration>48 </plugin>49 <plugin>50 <groupId>org.apache.maven.plugins</groupId>51 <artifactId>maven-shade-plugin</artifactId>52 <version>3.2.4</version>53 <configuration>54 <filters>55 <filter>56 <artifact>*:*</artifact>57 <excludes>58 <exclude>META-INF/*.SF</exclude>59 <exclude>META-INF/*.DSA</exclude>60 <exclude>META-INF/*.RSA</exclude>61 </excludes>62 </filter>63 </filters>64 </configuration>65 <executions>66 <execution>67 <phase>package</phase>68 <goals>69 <goal>shade</goal>70 </goals>71 </execution>72 </executions>73 </plugin>74 <plugin>75 <groupId>org.apache.maven.plugins</groupId>76 <artifactId>maven-jar-plugin</artifactId>77 <version>3.0.2</version>78 <configuration>79 <archive>80 <manifest>81 <addClasspath>true</addClasspath>82 <classpathPrefix>lib/</classpathPrefix>83 <mainClass>ExtractTextInfoFromPDF</mainClass>84 </manifest>85 </archive>86 </configuration>87 </plugin>88 <plugin>89 <groupId>org.codehaus.mojo</groupId>90 <artifactId>exec-maven-plugin</artifactId>91 <version>1.5.0</version>92 <executions>93 <execution>94 <goals>95 <goal>java</goal>96 </goals>97 </execution>98 </executions>99 </plugin>100 </plugins>101 </build>102</project>
This file will define what dependencies we need and how the application will be built.
Our application will take a PDF, Adobe Extract API Sample.pdf
(downloadable from here) and extract it's contents. The results will be saved as a ZIP file, ExtractTextInfoFromPDF.zip
. We will then parse the results from the ZIP and print out the text of any H1
headers found in the PDF.
5) In your editor, open the directory where you previously copied the credentials, and create a new directory, src/main/java
. In that directory, create ExtractTextInfoFromPDF.java
.
Now you're ready to begin coding.
Step Three: Creating the application
1) We'll begin by including our required dependencies:
Copied to your clipboard1import com.adobe.pdfservices.operation.ExecutionContext;2import com.adobe.pdfservices.operation.auth.Credentials;3import com.adobe.pdfservices.operation.exception.SdkException;4import com.adobe.pdfservices.operation.exception.ServiceApiException;5import com.adobe.pdfservices.operation.exception.ServiceUsageException;6import com.adobe.pdfservices.operation.io.FileRef;7import com.adobe.pdfservices.operation.pdfops.ExtractPDFOperation;8import com.adobe.pdfservices.operation.pdfops.options.extractpdf.ExtractElementType;9import com.adobe.pdfservices.operation.pdfops.options.extractpdf.ExtractPDFOptions;10import org.slf4j.LoggerFactory;1112import java.io.IOException;13import java.nio.file.Files;14import java.nio.file.Paths;15import java.util.Arrays;1617import java.util.zip.*;18import java.io.InputStream;19import java.util.Scanner;2021import org.json.JSONArray;22import org.json.JSONObject;
2) Now let's define our main class:
Copied to your clipboard1public class ExtractTextInfoFromPDF {23 private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ExtractTextInfoFromPDF.class);45 public static void main(String[] args) {67 }8}
3) Now let's define our input and output:
Copied to your clipboard1String zip_file = "./ExtractTextInfoFromPDF.zip";2Files.deleteIfExists(Paths.get(zip_file));34String input_file = "./Adobe Extract API Sample.pdf";
This defines what our output ZIP will be and optionally deletes it if it already exists. Then we define what PDF will be extracted. (You can download the source we used here.) In a real application, these values would be typically be dynamic.
4) Next, we can create our credentials and use them:
Copied to your clipboard1// Initial setup, create credentials instance.2Credentials credentials = Credentials.serviceAccountCredentialsBuilder()3 .fromFile("pdfservices-api-credentials.json")4 .build();56// Create an ExecutionContext using credentials.7ExecutionContext executionContext = ExecutionContext.create(credentials);
5) Now, let's create the operation:
Copied to your clipboard1ExtractPDFOperation extractPDFOperation = ExtractPDFOperation.createNew();23// Provide an input FileRef for the operation4FileRef source = FileRef.createFromLocalFile(input_file);5extractPDFOperation.setInputFile(source);67// Build ExtractPDF options and set them into the operation8ExtractPDFOptions extractPDFOptions = ExtractPDFOptions.extractPdfOptionsBuilder()9 .addGetStylingInfo(false)10 .addElementsToExtract(Arrays.asList(ExtractElementType.TEXT, ExtractElementType.TABLES))11 .build();12extractPDFOperation.setOptions(extractPDFOptions);
This set of code defines what we're doing (an Extract operation), points to our local file and specifies the input is a PDF, and then defines options for the Extract call. PDF Extract API has a few different options, but in this example, we're simply asking for the most basic of extractions, the textual content of the document.
6) The next code block executes the operation:
Copied to your clipboard1// Execute the operation2FileRef result = extractPDFOperation.execute(executionContext);34// Save the result at the specified location5result.saveAs(zip_file);
This code runs the Extraction process and then stores the result zip to the file system.
7) In this block, we read in the ZIP file, extract the JSON result file, and parse it:
Copied to your clipboard1ZipFile resultZip = new ZipFile(zip_file);2ZipEntry jsonEntry = resultZip.getEntry("structuredData.json");3InputStream is = resultZip.getInputStream(jsonEntry);4Scanner s = new Scanner(is).useDelimiter("\\A");5String jsonString = s.hasNext() ? s.next() : "";6s.close();78JSONObject jsonData = new JSONObject(jsonString);
8) Finally we can loop over the result and print out any found element that is an H1
:
Copied to your clipboard1JSONArray elements = jsonData.getJSONArray("elements");2for(int i=0; i < elements.length(); i++) {3 JSONObject element = elements.getJSONObject(i);4 String path = element.getString("Path");5 if(path.endsWith("/H1")) {6 String text = element.getString("Text");7 System.out.println(text);8 }9}
Here's the complete application (src/java/main/ExtractTextInfoFromPDF.java
):
Copied to your clipboard1import com.adobe.pdfservices.operation.ExecutionContext;2import com.adobe.pdfservices.operation.auth.Credentials;3import com.adobe.pdfservices.operation.exception.SdkException;4import com.adobe.pdfservices.operation.exception.ServiceApiException;5import com.adobe.pdfservices.operation.exception.ServiceUsageException;6import com.adobe.pdfservices.operation.io.FileRef;7import com.adobe.pdfservices.operation.pdfops.ExtractPDFOperation;8import com.adobe.pdfservices.operation.pdfops.options.extractpdf.ExtractElementType;9import com.adobe.pdfservices.operation.pdfops.options.extractpdf.ExtractPDFOptions;10import org.slf4j.LoggerFactory;1112import java.io.IOException;13import java.nio.file.Files;14import java.nio.file.Paths;15import java.util.Arrays;1617import java.util.zip.*;18import java.io.InputStream;19import java.util.Scanner;2021import org.json.JSONArray;22import org.json.JSONObject;2324public class ExtractTextInfoFromPDF {2526 private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ExtractTextInfoFromPDF.class);2728 public static void main(String[] args) {2930 try {3132 String zip_file = "./ExtractTextInfoFromPDF.zip";33 Files.deleteIfExists(Paths.get(zip_file));3435 String input_file = "./Adobe Extract API Sample.pdf";3637 // Initial setup, create credentials instance.38 Credentials credentials = Credentials.serviceAccountCredentialsBuilder()39 .fromFile("pdfservices-api-credentials.json")40 .build();4142 // Create an ExecutionContext using credentials.43 ExecutionContext executionContext = ExecutionContext.create(credentials);4445 ExtractPDFOperation extractPDFOperation = ExtractPDFOperation.createNew();4647 // Provide an input FileRef for the operation48 FileRef source = FileRef.createFromLocalFile(input_file);49 extractPDFOperation.setInputFile(source);5051 // Build ExtractPDF options and set them into the operation52 ExtractPDFOptions extractPDFOptions = ExtractPDFOptions.extractPdfOptionsBuilder()53 .addGetStylingInfo(false)54 .addElementsToExtract(Arrays.asList(ExtractElementType.TEXT, ExtractElementType.TABLES))55 .build();56 extractPDFOperation.setOptions(extractPDFOptions);5758 // Execute the operation59 FileRef result = extractPDFOperation.execute(executionContext);6061 // Save the result at the specified location62 result.saveAs(zip_file);6364 System.out.println("Successfully extracted information from PDF. Printing H1 Headers:\n");6566 ZipFile resultZip = new ZipFile(zip_file);67 ZipEntry jsonEntry = resultZip.getEntry("structuredData.json");68 InputStream is = resultZip.getInputStream(jsonEntry);69 Scanner s = new Scanner(is).useDelimiter("\\A");70 String jsonString = s.hasNext() ? s.next() : "";71 s.close();7273 JSONObject jsonData = new JSONObject(jsonString);74 JSONArray elements = jsonData.getJSONArray("elements");75 for(int i=0; i < elements.length(); i++) {76 JSONObject element = elements.getJSONObject(i);77 String path = element.getString("Path");78 if(path.endsWith("/H1")) {79 String text = element.getString("Text");80 System.out.println(text);81 }82 }838485 } catch (ServiceApiException | IOException | SdkException | ServiceUsageException e) {86 LOGGER.error("Exception encountered while executing operation", e);87 }88 }89}
Next Steps
Now that you've successfully performed your first operation, review the documentation for many other examples and reach out on our forums with any questions. Also remember the samples you downloaded while creating your credentials also have many demos.