How to Resize PDF Pages with Java
Why Resize PDF Pages with Java?
The pdfRest Set Page Boxes API Tool allows you to modify the page boxes of a PDF document, specifically the MediaBox, to control the physical dimensions of the pages. This tutorial will guide you through the process of sending an API call to the Set Page Boxes API Tool endpoint using Java to resize all pages of a PDF document.
Imagine you have a PDF document where all pages need to conform to a specific standard dimension for consistent display or processing. By using the Set Page Boxes API Tool and the "all" range, you can efficiently resize all PDF pages within your Java applications.
Resize PDF Pages with Java Code Example
import java.io.File; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; public class ResizePdfPages { public static void main(String[] args) throws IOException, InterruptedException { String apiKey = "YOUR_API_KEY"; // Replace with your actual API key String pdfFilePath = "/path/to/your/file.pdf"; // Replace with the actual path to your PDF file String outputName = "resized_all_to_a4_out.pdf"; String pdfWithPageBoxesEndpointUrl = "https://api.pdfrest.com/pdf-with-page-boxes-set"; // Define the MediaBox adjustments to resize all pages from Letter to A4 // Letter: 612 x 792 points // A4: 595 x 842 points double deltaWidthInward = (612 - 595) / 2; // Positive margin to shrink width inward double deltaHeightOutward = (792 - 842) / 2; // Negative margin to expand height outward String boxesJson = String.format( "{\"boxes\": [{\"box\": \"media\", \"pages\": [{\"range\": \"all\", \"left\": %.2f, \"top\": %.2f, \"bottom\": %.2f, \"right\": %.2f}]}]}", deltaWidthInward, deltaHeightOutward, deltaHeightOutward, deltaWidthInward ); MultipartFormDataBodyBuilder builder = new MultipartFormDataBodyBuilder() .addPart("file", Paths.get(pdfFilePath)) .addPart("boxes", boxesJson) .addPart("output", outputName.replace(".pdf", "")); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(pdfWithPageBoxesEndpointUrl)) .header("Api-Key", apiKey) .header("Content-Type", "multipart/form-data; boundary=" + builder.getBoundary()) .POST(builder.build()) .build(); HttpClient client = HttpClient.newBuilder().build(); System.out.println("Sending POST request to pdf-with-page-boxes-set endpoint to resize all PDF pages to A4..."); HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Response status code: " + response.statusCode()); System.out.println("Response body: " + response.body()); } // Helper class for building multipart/form-data request body private static class MultipartFormDataBodyBuilder { private final String boundary; private final StringBuilder body; private final Map headers; public MultipartFormDataBodyBuilder() { this.boundary = Long.toHexString(System.currentTimeMillis()); this.body = new StringBuilder(); this.headers = new HashMap<>(); } public MultipartFormDataBodyBuilder addPart(String name, String value) { body.append("--").append(boundary).append("\r\n"); body.append("Content-Disposition: form-data; name=\"").append(name).append("\"\r\n"); body.append("\r\n"); body.append(value).append("\r\n"); return this; } public MultipartFormDataBodyBuilder addPart(String name, Path file) throws IOException { body.append("--").append(boundary).append("\r\n"); body.append("Content-Disposition: form-data; name=\"").append(name).append("\"; filename=\"").append(file.getFileName()).append("\"\r\n"); body.append("Content-Type: application/pdf\r\n"); body.append("\r\n"); body.append(Files.readString(file)).append("\r\n"); // Note: Reads entire file into string - for large files, use streams return this; } public HttpRequest.BodyPublisher build() { body.append("--").append(boundary).append("--\r\n"); return HttpRequest.BodyPublishers.ofString(body.toString()); } public String getBoundary() { return boundary; } } }
Source: Based on the pdfRest API Documentation
Breaking Down the Code for Resizing All Pages
The code starts by importing necessary Java libraries for file operations, HTTP requests, and string formatting.
import java.io.File; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map;
This section defines the API key, input PDF file path, desired output file name, and the API endpoint URL. Remember to replace "YOUR_API_KEY"
with your actual pdfRest API key and "/path/to/your/file.pdf"
with the correct path to your PDF file.
String apiKey = "YOUR_API_KEY"; String pdfFilePath = "/path/to/your/file.pdf"; String outputName = "resized_all_to_a4_out.pdf"; String pdfWithPageBoxesEndpointUrl = "https://api.pdfrest.com/pdf-with-page-boxes-set";
This section sets the API endpoint URL.
// Define the MediaBox adjustments to resize all pages from Letter to A4 // Letter: 612 x 792 points // A4: 595 x 842 points double deltaWidthInward = (612 - 595) / 2; // Positive margin to shrink width inward double deltaHeightOutward = (792 - 842) / 2; // Negative margin to expand height outward String boxesJson = String.format( "{\"boxes\": [{\"box\": \"media\", \"pages\": [{\"range\": \"all\", \"left\": %.2f, \"top\": %.2f, \"bottom\": %.2f, \"right\": %.2f}]}]}", deltaWidthInward, deltaHeightOutward, deltaHeightOutward, deltaWidthInward );
The boxesJson
string is formatted to create the JSON payload for resizing all pages. The "box"
is set to "media"
, and "range"
is set to "all"
to apply the adjustments to every page. Positive deltaWidthInward
values shrink the width, and positive deltaHeightOutward
values expand the height.
MultipartFormDataBodyBuilder builder = new MultipartFormDataBodyBuilder() .addPart("file", Paths.get(pdfFilePath)) .addPart("boxes", boxesJson) .addPart("output", outputName.replace(".pdf", "")); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(pdfWithPageBoxesEndpointUrl)) .header("Api-Key", apiKey) .header("Content-Type", "multipart/form-data; boundary=" + builder.getBoundary()) .POST(builder.build()) .build(); HttpClient client = HttpClient.newBuilder().build(); System.out.println("Sending POST request to pdf-with-page-boxes-set endpoint to resize all PDF pages to A4..."); HttpResponseresponse = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Response status code: " + response.statusCode()); System.out.println("Response body: " + response.body());
This section uses Java's HttpClient
to build and send a POST request to the pdfRest API. It creates a multipart/form-data body containing the PDF file, the boxesJson
, and the output filename. The Api-Key
is set in the header. The response status code and body are then printed.
Next Steps for Resizing All PDF Pages
This tutorial demonstrated how to use Java and the pdfRest Set Page Boxes API Tool to resize all pages of a PDF from US Letter to A4 by setting the MediaBox with the "range": "all"
option. You can adapt the deltaWidthInward
and deltaHeightOutward
calculations to resize to other dimensions within your Java applications.
To learn more about the Set Page Boxes API Tool and its capabilities, including setting other page boxes and using different page ranges, you can demo all of the pdfRest API Tools in the API Lab and refer to the API Reference Guide for detailed documentation.