This tutorial and the sample source code explain filling a PDF form using the filling functionality from PDF.co Web API using Java programming language for Java developers. The users can utilize PDF Form Filler API to fill their respective PDF documents with their data interactively.

  1. Features of PDF Form Filler Web API
  2. Endpoint Parameters
  3. PDF Filler Source Code in Java
  4. Source Code Snippet
  5. Step-by-Step Guide to Use Form Filler API
  6. Filled 4506-T Form Output
  7. How to Fill 4506-T Form in Java – Video Guide

Features of PDF Form Filler Web API

Moreover, the PDF.co Web API possesses beneficial tools to fill a form by benefiting from easy field-name mapping, using e-signature support, and using an on-premise API server. The PDF.co Form Filler API works extremely fast to fill out forms rather than manually handling them. The data to be filed can be from different sources such as spreadsheets, CRM’s, and user input.

A PDF form can have various fields such as text fields, checkboxes, radio buttons, and combo boxes. There is also an option to embed e-signature and other important image objects which the document needs. A demo explaining all of these features in detail is below to help users understand it more easily.

Another critical thing to consider here is that the PDF.co Web API provides high security. This API transmits the user’s documents and data files via encrypted connections. Users can learn more about the PDF.co API security here.

Endpoint Parameters

Following are the parameters of the PDF Form Filler API.

  1. url: It is a required parameter which should be a string containing the form URL. When the user creates the request, the API takes the form from this parameter and modifies it. Moreover, the user can edit more than one form simultaneously by providing a comma-separated URL of the source files.
  2. password: The user must provide the file password if he is editing the locked file.
  3. fields: It is an optional parameter that accepts the value arrays to update the editable fields.
  4. images: It is an options parameter accepting image objects array to add images in the pdf form.
  5. encrypt: It is an optional parameter whose value is false by default, and the users can encrypt the output file using this parameter.
  6. async: It is an optional parameter with boolean values. The users can make the processes run asynchronously using it.
  7. name: It is an optional parameter that takes the string with the output file name.
  8. profiles: It is an optional parameter to set custom configuration.

PDF Filler Source Code in Java

The following source code shows users how to fill a sample PDF form using the PDF.co Form Filler API. The sample code in Java shows how to fill a sample form like IRS Form 4506. This form mainly consists of some text fields and checkboxes along with the signature in the form. The users can use the Get PDF Info tool to get the field names in an interactive PDF. Users can access it in the Helpers Tools menu in their respective PDF.co accounts. A direct link to the feature is here.

Users can upload their PDF documents to get critical information about their respective documents, such as the text fields, edit boxes, checkboxes, page numbers, and the location of every field to help the filling process efficiently.

The code contains IRS Form 4506 as an example here. The user needs to provide an API key generated by the PDF.co login and the pdf file URL in the API request for the API to work. Moreover, the pdf.co API returns the resulting or edited file URL from which the user can download the file and keep it on his local storage. The result.pdf file contains the filled document after execution of the code and fills the document with required important information.

Source Code Snippet

Here is an example URL code snippet.

package com.company;

import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.google.gson.*;
import okhttp3.*;
import java.io.IOException;
import java.net.http.*;
import java.net.URI;
public class Main {
// The authentication key (API Key).
// Get your own by registering at https://app.pdf.co
final static String API_KEY = "********************";

// Direct URL of source PDF file.
final static String SourceFileUrl = "https://www.irs.gov/pub/irs-pdf/f4506t.pdf";
// PDF document password. Leave empty for unprotected documents.
final static String Password = "";

// Destination PDF file name
final static Path ResultFile = Paths.get(".result.pdf");

public static void main(String[] args) throws IOException
{
// Create HTTP client instance
OkHttpClient webClient = new OkHttpClient();

// Prepare URL for `PDF Edit` API call
String query = "https://api.pdf.co/v1/pdf/edit/add";

// Prepare form filling data
String fields = "[n" +
"        {n" +
"            "fieldName": "topmostSubform[0].Page1[0].f1_1[0]",n" +
"            "pages": "0",n" +
"            "text": "John A."n" +
"        },        n" +
"        {n" +
"            "fieldName": "topmostSubform[0].Page1[0].f1_2[0]",n" +
"            "pages": "0",n" +
"            "text": "Doe"n" +
"        },        n" +
"        {n" +
"            "fieldName": "topmostSubform[0].Page1[0].f1_3[0]",n" +
"            "pages": "0",n" +
"            "text": "XYZ"n" +
"        },n" +
"        {n" +
"            "fieldName": "topmostSubform[0].Page1[0].f1_4[0]",n" +
"            "pages": "0",n" +
"            "text": "1234567"n" +
"        },n" +
"        {n" +
"            "fieldName": "topmostSubform[0].Page1[0].f1_5[0]",n" +
"            "pages": "0",n" +
"            "text": "Las Vegas, Nevada"n" +
"        },n" +
"        {n" +
"            "fieldName": "topmostSubform[0].Page1[0].f1_6[0]",n" +
"            "pages": "0",n" +
"            "text": "ABCDE"n" +
"        },n" +
"        {n" +
"            "fieldName": "topmostSubform[0].Page1[0].customer_file_number[0]",n" +
"            "pages": "0",n" +
"            "text": "987654321"n" +
"        },     n" +
"        {n" +
"            "fieldName": "topmostSubform[0].Page1[0].c1_1[1]",n" +
"            "pages": "0",n" +
"            "text": "True"n" +
"        },     n" +
"        {n" +
"            "fieldName": "topmostSubform[0].Page1[0].f1_24[0]",n" +
"            "pages": "0",n" +
"            "text": "05"n" +
"        },     n" +
"        {n" +
"            "fieldName": "topmostSubform[0].Page1[0].f1_25[0]",n" +
"            "pages": "0",n" +
"            "text": "01"n" +
"        },     n" +
"        {n" +
"            "fieldName": "topmostSubform[0].Page1[0].f1_26[0]",n" +
"            "pages": "0",n" +
"            "text": "20"n" +
"        }     n" +
"    ]";


// Asynchronous Job
String async = "false";

// Make correctly escaped (encoded) URL
URL url = null;
try
{
url = new URI(null, query, null).toURL();
}
catch (URISyntaxException e)
{
e.printStackTrace();
}


// Create JSON payload
String jsonPayload = String.format("{n" +
"    "url": "%s",n" +
"    "async": %s,n" +
"    "encrypt": false,n" +
"    "name": "f1040-filled",n" +
"    "fields": %s"+
"}", SourceFileUrl, async, fields);

// Prepare request body
RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload);
// Prepare request
Request request = new Request.Builder()
.url(url)
.addHeader("x-api-key", API_KEY) // (!) Set API Key
.addHeader("Content-Type", "application/json")
.post(body)
.build();

// Execute request
Response response = webClient.newCall(request).execute();
if (response.code() == 200)
{

// Parse JSON response
JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject();
boolean error = json.get("error").getAsBoolean();
if (!error)
{

// Get URL of generated output file
String resultFileUrl = json.get("url").getAsString();
System.out.println(resultFileUrl);

// Download the image file
downloadFile(webClient, resultFileUrl, ResultFile);
System.out.printf("Generated file saved to "%s" file.", ResultFile.toString());
}
else
{

// Display service reported error
System.out.println(json.get("message").getAsString());
}
}
else
{

// Display request error
System.out.println(response.code() + " " + response.message());
}
}

public static void downloadFile(OkHttpClient webClient, String url, Path destinationFile) throws IOException
{

// Prepare request
Request request = new Request.Builder()
.url(url)
.build();

// Execute request
Response response = webClient.newCall(request).execute();
byte[] fileBytes = response.body().bytes();

// Save downloaded bytes to file
OutputStream output = new FileOutputStream(destinationFile.toFile());
output.write(fileBytes);
output.flush();
output.close();
response.close();
}
}Code javacodeco

Step-by-Step Guide to Use Form Filler API

  1. Gson is a Java library that can easily convert Java Objects into JSON representation. The Gson library by Google prevents writing code from parsing JSON response and works well with any networking library, including Android Async HTTP Client and OkHttp. Users can download the relevant JAR file to add the library to their project dependency for a better developer experience.
  2. OkHttp is a third-party library that can assist in sending and receiving HTTP-based network requests. It is more efficient in reading and writing data than the standard Java I/O libraries. Users can download the JAR file for OkHttp and include it in their project dependency for efficient load handling and saving bandwidth.
  3. After logging in to the PDF.co website, the users can obtain their API key after logging in to the PDF.co website to access their Web API. As the users can not send a direct request, they have to use this specific API key as an access token in the header for authentication.
  4. The best practice is to use this API key in variable declaration. The users will have to change only the variable and can edit the following file easily. Otherwise, they will have to use a separate key for the other files as well.
  5. Upload the relevant PDF document by using the Helper Tools menu and get the field mapping. Pick the required fields from the information and verify the page numbers and field locations to fill the required fields in the form.
  6. Moreover, check the fields’ width to put only the critical information according to the limited width to avoid inconvenience.
  7. Provide the relevant information in the payload—for example, the field names, page numbers, and the information to be added. Moreover, the users can add image objects in the payload to include signatures in the PDF form.
  8. Send the POST request and observe its response. Check if the status code of that response is successful or not. Usually, if the status code is 200, it means that the request was successful.
  9. If the request was successful, convert the response to a JSON object and print it on the screen to obtain a URL, leading to the filled PDF form.
  10. However, if the request was unsuccessful, observe the error from the status code and repeat the process accordingly.
  11. The users can download the filled PDF from the obtained URL as well. For this purpose, the users can provide the document link to the download function and provide the output path of the file as well.
  12. For a better experience, the users can write a function to effectively download the edited form from the response URL, as shown in the sample code. The function takes the file URL, output file path, and the web client to download and store the file in the given location. The users can choose to provide the path of the output file in the variable declaration for conveniently changing them according to the requirement.

Filled 4506-T Form Output

Below is the screenshot of the edited form:

4506-T Filled Form

How to Fill 4506-T Form in Java – Video Guide

How to Fill 4506-T Form Demo

In this tutorial, you found out how to fill the 4506-T form in Java using PDF.co Web API. See below Java code samples needed for this tutorial.