Programming

Add, Remove, or Rotate Pages in a PDF Document

Spread the love


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:

<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:

<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:

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:

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:

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:

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.



Source link

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button