Skip to content

Instantly share code, notes, and snippets.

@silvioangels
Forked from gholker/JpgToPdf.java
Created September 27, 2018 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silvioangels/af4e7e0bc286213aca524c199313bdfd to your computer and use it in GitHub Desktop.
Save silvioangels/af4e7e0bc286213aca524c199313bdfd 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>

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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment