Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
JPG to PDF in Java


Scanned document stored as series of jpeg images and I needed a PDF. There are ways to accomplish this without code (print to PDF), but I needed to make the file a particular size and print to pdf made the single PDF larger than the combined size of the images.


iText PDF library and Java program to create a PDF with the images. See more about iText here:

See the code in It started with a piece of code from nathan on stackoverflow with modifications to resize the image and to add multiple images (1 per page). See:

Maven dependency:



import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import java.util.ArrayList;
import java.util.List;
public class JpgToPdf {
public static void main(String arg[]) throws Exception {
File root = new File("<folder containing images>");
String outputFile = "output.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());
image.setAbsolutePosition(0, 0);

This comment has been minimized.

Copy link

@geckoway geckoway commented Apr 25, 2019

image file :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at com.itextpdf.text.Jpeg.processParameters(
at com.itextpdf.text.Jpeg.(


This comment has been minimized.

Copy link

@lfo lfo commented May 10, 2019

It is exactly what I was looking for. It was a time saver.



This comment has been minimized.

Copy link

@keerthiprasad keerthiprasad commented Jul 1, 2020

It is simple and neat.



This comment has been minimized.

Copy link

@Calikidd86 Calikidd86 commented Jan 15, 2021

Effective and efficient. Thank you, sir!


This comment has been minimized.

Copy link

@ryabos ryabos commented Jan 19, 2021

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment