Skip to content

Instantly share code, notes, and snippets.

Last active February 18, 2024 02:08
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save gholker/9a6b68ae51b3bef8931b946958dd81f2 to your computer and use it in GitHub Desktop.
Save gholker/9a6b68ae51b3bef8931b946958dd81f2 to your computer and use it in GitHub Desktop.
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);
Copy link

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

Copy link

lfo commented May 10, 2019

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


Copy link

It is simple and neat.


Copy link

Effective and efficient. Thank you, sir!

Copy link

ryabos commented Jan 19, 2021

Thank you!

Copy link

It's really help. Thx

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