Skip to content

Instantly share code, notes, and snippets.

@gholker
Last active February 18, 2024 02:08
Show Gist options
  • 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

Problem:

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.

Solution:

iText PDF library and Java program to create a PDF with the images. See more about iText here: http://developers.itextpdf.com/itext-java

See the code in Main.java. 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: http://stackoverflow.com/questions/15744454/how-to-convert-jpg-to-pdf-in-android-java

Maven dependency:

  <dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.9</version>
  </dependency>
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
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>();
files.add("page1.jpg");
files.add("page2.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.scaleAbsolute(PageSize.A4);
document.add(image);
}
document.close();
}
}
@geckoway
Copy link

image file : https://drugdoc.ysbang.cn/1642/11210020_f4f28633-7678-4278-89a7-4b7bbc3b7887.jpg
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at com.itextpdf.text.Jpeg.processParameters(Jpeg.java:290)
at com.itextpdf.text.Jpeg.(Jpeg.java:117)

@lfo
Copy link

lfo commented May 10, 2019

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

Thanks.

@keerthiprasad
Copy link

It is simple and neat.

Thanks

@AyoHandGod
Copy link

Effective and efficient. Thank you, sir!

@ryabos
Copy link

ryabos commented Jan 19, 2021

Thank you!

@reynoldyehezkiel
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