A Java program that converts a TIFF file into a PDF document using Qoppa’s library Java PDF image library jPDFImages.
TIFF images cannot be inserted directly into a PDF, so we have to read them into an image object and then recompress.
Using Flate Compression
This sample below is the simplest way to convert a multi page tiff into PDF using the PDFImages.appendTIFFAsPage method. Currently (as of v2017R1), the appendTiffAsPages will use the “flate” compression which is loss-less but might result in PDF files that are bigger than the original TIFF.
import com.qoppa.pdfImages.PDFImages; public class TIFFToPDF { public static void main (String [] args) { try { PDFImages pdfDoc = new PDFImages(); pdfDoc.appendTIFFAsPages("input.tif"); pdfDoc.saveDocument("output.pdf"); } catch (Throwable t) { t.printStackTrace(); } } } |
Download source code TiffToPDF.java
Using JBIG2 or JPEG Compression
You can also use a different method, PDFDocument.appendImageAsPage() which allows you to set the type of compression.
The sample below reads the images in your code and then passes each image into this method. It uses Java ImageIO to read the images in the TIFF file and the makes calls to the appendImageAsPage() method. When calling the method, we tell it to use JBIG2 compression, this compression works only on black and white images (same as most TIFFs) but produces better compression that TIFF compression. This will only work for black and white tiff. Othewise, you should use JPEG compression (which will work for both color and black and white TIFF images.
// Create new PDF document PDFDocument pdf = new PDFDocument(); // Get ImageIO Tiff image reader Iterator<ImageReader> rs = ImageIO.getImageReadersBySuffix("tiff"); if (!rs.hasNext()) { throw new PDFException ("no reader for TIFF files."); } ImageReader tiffReader = rs.next(); // Start reading the TIFF file FileInputStream inStream = new FileInputStream("input.tif"); tiffReader.setInput(ImageIO.createImageInputStream(inStream)); int numImages = tiffReader.getNumImages(true); // Loop through all the pages / images in the TIFF file for (int pageIx = 0; pageIx < numImages; ++pageIx) { // Get DPI from the image int [] dpi = new int [] {72, 72}; // Get image metadata IIOMetadata metadata = tiffReader.getImageMetadata(pageIx); if (metadata != null) dpi = getImageDPI(metadata); // Create a page from the image using JBIG2 compression pdf.appendImageAsPage(tiffReader.read(pageIx), ImageCompression.COMPRESSION_JBIG2, ImageColorSpace.COLORSPACE_RETAIN, dpi[0]); } // Save the resulting PDF document pdf.saveDocument("output.pdf"); |