Edit in GitHubLog an issue

Quickstart for Adobe Document Generation API (Java)

To get started using Adobe Document Generation API, let's walk through a simple scenario - using a Word document as a template for dynamic receipt generation in PDF. 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 11 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=document-generation-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.

Sign in

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."

Project setup

6) After your credentials are created, they are automatically downloaded:

alt

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 folder of samples and the pdfservices-api-credentials.json file.

alt

2) Take the pdfservices-api-credentials.json file and place it in a new directory.

3) In this directory, create a new file named pom.xml and copy the following content:

Copied to your clipboard
1<?xml version="1.0" encoding="UTF-8"?>
2
3<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>
7
8 <groupId>com.adobe.documentservices</groupId>
9 <artifactId>pdfservices-sdk-documentgeneration-guide</artifactId>
10 <version>1</version>
11
12 <name>PDF Services Java SDK Samples</name>
13
14 <properties>
15 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
16 <maven.compiler.source>11</maven.compiler.source>
17 <maven.compiler.target>11</maven.compiler.target>
18 <pdfservices.sdk.version>4.0.0</pdfservices.sdk.version>
19 </properties>
20
21 <dependencies>
22
23 <dependency>
24 <groupId>com.adobe.documentservices</groupId>
25 <artifactId>pdfservices-sdk</artifactId>
26 <version>${pdfservices.sdk.version}</version>
27 </dependency>
28
29 <!-- 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.21.1</version>
35 </dependency>
36 </dependencies>
37
38 <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.codehaus.mojo</groupId>
51 <artifactId>exec-maven-plugin</artifactId>
52 <version>1.5.0</version>
53 <executions>
54 <execution>
55 <goals>
56 <goal>java</goal>
57 </goals>
58 </execution>
59 </executions>
60 </plugin>
61 </plugins>
62 </build>
63</project>

This file will define what dependencies we need and how the application will be built.

Our application will take a Word document, receiptTemplate.docx (downloadable from here), and combine it with data in a JSON file, receipt.json (downloadable from here), to be sent to the Acrobat Services API and generate a receipt PDF.

4) In your editor, open the directory where you previously copied the credentials, and create a new directory, src/main/java. In that directory, create GeneratePDF.java.

Now you're ready to begin coding.

Step Three: Creating the application

1) Let's start by looking at the Word template. If you open the document in Microsoft Word, you'll notice multiple tokens throughout the document (called out by the use of {{ and }}).

Example of tokens

When the Document Generation API is used, these tokens are replaced with the JSON data sent to the API. These tokens support simple replacements, for example, {{Customer.Name}} will be replaced by a customer's name passed in JSON. You can also have dynamic tables. In the Word template, the table uses invoice items as a way to dynamically render whatever items were ordered. Conditions can also be used to hide or show content as you can see two conditions at the end of the document. Finally, basic math can be also be dynamically applied, as seen in the "Grand Total".

2) Next, let's look at our sample data:

Copied to your clipboard
1{
2 "author": "Gary Lee",
3 "Company": {
4 "Name": "Projected",
5 "Address": "19718 Mandrake Way",
6 "PhoneNumber": "+1-100000098"
7 },
8 "Invoice": {
9 "Date": "January 15, 2021",
10 "Number": 123,
11 "Items": [
12 {
13 "item": "Gloves",
14 "description": "Microwave gloves",
15 "UnitPrice": 5,
16 "Quantity": 2,
17 "Total": 10
18 },
19 {
20 "item": "Bowls",
21 "description": "Microwave bowls",
22 "UnitPrice": 10,
23 "Quantity": 2,
24 "Total": 20
25 }
26 ]
27 },
28 "Customer": {
29 "Name": "Collins Candy",
30 "Address": "315 Dunning Way",
31 "PhoneNumber": "+1-200000046",
32 "Email": "cc@abcdef.co.dw"
33 },
34 "Tax": 5,
35 "Shipping": 5,
36 "clause": {
37 "overseas": "The shipment might take 5-10 more than informed."
38 },
39 "paymentMethod": "Cash"
40}

Notice how the tokens in the Word document match up with values in our JSON. While our example will use a hard coded set of data in a file, production applications can get their data from anywhere. Now let's get into our code.

3) We'll begin by including our required dependencies:

Copied to your clipboard
1import com.adobe.pdfservices.operation.PDFServices;
2import com.adobe.pdfservices.operation.PDFServicesMediaType;
3import com.adobe.pdfservices.operation.PDFServicesResponse;
4import com.adobe.pdfservices.operation.auth.Credentials;
5import com.adobe.pdfservices.operation.auth.ServicePrincipalCredentials;
6import com.adobe.pdfservices.operation.exception.SDKException;
7import com.adobe.pdfservices.operation.exception.ServiceApiException;
8import com.adobe.pdfservices.operation.exception.ServiceUsageException;
9import com.adobe.pdfservices.operation.io.Asset;
10import com.adobe.pdfservices.operation.io.StreamAsset;
11import com.adobe.pdfservices.operation.pdfjobs.jobs.DocumentMergeJob;
12import com.adobe.pdfservices.operation.pdfjobs.params.documentmerge.DocumentMergeParams;
13import com.adobe.pdfservices.operation.pdfjobs.params.documentmerge.OutputFormat;
14import com.adobe.pdfservices.operation.pdfjobs.result.DocumentMergeResult;
15import org.apache.commons.io.IOUtils;
16import org.json.JSONObject;
17import org.slf4j.Logger;
18import org.slf4j.LoggerFactory;
19
20import java.io.File;
21import java.io.IOException;
22import java.io.InputStream;
23import java.io.OutputStream;
24import java.nio.file.Files;
25import java.nio.file.Path;
26import java.nio.file.Paths;

4) Now let's define our main class:

Copied to your clipboard
1public class GeneratePDF {
2
3 private static final Logger LOGGER = LoggerFactory.getLogger(GeneratePDF.class);
4
5 public static void main(String[] args) {
6
7 }
8
9}

These lines are hard coded but in a real application would typically be dynamic.

5) Set the environment variables PDF_SERVICES_CLIENT_ID and PDF_SERVICES_CLIENT_SECRET by running the following commands and replacing placeholders YOUR CLIENT ID and YOUR CLIENT SECRET with the credentials present in pdfservices-api-credentials.json file:

  • Windows:

    • set PDF_SERVICES_CLIENT_ID=<YOUR CLIENT ID>
    • set PDF_SERVICES_CLIENT_SECRET=<YOUR CLIENT SECRET>
  • MacOS/Linux:

    • export PDF_SERVICES_CLIENT_ID=<YOUR CLIENT ID>
    • export PDF_SERVICES_CLIENT_SECRET=<YOUR CLIENT SECRET>

6) Next, we can create our credentials and use them to create a PDF Services instance

Copied to your clipboard
1// Initial setup, create credentials instance
2Credentials credentials = new ServicePrincipalCredentials(
3 System.getenv("PDF_SERVICES_CLIENT_ID"),
4 System.getenv("PDF_SERVICES_CLIENT_SECRET"));
5
6// Create PDF Services instance
7PDFServices pdfServices = new PDFServices(credentials);

7) Now, let's upload the asset and create JSON data for merge:

Copied to your clipboard
1Asset asset = pdfServices.upload(inputStream, PDFServicesMediaType.DOCX.getMediaType());
2
3Path jsonPath = Paths.get("src/main/resources/receipt.json");
4String json = new String(Files.readAllBytes(jsonPath));
5JSONObject jsonDataForMerge = new JSONObject(json);

8) Now, let's create the parameters and the job:

Copied to your clipboard
1// Create parameters for the job
2DocumentMergeParams documentMergeParams = DocumentMergeParams.documentMergeParamsBuilder()
3 .withJsonDataForMerge(jsonDataForMerge)
4 .withOutputFormat(OutputFormat.PDF)
5 .build();
6
7// Creates a new job instance
8DocumentMergeJob documentMergeJob = new DocumentMergeJob(asset, documentMergeParams);

This set of code defines what we're doing (a document merge operation, the SDK's way of describing Document Generation), points to our local JSON file and specifies the output is a PDF. It also points to the Word file used as a template.

9) The next code block submits the job and gets the job result:

Copied to your clipboard
1// Submit the job and get the job result
2String location = pdfServices.submit(documentMergeJob);
3PDFServicesResponse<DocumentMergeResult> pdfServicesResponse = pdfServices.getJobResult(location, DocumentMergeResult.class);
4
5// Get content from the resulting asset(s)
6Asset resultAsset = pdfServicesResponse.getResult().getAsset();
7StreamAsset streamAsset = pdfServices.getContent(resultAsset);

10) The next code block saves the result at the specified location:

Copied to your clipboard
1// Creating an output stream and copying stream asset's content to it
2OutputStream outputStream = Files.newOutputStream(new File("output/generatePDFOutput").toPath());
3IOUtils.copy(streamAsset.getInputStream(), outputStream);

This code runs the Document Generation process and then stores the resulting PDF document to the file system.

Example running in the command line

Here's the complete application (src/main/java/GeneratePDF.java):

Copied to your clipboard
1import com.adobe.pdfservices.operation.PDFServices;
2import com.adobe.pdfservices.operation.PDFServicesMediaType;
3import com.adobe.pdfservices.operation.PDFServicesResponse;
4import com.adobe.pdfservices.operation.auth.Credentials;
5import com.adobe.pdfservices.operation.auth.ServicePrincipalCredentials;
6import com.adobe.pdfservices.operation.exception.SDKException;
7import com.adobe.pdfservices.operation.exception.ServiceApiException;
8import com.adobe.pdfservices.operation.exception.ServiceUsageException;
9import com.adobe.pdfservices.operation.io.Asset;
10import com.adobe.pdfservices.operation.io.StreamAsset;
11import com.adobe.pdfservices.operation.pdfjobs.jobs.DocumentMergeJob;
12import com.adobe.pdfservices.operation.pdfjobs.params.documentmerge.DocumentMergeParams;
13import com.adobe.pdfservices.operation.pdfjobs.params.documentmerge.OutputFormat;
14import com.adobe.pdfservices.operation.pdfjobs.result.DocumentMergeResult;
15import org.apache.commons.io.IOUtils;
16import org.json.JSONObject;
17import org.slf4j.Logger;
18import org.slf4j.LoggerFactory;
19
20import java.io.File;
21import java.io.IOException;
22import java.io.InputStream;
23import java.io.OutputStream;
24import java.nio.file.Files;
25import java.nio.file.Path;
26import java.nio.file.Paths;
27
28public class GeneratePDF {
29
30 private static final Logger LOGGER = LoggerFactory.getLogger(GeneratePDF.class);
31
32 public static void main(String[] args) {
33
34 try (InputStream inputStream = Files.newInputStream(new File("src/main/resources/receiptTemplate.docx").toPath())) {
35 // Initial setup, create credentials instance
36 Credentials credentials = new ServicePrincipalCredentials(
37 System.getenv("PDF_SERVICES_CLIENT_ID"),
38 System.getenv("PDF_SERVICES_CLIENT_SECRET"));
39
40 // Creates a PDF Services instance
41 PDFServices pdfServices = new PDFServices(credentials);
42
43 // Creates an asset(s) from source file(s) and upload
44 Asset asset = pdfServices.upload(inputStream, PDFServicesMediaType.DOCX.getMediaType());
45
46 // Setup input data for the document merge process
47 Path jsonPath = Paths.get("src/main/resources/receipt.json");
48 String json = new String(Files.readAllBytes(jsonPath));
49 JSONObject jsonDataForMerge = new JSONObject(json);
50
51 // Create parameters for the job
52 DocumentMergeParams documentMergeParams = DocumentMergeParams.documentMergeParamsBuilder()
53 .withJsonDataForMerge(jsonDataForMerge)
54 .withOutputFormat(OutputFormat.PDF)
55 .build();
56
57 // Creates a new job instance
58 DocumentMergeJob documentMergeJob = new DocumentMergeJob(asset, documentMergeParams);
59
60 // Submit the job and gets the job result
61 String location = pdfServices.submit(documentMergeJob);
62 PDFServicesResponse<DocumentMergeResult> pdfServicesResponse = pdfServices.getJobResult(location, DocumentMergeResult.class);
63
64 // Get content from the resulting asset(s)
65 Asset resultAsset = pdfServicesResponse.getResult().getAsset();
66 StreamAsset streamAsset = pdfServices.getContent(resultAsset);
67
68 // Creates an output stream and copy stream asset's content to it
69 Files.createDirectories(Paths.get("output/"));
70 OutputStream outputStream = Files.newOutputStream(new File("output/generatePDFOutput.pdf").toPath());
71 LOGGER.info("Saving asset at output/generatePDFOutput.pdf");
72 IOUtils.copy(streamAsset.getInputStream(), outputStream);
73 outputStream.close();
74 } catch (ServiceApiException | IOException | SDKException | ServiceUsageException e) {
75 LOGGER.error("Exception encountered while executing operation", e);
76 }
77 }
78}

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.

  • Privacy
  • Terms of Use
  • Do not sell or share my personal information
  • AdChoices
Copyright © 2024 Adobe. All rights reserved.