How to convert multi-page TIFF to PDF in Java
This tutorial provides a very efficient way to convert a multi-page TIFF to PDF using iText library.
The below utility method accepts a multi-page TIFF file as an input and returns a PDF file as an output. In order to use it, you must add theĀ iText library to your classpath.
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 31 32 | public static File convertTIFFToPDF(File tiffFile) { File pdfFile = new File("C:\\Users\\user\\\\Desktop\\output.pdf"); try { RandomAccessFileOrArray myTiffFile = new RandomAccessFileOrArray(tiffFile.getCanonicalPath()); // Find number of images in Tiff file int numberOfPages = TiffImage.getNumberOfPages(myTiffFile); Document TifftoPDF = new Document(); PdfWriter pdfWriter = PdfWriter.getInstance(TifftoPDF, new FileOutputStream(pdfFile)); pdfWriter.setStrictImageSequence(true); TifftoPDF.open(); Image tempImage; // Run a for loop to extract images from Tiff file // into a Image object and add to PDF recursively for (int i = 1; i <= numberOfPages; i++) { tempImage = TiffImage.getTiffImage(myTiffFile, i); Rectangle pageSize = new Rectangle(tempImage.getWidth(), tempImage.getHeight()); TifftoPDF.setPageSize(pageSize); TifftoPDF.newPage(); TifftoPDF.add(tempImage); } TifftoPDF.close(); } catch(Exception ex) { ex.printStackTrace(); } return pdfFile; } |
Happy Coding!