Convert Image to Pdf file using Java

You may also like to read:

Introduction

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 conversion procedure.

You may also like to read Convert PDF to Image using Java.

Prerequisites

Knowledge of Java, JDK 1.8
Have JDK installed and configured
Have maven installed and configured

Example with Source Code

Here we will create maven based standalone project in Eclipse.

Creating Project

Create maven based standalone project in Eclipse with below artifact and group id.

artifact id: pdf-image, group id: com.jeejava

Updating pom.xml

The required maven dependency has to be added in the dependencies section of the pom.xml file.

<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>4.2.2</version>
</dependency>

Java Class

The following Java class will take image as inputs and produce pdf file.

package com.jeejava.pdf.image;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

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

public class ConvertImageToPdf {

	public static void main(String arg[]) throws Exception {

		File root = new File("C:/Desktop");

		String outputFile = "sampleout.pdf";

		List<String> files = new ArrayList<String>();
		files.add("sample_1.png");
		files.add("sample_2.png");

		Document document = new Document();

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

		for (String f : files) {
			document.newPage();
			Image image = Image.getInstance(new File(root, f).getAbsolutePath());
			image.setAbsolutePosition(0, 0);
			image.setBorderWidth(0);
			image.scaleAbsoluteHeight(PageSize.A4.getHeight());
			image.scaleAbsoluteWidth(PageSize.A4.getWidth());
			document.add(image);
		}

		document.close();

	}
}

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

Output Pdf

Source Code

You can download source code.

Thanks for reading.

Convert Image to Pdf file using Java

Leave a Reply

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

Scroll to top