How to Convert a PDF to PNG or JPG in Java
This tutorial shows how to convert any PDF document to a stacked PNG image or PNG or JPG array with one image per page, using an API.
Join the DZone community and get the full member experience.
Join For FreeFor sharing documents both in hardcopy and digitally, the PDF file format is the preferred choice. Because of its high-versatility and compatibility between different operating systems, the PDF format allows users to create, edit, encrypt, and lock important documents for viewing on any browser or with any PDF viewing application such as Adobe Acrobat. Furthermore, its flexibility means that almost any other file type can be converted into PDF format without loss of quality or corruption of formatting. This means that complex file types such as DOCX and XLSX documents can be converted and shared easily in a protected format that will limit the chance of accidental edits or formatting errors.
However, if you are planning to display examples or insert an image of a PDF document in a separate file or web page, converting your PDF files to an image array will be more useful. For example, if you are creating a PowerPoint showing the on-boarding process for your organization and need to include images of different documents or contracts associated with the process, converting your PDF files into JPG will allow you to quickly and effortlessly insert the image and scale or crop it according to the needs of your presentation. When performing a similar process for a web page, having your document available as a PNG image will optimize it for viewing online within your website. It also prevents users from downloading and editing the document as would be possible with a PDF.
In this article, we will review three Conversion APIs that will allow you to convert any PDF document into an image. This includes conversion to a PNG or JPG array with one image created per page in your document. We will also discuss how you can merge and stack your PDF pages for conversion into a single PNG, or “tall” image.
Our goal for this tutorial is to simplify and improve your versatility for document display and sharing. Furthermore, as most documents can be converted to PDF, you can apply these APIs to any file, post-PDF-conversion. This will greatly increase your deliverable scope and production value.
The first API that we will discuss here provides an automated process for converting a PDF document to a PNG array. As an array, one PNG image will be created of each page within the PDF document, meaning you can choose specific pages for use without need for extra input commands.
As with all of our APIs shown below, the first step is to install our library by adding a Jitpack reference to our repositories in pom.xml:
xxxxxxxxxx
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Then, we need to add the following reference to the dependencies:
xxxxxxxxxx
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v3.54</version>
</dependency>
</dependencies>
To install with Gradle, add it into your root build.gradle at the end of repositories:
xxxxxxxxxx
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Then, add the dependency in build.gradle:
xxxxxxxxxx
dependencies {
implementation 'com.github.Cloudmersive:Cloudmersive.APIClient.Java:v3.54'
}
After this, we can add our imports to the top of the file and call our function:
xxxxxxxxxx
// 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.ConvertDocumentApi;
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");
ConvertDocumentApi apiInstance = new ConvertDocumentApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
try {
PdfToPngResult result = apiInstance.convertDocumentPdfToPngArray(inputFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertDocumentApi#convertDocumentPdfToPngArray");
e.printStackTrace();
}
The only input necessary for this API is your PDF file. To ensure that this and the other APIs function properly, you will need to verify that:
- Your input file is valid
- Your API Key has been properly inserted into the code block. This can be retrieved at no cost on the Cloudmersive website and will provide access to 800 monthly calls across our library of APIs.
If you need a PNG image of your document but wish to show all your pages at once, the following API will allow you to merge your PDF pages into one “tall” PNG image. In this format, the pages will be stacked vertically from the first page down to the last. Whatever order your pages hold within your document will be the order reflected in the tall PNG.
As shown above, you will need to install our library with Maven or Gradle, and then you can add the imports to the top of the file. Once this has been completed, you can call the function as shown below.
xxxxxxxxxx
// 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.ConvertDocumentApi;
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");
ConvertDocumentApi apiInstance = new ConvertDocumentApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
try {
byte[] result = apiInstance.convertDocumentPdfToPngSingle(inputFile);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertDocumentApi#convertDocumentPdfToPngSingle");
e.printStackTrace();
}
Ensure that the document’s pages are in the correct order before conversion, as they will maintain that order within the PNG. This formatting will allow users to scroll through the entire document at once without the need for multiple PNG files.
Finally, as PNGs are preferable for online use due to their flexibility, a JPG file is most useful as a static image within other files or for print. For example, if you need to include images of your document within a presentation or appendix, the JPG file format will compress the image and allow you to place and scale high-fidelity images in your project without requiring much space.
Once again, to start our function, we need to install our library with Maven or Gradle and add our imports to the top of our file.
Then, we can call our final function:
// 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.ConvertDocumentApi;
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");
ConvertDocumentApi apiInstance = new ConvertDocumentApi();
File inputFile = new File("/path/to/inputfile"); // File | Input file to perform the operation on.
Integer quality = 56; // Integer | Optional; Set the JPEG quality level; lowest quality is 1 (highest compression), highest quality (lowest compression) is 100; recommended value is 75. Default value is 75.
try {
PdfToJpgResult result = apiInstance.convertDocumentPdfToJpg(inputFile, quality);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ConvertDocumentApi#convertDocumentPdfToJpg");
e.printStackTrace();
}
Here, you will need to input your source file, and you can also optionally set the quality level for your image. The quality scale goes from 1 at the highest compression and lowest quality, to 100, which is the lowest compression and highest quality. Our recommended and default value is 75.
With the completion of this tutorial you will be able to convert any PDF file to PNG or JPG to meet the needs of your project. 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.
Opinions expressed by DZone contributors are their own.
Comments