Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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>

Analytics

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

This comment has been minimized.

Copy link

@geckoway geckoway commented Apr 25, 2019

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

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.

Thanks.

@keerthiprasad

This comment has been minimized.

Copy link

@keerthiprasad keerthiprasad commented Jul 1, 2020

It is simple and neat.

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.