How to Create a Blank PDF with Java

Learn how to generate a blank PDF to fill with content using Java with the pdfRest Create Blank PDF API.
Share this page

Generate a Blank PDF Programmatically with Java

Some PDF-generation workflows need a document with known page dimensions and count before any content is added. Storing a separate empty template for every variation creates files that must be versioned, distributed, and kept synchronized. The pdfRest Create Blank PDF API Tool generates that starting document on demand, giving a Java application a consistent canvas for reports, covers, forms, certificates, print pieces, test fixtures, and other dynamically assembled PDFs.

The /blank-pdf endpoint requires no source upload. It creates the requested pages and returns a resource that is ready for another pdfRest operation. This separates document setup from content placement and allows applications to vary size, orientation, and page count through data rather than maintaining a growing template library.

For example, a Java reporting service can create a three-page Letter-size PDF for each customer, then use Add to PDF to place a cover, account summary, and supporting details on the appropriate pages. The document structure can be generated from report data without storing and selecting a separate empty template first.

This Java example creates a three-page, portrait, Letter-size PDF with OkHttp and prints the JSON response.

Java Create Blank PDF Code Example

Add OkHttp, java-dotenv, and JSON-java to the project. Set PDFREST_API_KEY in the environment or a .env file before running the sample.

import io.github.cdimascio.dotenv.Dotenv;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONObject;

public class BlankPDF {

  // By default, we use the US-based API service. This is the primary endpoint for global use.
  private static final String API_URL = "https://api.pdfrest.com";

  /* For GDPR compliance and enhanced performance for European users, you can switch to the EU-based
   * service by commenting out the URL above and uncommenting the URL below.
   * For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
   */
  // private static final String API_URL = "https://eu-api.pdfrest.com";

  // Specify your API key here, or in the environment variable PDFREST_API_KEY.
  // You can also put the environment variable in a .env file.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  public static void main(String[] args) {
    final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

    MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
    builder.addFormDataPart("page_size", "letter");
    builder.addFormDataPart("page_count", "3");
    builder.addFormDataPart("page_orientation", "portrait");

    RequestBody requestBody = builder.build();

    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url(API_URL + "/blank-pdf")
            .post(requestBody)
            .build();
    try {
      OkHttpClient client =
          new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
      Response response = client.newCall(request).execute();
      System.out.println("blank-pdf Result code " + response.code());
      if (response.body() != null) {
        System.out.println(prettyJson(response.body().string()));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static String prettyJson(String json) {
    return new JSONObject(json).toString(4);
  }
}

Source: pdfRest Create Blank PDF multipart Java sample

Create Blank PDF does not require an input file, so an application can send the page settings as JSON instead of multipart form data. See the Create Blank PDF JSON-payload sample for Java.

Define Page Size, Count, and Orientation

The sample builds a multipart request with three fields:

  • page_size selects a standard size. Current values include letter, legal, ledger, A3, A4, and A5.
  • page_count sets the number of blank pages. One request can create as many as 1,000 pages.
  • page_orientation selects portrait or landscape when a standard page size is used.

For a nonstandard canvas, set page_size to custom and provide custom_width and custom_height. Custom dimensions use PDF units, where 72 units equal one inch. Orientation is implicit in the custom width and height, so page_orientation is not required for a custom size.

Choose these values from validated application input rather than inserting untrusted strings directly into the request. Consistent page specifications are especially important when later steps position text or images at known coordinates or when the output must meet printing requirements.

Continue the PDF Generation Workflow

After the request succeeds, the response contains a resource ID for the new PDF. Pass that ID to the Add to PDF API Tool to place text, images, or other content onto the blank pages. Because the next call can use the server-side ID, the application does not have to download the empty PDF and upload it again before adding content.

The same resource-based pattern can continue into other pdfRest tools for merging, optimization, security, or delivery. It keeps the Java application focused on workflow rules while pdfRest handles the underlying PDF creation and modification operations. An optional output field can provide a meaningful filename for the generated document.

Handle the OkHttp Response Reliably

The example reads the API key through Dotenv, sends the request to the US Cloud API, and includes an alternate EU base URL. Keep the selected base URL in deployment configuration when the same application runs in multiple regions or environments.

Before using the result, check response.isSuccessful() and validate that the expected resource information is present. Use try-with-resources around the OkHttp Response so its body is closed after every request. The sample applies a 60-second read timeout; production services should choose timeouts and retry behavior based on their own workload and should distinguish transient network failures from invalid request parameters.

Keep the API key out of source control and avoid logging credentials or sensitive generated content. Test standard and custom page sizes, minimum and maximum expected page counts, and the next API operation in the chain before moving the workflow into production.

You can experiment with page settings in API Lab and review the exact request and response schema in the Create Blank PDF API reference.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.