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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert Between PDF and TIFF in Java
  • How to Split PDF Files into Separate Documents Using Java
  • How to Get Plain Text From Common Documents in Java
  • How to Change PDF Paper Sizes With an API in Java

Trending

  • What Is Plagiarism? How to Avoid It and Cite Sources
  • How AI Agents Are Transforming Enterprise Automation Architecture
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Accelerating AI Inference With TensorRT
  1. DZone
  2. Coding
  3. Java
  4. How to Optimize a PDF in Java

How to Optimize a PDF in Java

Optimize a PDF by reducing file size, linearizing content for streaming download, or converting to PDF/A using PDF conversion APIs.

By 
Brian O'Neill user avatar
Brian O'Neill
DZone Core CORE ·
Dec. 04, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
9.2K Views

Join the DZone community and get the full member experience.

Join For Free

As we have discussed before, the PDF is the ideal file format for saving, sharing, and protecting documents, both small and large. Its high compatibility with most Operating Systems makes it popular amongst most users for sharing information with different parties. Furthermore, it provides a more static platform for working with important documents like contracts and manuals, as steps can be taken to prevent any unwanted access or editing to the file. 

With large and highly complex files like this, however, different systems may have difficulty uploading, downloading, and reading the formatting for your document. This can lead to file corruption or increased loading times that can halt productivity. Thus, streamlining large PDF files can greatly benefit organizations that regularly use this format in day-to-day operations. 

The following APIs will allow you to optimize your PDF files in three distinct ways: reducing the file size, linearizing the content, and converting common PDF files to PDF/A. Using these tools, you will simplify the saving and sharing of your largest documents and increase your organization’s overall productivity. 

To start using any of these APIs, you first need to install the SDK library, which can be done either through Maven or Gradle. To install with Maven, you will need to add a Jitpack reference to the repository in pom.xml:

XML
 




x


 
1
<repositories>
2
    <repository>
3
        <id>jitpack.io</id>
4
        <url>https://jitpack.io</url>
5
    </repository>
6
</repositories>


Then, you can add a reference to the dependency:

XML
 




xxxxxxxxxx
1


 
1
<dependencies>
2
<dependency>
3
    <groupId>com.github.Cloudmersive</groupId>
4
    <artifactId>Cloudmersive.APIClient.Java</artifactId>
5
    <version>v3.54</version>
6
</dependency>
7
</dependencies>


To install with Gradle, you can add the reference in your root build.gradle at the end of repositories:

Java
 




xxxxxxxxxx
1


 
1
allprojects {
2
    repositories {
3
        ...
4
        maven { url 'https://jitpack.io' }
5
    }
6
}


Then, add the dependency in build.gradle:

Java
 




xxxxxxxxxx
1


 
1
dependencies {
2
        implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v3.54'
3
}


Once you have completed the install, you can call the function. The first function will reduce the file size of a PDF by optimizing its content.

Java
 




xxxxxxxxxx
1
24


 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.EditPdfApi;
7

          
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9

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

          
16
EditPdfApi apiInstance = new EditPdfApi();
17
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
18
try {
19
    byte[] result = apiInstance.editPdfReduceFileSize(inputFile);
20
    System.out.println(result);
21
} catch (ApiException e) {
22
    System.err.println("Exception when calling EditPdfApi#editPdfReduceFileSize");
23
    e.printStackTrace();
24
}


This will return a downloadable PDF file that can then be used however you need it. To ensure that this API works properly, you need to ensure certain requirements are met:  

  • The PDF file is valid and input correctly.
  • You have input your API Key. This can be retrieved at no cost on the Cloudmersive website, providing 800 monthly calls across our API library.

If you are sending or downloading a large file using the internet, the next API will linearize your PDF file for streaming download. This will allow you to view the content of the file as it is downloaded, rather than waiting for the long load times that might occur otherwise. Like before, you will need first to install the SDK library; then, you can call the function:

Java
 




xxxxxxxxxx
1
24


 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.EditPdfApi;
7

          
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9

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

          
16
EditPdfApi apiInstance = new EditPdfApi();
17
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
18
try {
19
    byte[] result = apiInstance.editPdfLinearize(inputFile);
20
    System.out.println(result);
21
} catch (ApiException e) {
22
    System.err.println("Exception when calling EditPdfApi#editPdfLinearize");
23
    e.printStackTrace();
24
}


Again, this will return a file with the optimized content, ready for use. 

Finally, this last API will convert any PDF file to PDF/A, which is a standardized PDF format that has higher usability across systems. This will prevent your files from becoming corrupted or losing any formatting when sending between computers. You also have the option to select the conformance level for the PDF/A file: “1b” for PDF/A-1b or “2b” for PDF/A-2b. The default is PDF/A-1b.

Java
 




xxxxxxxxxx
1
25


 
1
// Import classes:
2
//import com.cloudmersive.client.invoker.ApiClient;
3
//import com.cloudmersive.client.invoker.ApiException;
4
//import com.cloudmersive.client.invoker.Configuration;
5
//import com.cloudmersive.client.invoker.auth.*;
6
//import com.cloudmersive.client.EditPdfApi;
7

          
8
ApiClient defaultClient = Configuration.getDefaultApiClient();
9

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

          
16
EditPdfApi apiInstance = new EditPdfApi();
17
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
18
String conformanceLevel = "conformanceLevel_example"; // String | Optional: Select the conformance level for PDF/A - specify '1b' for PDF/A-1b or specify '2b' for PDF/A-2b; default is PDF/A-1b
19
try {
20
    byte[] result = apiInstance.editPdfConvertToPdfA(inputFile, conformanceLevel);
21
    System.out.println(result);
22
} catch (ApiException e) {
23
    System.err.println("Exception when calling EditPdfApi#editPdfConvertToPdfA");
24
    e.printStackTrace();
25
}


With the returned PDF/A file, you will not have to worry about your file appearing the way you designed it when sharing with other users.

With these functions, you can easily streamline and optimize your PDF documents according to your needs. If you have any questions about using these APIs or inquiries concerning other API solutions, you can visit the Cloudmersive website, where our team is happy to help with anything you might need.

PDF Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert Between PDF and TIFF in Java
  • How to Split PDF Files into Separate Documents Using Java
  • How to Get Plain Text From Common Documents in Java
  • How to Change PDF Paper Sizes With an API 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!