Java: Convert Images to PDF

2022-04-08 07:34:00 Written by  support iceblue
Rate this item
(0 votes)

Converting images to PDF is beneficial for many reasons. For one reason, it allows you to convert images into a format that is more readable and easier to share. For another reason, it dramatically reduces the size of the file while preserving the quality of images. In this article, you will learn how to convert images to PDF in Java using Spire.PDF for Java.

There is no straightforward method provided by Spire.PDF to convert images to PDF. You could, however, create a new PDF document and draw images at the specified locations. Depending on whether the page size of the generated PDF matches the image, this topic can be divided into two subtopics.

Install Spire.PDF for Java

First, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's 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>10.10.7</version>
    </dependency>
</dependencies>
    

Additionally, the imgscalr library is used in the first code example to resize images. It is not necessary to install it if you do not need to adjust the image’s size.

Add an Image to PDF at a Specified Location

The following are the steps to add an image to PDF at a specified location using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Set the page margins using PdfDocument.getPageSettings().setMargins() method.
  • Add a page using PdfDocument.getPages().add() method
  • Load an image using ImageIO.read() method, and get the image width and height.
  • If the image width is larger than the page (the content area) width, resize the image to make it to fit to the page width using the imgscalr library.
  • Create a PdfImage object based on the scaled image or the original image.
  • Draw the PdfImage object on the first page at (0, 0) using PdfPageBase.getCanvas().drawImage() method.
  • Save the document to a PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;
import org.imgscalr.Scalr;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;

public class AddImageToPdf {

    public static void main(String[] args) throws IOException {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Set the margins
        doc.getPageSettings().setMargins(20);

        //Add a page
        PdfPageBase page = doc.getPages().add();

        //Load an image
        BufferedImage image = ImageIO.read(new FileInputStream("C:\\Users\\Administrator\\Desktop\\announcement.jpg"));

        //Get the image width and height
        int width = image.getWidth();
        int height = image.getHeight();

        //Declare a PdfImage variable
        PdfImage pdfImage;

        //If the image width is larger than page width
        if (width > page.getCanvas().getClientSize().getWidth())
        {
            //Resize the image to make it to fit to the page width
            int widthFitRate =  width / (int)page.getCanvas().getClientSize().getWidth();
            int targetWidth = width / widthFitRate;
            int targetHeight = height / widthFitRate;
            BufferedImage scaledImage = Scalr.resize(image,Scalr.Method.QUALITY,targetWidth,targetHeight);

            //Load the scaled image to the PdfImage object
            pdfImage = PdfImage.fromImage(scaledImage);

        } else
        {
            //Load the original image to the PdfImage object
            pdfImage = PdfImage.fromImage(image);
        }

        //Draw image at (0, 0)
        page.getCanvas().drawImage(pdfImage, 0, 0, pdfImage.getWidth(), pdfImage.getHeight());

        //Save to file
        doc.saveToFile("output/AddImage.pdf");
    }
}

Java: Convert Images to PDF

Convert an Image to PDF with the Same Width and Height

The following are the steps to convert an image to a PDF with the same page size as the image using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Set the page margins to zero using PdfDocument.getPageSettings().setMargins() method.
  • Load an image using ImageIO.read() method, and get the image width and height.
  • Add a page to PDF based on the size of the image using PdfDocument.getPages().add() method.
  • Create a PdfImage object based on the image.
  • Draw the PdfImage object on the first page from the coordinate (0, 0) using PdfPageBase.getCanvas().drawImage() method.
  • Save the document to a PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;

public class ConvertImageToPdfWithSameSize {

    public static void main(String[] args) throws IOException {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Set the margins to 0
        doc.getPageSettings().setMargins(0);

        //Load an image
        BufferedImage image = ImageIO.read(new FileInputStream("C:\\Users\\Administrator\\Desktop\\announcement.jpg"));

        //Get the image width and height
        int width = image.getWidth();
        int height = image.getHeight();

        //Add a page of the same size as the image
        PdfPageBase page = doc.getPages().add(new Dimension(width, height));

        //Create a PdfImage object based on the image
        PdfImage pdfImage = PdfImage.fromImage(image);

        //Draw image at (0, 0) of the page
        page.getCanvas().drawImage(pdfImage, 0, 0, pdfImage.getWidth(), pdfImage.getHeight());

        //Save to file
        doc.saveToFile("output/ConvertPdfWithSameSize.pdf");
    }
}

Java: Convert Images to PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Thursday, 27 July 2023 06:26