File format conversion is the most commonly used function when we are dealing with Word, Excel, PowerPoint or PDF documents. This article will introduce how to convert an image to PDF programatically with Free Spire.PDF for JAVA. This free Java library supports converting multiple image formats such as BMP, JPEG, GIF, PNG, TIFF and ICO to PDF.
Import jar dependency (2 Methods)
● Download the Free Spire.PDF for Java and unzip it.Then add the Spire.Pdf.jar file to your project as dependency.
● Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>4.3.0</version>
</dependency>
</dependencies>
Convert Image to PDF:
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;
import java.awt.geom.Rectangle2D;
public class ImageToPDF {
public static void main(String[] args){
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Add a page
PdfPageBase page = pdf.getPages().add();
//Load the image
PdfImage image = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\source.jpg");
//Draw the image to the specific rectangular area of the page
double widthFitRate = image.getPhysicalDimension().getWidth() / page.getCanvas().getClientSize().getWidth();
double heightFitRate = image.getPhysicalDimension().getHeight() / page.getCanvas().getClientSize().getHeight();
double fitRate = Math.max(widthFitRate, heightFitRate);
double fitWidth = image.getPhysicalDimension().getWidth() / fitRate;
double fitHeight = image.getPhysicalDimension().getHeight() / fitRate;
page.getCanvas().drawImage(image, new Rectangle2D.Double(0, 0, fitWidth, fitHeight));
//Save the resultant document
pdf.saveToFile("ImageToPDF.pdf");
}
}
Top comments (0)