In a previous post I looked at why you might want to convert a PDF file to an image. This time I will look at doing the opposite, and explain why and how to convert an image to a PDF file.
Why convert image to PDF?
Some images can be displayed in the browser, and do not require PDF display tools to be viewed. Converting images to PDF files allows the display of Tiff and other non-support image types and makes them easier to handle. PDF files can be altered and extra content can be added to them. Converting an image to a PDF will also reduce the size of the file.
How to convert image to PDF?
1. Use iText
One way to convert an image to a PDF in Java is to use iText. iText is a PDF generation and manipulation tool for Java. It allows you to create a new PDF document and then add an existing image to that document.
You can find example code for adding an image to a PDF document using iText here.
2. Use JDeli
Another way to convert an image to a PDF in Java is to use JDeli, our Java image library. JDeli can be used to read and write a large number of image file formats in Java. It can also be used to write an image to a PDF file.
Below is some example code to convert an image to a PDF using JDeli (the full javadocs can be found here):
//create the image file File imageFile = new File("C:\\path\\to\\image\\exampleImage.png"); //create a new PDF file File pdfFile = new File("C:\\path\\to\\pdf\\examplePDF.pdf"); pdfFile.createNewFile(); //write the image to the pdf PdfEncoder encoder = new PdfEncoder(); encoder.write(imageFile, pdfFile);
Alternatively you can pass in a BufferedImage instead of a File to the write method. If the image is a multi-page TIFF then JDeli will generate a multi-page PDF file, with as many images as the TIFF contains.
If you found this guide useful, you may be interested in our series of articles on handling common image file formats in Java.