Monday, 29 November 2021

Convert PDF to Image with Transparent Background

In a previous article, I introduced how to use the PdfDocument.saveAsImage() method provided by Free Spire.PDF for Java to convert each page of a PDF document to a normal image. This tutorial will demonstrate how to set the background transparency of the image converted from PDF using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you need to download the product package from the link, and then manually add the Spire.Pdf.jar file as a dependency in the Java program. Or you can create a Maven project in the Java application, and add the following code to the pom.xml file. 

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf</artifactId>
<version>4.11.1</version>
</dependency>
</dependencies>

Using the code

Spire.PDF for Java provides PdfDocument.getConvertOptions().setPdfToImageOptions() method to set the transparent value of the resulted image’s background. The following are detailed steps for your reference.

l  Create a PdfDocument instance.

l  Load a sample PDF document using PdfDocument.loadFromFile() method.

l  Set the background transparent value of the image converted from PDF using PdfDocument.getConvertOptions().setPdfToImageOptions() method.

l  Save the document to another file using PdfDocument.saveAsImage() method.

import com.spire.pdf.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PdfToImage {
public static void main(String[] args) throws IOException {
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();

//Load a sample PDF document
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.pdf");

//Set the background transparent value as 0
pdf.getConvertOptions().setPdfToImageOptions(0);

//Save the document to a .png image
BufferedImage image = pdf.saveAsImage(0);
File file = new File( String.format("output/ToImage.png"));
ImageIO.write(image, "PNG", file);
}
}



No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...