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.

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>

Source Code Example

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 ConvertJpgToPdf {

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

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

		String outputFile = "some.pdf";

		List<String> files = new ArrayList<String>();
		files.add("some.jpg");

		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.

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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