DEV Community

Alexis
Alexis

Posted on

Java - How to Convert PNG to PDF

PDF is a universal format having the ability to work well on any software and hardware. Due to this reason, it is used throughout all kinds of workplaces. When an image file is converted to PDF, it keeps the design of the image well enough to ensure that it looks exactly the same. In this article, I am going to introduce how to convert PNG (or whatever image format) files to a PDF document by using Spire.PDF for Java.

Add Spire.Pdf.jar as dependency

If you are working on a maven project, you can include the dependency in pom.xml file using this:

<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>8.5.8</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

If you are not using maven, then you can find the required jar files from the zip file available in this location. Include all the jar files into the application lib folder to run the sample code given in this tutorial.

Convert PNG Files to a Single PDF Maintaining Image Quality

This part will show you how to combine multiple images in a single PDF document with each being transferred to a separate PDF page, without compressing the image quality. The main steps are as follows.

  • Create a PdfDocument object.
  • Set the page margins to zero using PdfDocument.getPageSettings.setMargins() method.
  • Get the abstract paths of the image files in a folder.
  • Loop though the images to get a specific one and load it to a PdfImage object using PdfImage.fromImage() 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.
  • Draw the PdfImage object on the page at the coordinate (0, 0) using PdfPageBase.getCanvas().drawImage() method.
  • Save the document to a PDF file using PdfDocument.saveToFile() method.
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.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ConvertPngToPdf {

    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);

        //Creating a File object for directory
        File directoryPath = new File("C:\\Users\\Administrator\\Desktop\\Images");

        //Get the abstract paths of the image files in the folder
        File filesList[] = directoryPath.listFiles();

        //Loop through the images
        for (int i = 0; i < filesList.length; i++) {

            //Read an image to BufferedImage
            BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filesList[i].getAbsolutePath()));

            //Create a PdfImage object
            PdfImage pdfImage = PdfImage.fromImage(bufferedImage);

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

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

            //Draw image at (0, 0) of the page
            page.getCanvas().drawImage(pdfImage, 0, 0, width, height);
        }

        //Save to file
        doc.saveToFile("PngToPdf.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Convert PNG Files to a PDF Compressing Image Quality

When merging high-quality images into a PDF, the PDF size tends to be large. If you want to reduce the size of the generated PDF document, you can compress the image quality while merging. The following are the steps.

  • Create a PdfDocument object.
  • Set the page margins to zero using PdfDocument.getPageSettings.setMargins() method.
  • Get the abstract paths of the image files in a folder.
  • Loop though the images to get a specific one and load it to a PdfImage object using PdfImage.fromImage() 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.
  • Draw the image in compressed quality on the page at the coordinate (0, 0) using PdfPageBase.getCanvas().drawImage(PdfImage image, int compressionQuality, float x, float y, float width, float height) method. The compressionQuality parameter ranges from 1 to 100. 1 means that the picture is compressed to 1% of the original quality, and 100 means that the picture will not be compressed.
  • Save the document to a PDF file using PdfDocument.saveToFile() method.
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.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ConvertPngToPdfCompressingQuality {

    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);

        //Creating a File object for directory
        File directoryPath = new File("C:\\Users\\Administrator\\Desktop\\Images");

        //Get the abstract paths of the image files in the folder
        File filesList[] = directoryPath.listFiles();

        //Loop through the images
        for (int i = 0; i < filesList.length; i++) {

            //Read an image to BufferedImage
            BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filesList[i].getAbsolutePath()));

            //Create a PdfImage object
            PdfImage pdfImage = PdfImage.fromImage(bufferedImage);

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

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

            //Draw image at (0, 0) of the page
            page.getCanvas().drawImage(pdfImage,30,0, 0, width, height);
        }

        //Save to file
        doc.saveToFile("CompressingQuality.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)