This tutorial will show you how to convert image to pdf file. For this I am using here itext API. The example Java image to pdf file will show you the step by step procedures for image to pdf conversion. We will build the application using both gradle and maven tools.

In this example we will align the images in the center of the pdf page. If the image width goes outside of pdf page then we will fit the image within the size of the pdf document page.


Eclipse 2019-12, At least JDK 1.8, Maven 3.6.3, Gradle 6.4.1, itextpdf

Project Setup

You can create gradle or maven based project in Eclipse. The name of the project is java-image-to-pdf.

If you are creating gradle based project then you can use below build.gradle script.

plugins {
    id 'java-library'

repositories {

dependencies {
    implementation 'com.itextpdf:itextpdf:'

If you are creating maven based project then you can use below pom.xml file.

<project xmlns=""
					<source>at least java 1.8</source>
					<target>at least java 1.8</target>

Related Posts:

Convert Image to Pdf

The following Java class will take image as input and produce pdf file as an output.

Here I am adding two images into the list and the output pdf file will have two pages with images. The second image goes out of the pdf page width so we have put conditional statement to fit the image into the pdf page.


import java.util.ArrayList;
import java.util.List;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;

public class ImageToPdfConverter {

	public static void main(String arg[]) throws Exception {
		File root = new File("C:/Users/SoumitraSarkar/Desktop");
		String outputFile = "sampleout.pdf";

		List<String> files = new ArrayList<String>();

		Document document = new Document();
		PdfWriter.getInstance(document, new FileOutputStream(new File(root, outputFile)));;

		for (String f : files) {

			Image image = Image.getInstance(new File(root, f).getAbsolutePath());


			float imageWidth = image.getWidth();

			if (imageWidth > document.getPageSize().getWidth()) {
				int indentation = 0;
				float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin()
						- indentation) / image.getWidth()) * 100;




In the above source code we first define the output file’s destination directory where we want to generate the pdf file.

Then we store all the image files which need to be added to the same pdf file.

Testing the Application

Input Images

java image to pdf
java image to pdf

Output Pdf

Source Code


Thanks for reading.


Leave a Reply

Your email address will not be published. Required fields are marked *