There are several open source libraries in Java helps to convert images to Java. Images can be of any valid types like jpg, jpeg, png, webp, tiff, bmp etc.,
ITextPdf library is one of the Java library which has more features require to do all type of operations in PDF.
To Include ItextPdf library in our application, download from maven repository using the following link, or use it in application inside pom.xml.
1 2 3 4 5 6 7 |
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.9</version> </dependency> |
Below is a simple example to convert an Image file to PDF in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfWriter; import java.io.IOException; import java.net.MalformedURLException; import java.util.List; public class PDFServices { public byte[] convertImagesToPDF(List<String> files) throws DocumentException, MalformedURLException, IOException { Document document = new Document(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); PdfWriter.getInstance(document, bout); document.open(); for(String file:files) { Image image = Image.getInstance(file); document.setMargins(5, 5, 5, 5); document.setPageSize(PageSize.A4); document.newPage(); image.scaleToFit(PageSize.A4); document.add(image); } document.close(); return bout.toByteArray(); } } |
The Output of the above program will return the PDF document in byte array.
We can write the byte output in a file to fetch the PDF document in byte array.