Friday, 13 December 2019 07:34

Convert Image to PDF in Java

Written by  support iceblue
Rate this item
(0 votes)

Spire.PDF for Java supports converting multiple image formats such as BMP, JPEG, GIF, PNG, TIFF and ICO to PDF. The following example will show you how to convert an image to PDF using Spire.PDF for Java.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

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("Hydrangeas.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

Convert Image to PDF in Java