package test; import java.io.FileInputStream; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import com.qoppa.pdf.PDFException; import com.qoppa.pdf.settings.ImageColorSpace; import com.qoppa.pdf.settings.ImageCompression; import com.qoppa.pdfProcess.PDFDocument; public class AddTIFF { public static void main(String [] args) { try { // Create new document PDFDocument pdf = new PDFDocument(); // Get ImageIO image reader Iterator rs = ImageIO.getImageReadersBySuffix("tiff"); if (!rs.hasNext()) { throw new PDFException ("no reader for for TIFF files."); } ImageReader tiffReader = rs.next(); // Start reading the file FileInputStream inStream = new FileInputStream("input.tif"); tiffReader.setInput(ImageIO.createImageInputStream(inStream)); int numImages = tiffReader.getNumImages(true); // Loop through the images in the TIFF file for (int pageIx = 0; pageIx < numImages; ++pageIx) { // Get DPI from the image int [] dpi = new int [] {72, 72}; IIOMetadata metadata = tiffReader.getImageMetadata(pageIx); if (metadata != null) dpi = getImageDPI(metadata); // Create a page from the image pdf.appendImageAsPage(tiffReader.read(pageIx), ImageCompression.COMPRESSION_JBIG2, ImageColorSpace.COLORSPACE_RETAIN, dpi[0]); } // Save the document pdf.saveDocument("output.pdf"); } catch(Throwable t) { t.printStackTrace(); } } public static int [] getImageDPI(IIOMetadata imgMetadata) { Node node = imgMetadata.getAsTree("javax_imageio_1.0"); int [] dpi = new int[] {-1, -1}; return getPixelSize(node, dpi); } private static int [] getPixelSize(Node m, int [] dpi) { if (dpi[0] > -1 && dpi[1] > -1) { return dpi; } if (m.getNodeName().equalsIgnoreCase("HorizontalPixelSize")) { NamedNodeMap map = m.getAttributes(); if (map != null && map.getLength() > 0) { Node attr = map.item(0); double x = -1; try { x = Double.parseDouble(attr.getNodeValue()); } catch (NumberFormatException e) { e.printStackTrace(); } if (x > -1) { dpi[0] = dotsPerMMtoDpi(x); } } } else if (m.getNodeName().equalsIgnoreCase("VerticalPixelSize")) { NamedNodeMap map = m.getAttributes(); if (map != null && map.getLength() > 0) { Node attr = map.item(0); double y = -1; try { y = Double.parseDouble(attr.getNodeValue()); } catch (NumberFormatException e) { e.printStackTrace(); } if (y > -1) { dpi[1] = dotsPerMMtoDpi(y); } } } for (int i = 0; i < m.getChildNodes().getLength(); i++) { getPixelSize(m.getChildNodes().item(i), dpi); if (dpi[0] > -1 && dpi[1] > -1) { return dpi; } } return dpi; } private static int dotsPerMMtoDpi(double dotsPerMM) { return (int) Math.round((1 / (((dotsPerMM) / 10) / 2.54))); } }