DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How to Get Plain Text From Common Documents in Java
  • How To Convert Common Documents to PNG Image Arrays in Java
  • How to Rasterize PDFs in Java
  • How To Create and Edit PDF Annotations in Java

Trending

  • Using Python Libraries in Java
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  1. DZone
  2. Data Engineering
  3. Data
  4. How To Add, Remove, or Rotate Pages in a PDF Document Using Java

How To Add, Remove, or Rotate Pages in a PDF Document Using Java

Learn API solutions to add pages from one PDF to another, remove pages from a PDF, rotate all pages within a PDF, and rotate a subset of pages within a PDF.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Sep. 06, 22 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
6.3K Views

Join the DZone community and get the full member experience.

Join For Free

Given the quantity of free PDF editing tools available online (including the native tools present within a PDF file), it isn’t all that difficult to make small-scale changes to PDF documents when the need arises. Making those same changes at a greater scale, however, presents an entirely new challenge.  

Let’s say you have 100 PDF files, each requiring the same editing operations.  In this case, it doesn’t make sense to perform the changes manually: the inefficiency of that process ultimately creates more problems than it solves, getting in the way of competing tasks/priorities.  The most efficient way to make changes to large volumes of PDF documents at scale is to do so programmatically, using APIs which are designed to communicate with compressed PDF files and manipulate their properties with ease.  

In this article, I’ll demonstrate four easy-to-use API solutions which allow you to programmatically add, remove or rotate pages in PDF documents at scale.  These solutions provide the following specific services:

  1. Inserting/copying pages from one PDF document into another
  2. Removing/deleting pages from a PDF document
  3. Rotating all pages within a PDF document
  4. Rotating a particular range/subset of pages in a PDF document

Below, I’ve highlighted some use cases and required parameters for each API solution in this list and supplied code examples in Java to help you structure your API calls.  These APIs are completely free to use in limited-scale operations (those involving no more than 800 API calls per month), with zero additional commitments.  To get a secure API key, you can simply register a free-tier account on our website. Once you have that, you can easily and repeatedly authenticate API access within the code examples provided below.

Installing the API Client

Before we dive into the use cases and parameters for each API solution, our first step is to install the Cloudmersive API client.  We can begin to do so by first adding a reference to our Maven POM file, as shown below:

XML
 
<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>


Then we can include the following reference in our dependency, enabling JitPack to compile the library:

XML
 
<dependencies>
<dependency>
    <groupId>com.github.Cloudmersive</groupId>
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
    <version>v4.25</version>
</dependency>
</dependencies>


Alternatively, we can install with Gradle by including the below in our root build.gradle at the end of repositories:

 
allprojects {
	repositories {
		...
		maven { url 'https://jitpack.io' }
	}
}


Following that, we can add the dependency in build.gradle:

 
dependencies {
        implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v4.25'
}


Lastly, we’ll need to include the following imports at the top of our file:

 
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.EditPdfApi;


Insert, Copy Pages From One PDF Into Another

As the title of this API suggests, we can use this "Insert, Copy" solution to include a specific range of pages from a source PDF in a destination PDF.  This is an excellent tool for quickly compiling large-scale reports, memos, marketing samples, and much more.  This API’s parameters allow us to specify exactly which pages we want to start and finish copying from, and where specifically to insert those copied pages into the destination document.  While the source and destination file inputs are quite straightforward to navigate, we’ll need to pay a little closer attention when configuring the following three parameters:

  1. pageStartSource: The page (1-based) to begin copying content from; content from this page will be included in the destination file.
  2. pageEndSource: The final page (1-based) to copy content from; content from this page will be included in the destination file.
  3. pageInsertBeforeDestination: The page (1-based) in the destination PDF before which the copied content should be included.

With our parameters squared away, we can structure the API call like so:

Java
 
ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

EditPdfApi apiInstance = new EditPdfApi();
File sourceFile = new File("/path/to/inputfile"); // File | Source PDF file to copy pages from.
File destinationFile = new File("/path/to/inputfile"); // File | Destination PDF file to copy pages into.
Integer pageStartSource = 56; // Integer | Page number (1 based) to start copying pages from (inclusive) in the Source file.
Integer pageEndSource = 56; // Integer | Page number (1 based) to stop copying pages pages from (inclusive) in the Source file.
Integer pageInsertBeforeDesitnation = 56; // Integer | Page number (1 based) to insert the pages before in the Destination file.
try {
    byte[] result = apiInstance.editPdfInsertPages(sourceFile, destinationFile, pageStartSource, pageEndSource, pageInsertBeforeDesitnation);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditPdfApi#editPdfInsertPages");
    e.printStackTrace();
}


Remove, Delete Pages From a PDF Document

If our goal is to remove pages from PDF files at scale instead, we can employ the "Remove, Delete" solution. This page removal solution has a multitude of use cases. To provide a common example, it’s particularly useful in scenarios where several versions of a private report/memo need to be shared across an organization.  To remove pages from the input PDF, we must include the PDF file path and then satisfy the following parameters:

  1. pageStart: Specifies which page (1-based) to begin deleting from, and deletes this page
  2. pageEnd: Specifies which page (1-based) to finish deleting from, and deletes this page

We can structure our page removal API call like so, once again beginning with our API key authorization snippet:

Java
 
ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

EditPdfApi apiInstance = new EditPdfApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
Integer pageStart = 56; // Integer | Page number (1 based) to start deleting pages from (inclusive).
Integer pageEnd = 56; // Integer | Page number (1 based) to stop deleting pages from (inclusive).
try {
    byte[] result = apiInstance.editPdfDeletePages(inputFile, pageStart, pageEnd);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditPdfApi#editPdfDeletePages");
    e.printStackTrace();
}


Rotate All Pages in a PDF Document

Whether intentional or due to an oversight, it’s common that large PDF files – especially those converted from formats like JPG, PNG, PowerPoint PPTX, and more – contain pages that are rotated at an undesirable angle.  When every single page within a PDF file is rotated incorrectly to the same degree, we’re in luck: we can use the simplistic "Rotate All Pages" solution to correct the issue instantly.  We just need to pay close attention to the rotationAngle parameter in this solution, as it only accepts positive (rotate right) and negative (rotate left) integers which can only be multiples of 90 degrees. Once we’ve properly specified this parameter, we can structure the API as demonstrated with the examples below:

Java
 
ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

EditPdfApi apiInstance = new EditPdfApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
Integer rotationAngle = 56; // Integer | The angle to rotate the page in degrees, must be a multiple of 90 degrees, e.g. 90, 180, 270, or -90, -180, -270, etc.
try {
    byte[] result = apiInstance.editPdfRotateAllPages(inputFile, rotationAngle);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditPdfApi#editPdfRotateAllPages");
    e.printStackTrace();
}


Rotate a Range, Subset of Pages in a PDF Document

When only a certain subset of pages within a PDF document requires rotational adjustment, there’s no need to worry: we can perform a more specific version of the previously outlined operation with ease.  We simply need to configure the rotation angle once again, along with two parameters specifying where the operation should begin and end:

  1. rotationAngle: Defines how many degrees the specified pages will be rotated; accepts positive (rotate right) and negative (rotate left) integers which are multiples of 90 degrees
  2. pageStart: Specifies which page (1-based) in the subset to begin from, and includes this page
  3. pageEnd: Specifies which page (1-based) in the subset to finish on, and includes this page

This API call should be structured like so:

Java
 
ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");

EditPdfApi apiInstance = new EditPdfApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
Integer rotationAngle = 56; // Integer | The angle to rotate the page in degrees, must be a multiple of 90 degrees, e.g. 90, 180, 270, or -90, -180, -270, etc.
Integer pageStart = 56; // Integer | Page number (1 based) to start rotating pages from (inclusive).
Integer pageEnd = 56; // Integer | Page number (1 based) to stop rotating pages from (inclusive).
try {
    byte[] result = apiInstance.editPdfRotatePageRange(inputFile, rotationAngle, pageStart, pageEnd);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling EditPdfApi#editPdfRotatePageRange");
    e.printStackTrace();
}


Once you’ve structured your API call(s) with the above examples, you’re all set: no more code is required. Each API response will produce a string of encoding for the new PDF file, which can be used to generate a new file or update the existing document as needed.

API Document PDF Java (programming language) Data Types

Opinions expressed by DZone contributors are their own.

Related

  • How to Get Plain Text From Common Documents in Java
  • How To Convert Common Documents to PNG Image Arrays in Java
  • How to Rasterize PDFs in Java
  • How To Create and Edit PDF Annotations in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!