@Test public void transparentTiffTest() throws IOException { InputStream inputStream = TiffReadingTest.class.getClassLoader().getResourceAsStream("gradient.tiff"); byte[] data; try(ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream()) { int bytesRead; byte[] buffer = new byte[8192]; while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) { byteOutputStream.write(buffer, 0, bytesRead); } data = byteOutputStream.toByteArray(); } RandomAccessFileOrArray ra = new RandomAccessFileOrArray(data); int pages = TiffImage.getNumberOfPages(ra); for (int i = 1; i <= pages; i++) { Assert.assertNotNull(TiffImage.getTiffImage(ra, i)); } }
/** * Returns the number of image directories (subimages) stored in a * given TIFF file, represented by a <code>SeekableStream</code>. */ public static int getNumDirectories(RandomAccessFileOrArray stream) throws IOException{ long pointer = stream.getFilePointer(); // Save stream pointer stream.seek(0L); int endian = stream.readUnsignedShort(); if (!isValidEndianTag(endian)) { throw new IllegalArgumentException("Bad endianness tag (not 0x4949 or 0x4d4d)."); } boolean isBigEndian = (endian == 0x4d4d); int magic = readUnsignedShort(stream, isBigEndian); if (magic != 42) { throw new IllegalArgumentException("Bad magic number, should be 42."); } stream.seek(4L); long offset = readUnsignedInt(stream, isBigEndian); int numDirectories = 0; while (offset != 0L) { ++numDirectories; // EOFException means IFD was probably not properly terminated. try { stream.seek(offset); int entries = readUnsignedShort(stream, isBigEndian); stream.skip(12*entries); offset = readUnsignedInt(stream, isBigEndian); } catch(EOFException eof) { numDirectories--; break; } } stream.seek(pointer); // Reset stream pointer return numDirectories; }
/** * Gets the content stream of a page. * @param pageNum the page number of page you want get the content stream from * @return a byte array with the content stream of a page * @throws IOException */ private byte[] getContentBytesForPage(int pageNum) throws IOException { RandomAccessFileOrArray f = reader.getSafeFile(); byte[] contentBytes = reader.getPageContent(pageNum, f); f.close(); return contentBytes; }
/** * Writes information about a specific page from PdfReader to the specified output stream. * @since 2.1.5 * @param reader the PdfReader to read the page content from * @param pageNum the page number to read * @param out the output stream to send the content to * @throws IOException */ static public void listContentStreamForPage(PdfReader reader, int pageNum, PrintWriter out) throws IOException { out.println("==============Page " + pageNum + "===================="); out.println("- - - - - Dictionary - - - - - -"); PdfDictionary pageDictionary = reader.getPageN(pageNum); out.println(getDictionaryDetail(pageDictionary)); out.println("- - - - - Content Stream - - - - - -"); RandomAccessFileOrArray f = reader.getSafeFile(); byte[] contentBytes = reader.getPageContent(pageNum, f); f.close(); InputStream is = new ByteArrayInputStream(contentBytes); int ch; while ((ch = is.read()) != -1){ out.print((char)ch); } out.println("- - - - - Text Extraction - - - - - -"); PdfTextExtractor extractor = new PdfTextExtractor(reader); String extractedText = extractor.getTextFromPage(pageNum); if (extractedText.length() != 0) out.println(extractedText); else out.println("No text found on page " + pageNum); out.println(); }
/** Gets the number of pages the TIFF document has. * @param s the file source * @return the number of pages */ public static int getNumberOfPages(RandomAccessFileOrArray s) { try { return TIFFDirectory.getNumDirectories(s); } catch (Exception e) { throw new ExceptionConverter(e); } }
/** * Gets a byte array that can be used as a /JBIG2Globals, * or null if not applicable to the given jbig2. * @param ra an random access file or array * @return a byte array */ public static byte[] getGlobalSegment(RandomAccessFileOrArray ra ) { try { JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.read(); return sr.getGlobal(true); } catch (Exception e) { return null; } }
/** * returns an Image representing the given page. * @param ra the file or array containing the image * @param page the page number of the image * @return an Image object */ public static Image getJbig2Image(RandomAccessFileOrArray ra, int page) { if (page < 1) throw new IllegalArgumentException("The page number must be >= 1."); try { JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.read(); JBIG2SegmentReader.JBIG2Page p = sr.getPage(page); Image img = new ImgJBIG2(p.pageBitmapWidth, p.pageBitmapHeight, p.getData(true), sr.getGlobal(true)); return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
/*** * Gets the number of pages in a JBIG2 image. * @param ra a random acces file array containing a JBIG2 image * @return the number of pages */ public static int getNumberOfPages(RandomAccessFileOrArray ra) { try { JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.read(); return sr.numberOfPages(); } catch (Exception e) { throw new ExceptionConverter(e); } }
/** * Constructs a TIFFDirectory by reading a SeekableStream. * The ifd_offset parameter specifies the stream offset from which * to begin reading; this mechanism is sometimes used to store * private IFDs within a TIFF file that are not part of the normal * sequence of IFDs. * * @param stream a SeekableStream to read from. * @param ifd_offset the long byte offset of the directory. * @param directory the index of the directory to read beyond the * one at the current stream offset; zero indicates the IFD * at the current offset. */ public TIFFDirectory(RandomAccessFileOrArray stream, long ifd_offset, int directory) throws IOException { long global_save_offset = stream.getFilePointer(); stream.seek(0L); int endian = stream.readUnsignedShort(); if (!isValidEndianTag(endian)) { throw new IllegalArgumentException("Bad endianness tag (not 0x4949 or 0x4d4d)."); } isBigEndian = (endian == 0x4d4d); // Seek to the first IFD. stream.seek(ifd_offset); // Seek to desired IFD if necessary. int dirNum = 0; while(dirNum < directory) { // Get the number of fields in the current IFD. int numEntries = readUnsignedShort(stream); // Skip to the next IFD offset value field. stream.seek(ifd_offset + 12*numEntries); // Read the offset to the next IFD beyond this one. ifd_offset = readUnsignedInt(stream); // Seek to the next IFD. stream.seek(ifd_offset); // Increment the directory. dirNum++; } initialize(stream); stream.seek(global_save_offset); }
private short readShort(RandomAccessFileOrArray stream) throws IOException { if (isBigEndian) { return stream.readShort(); } else { return stream.readShortLE(); } }
private int readUnsignedShort(RandomAccessFileOrArray stream) throws IOException { if (isBigEndian) { return stream.readUnsignedShort(); } else { return stream.readUnsignedShortLE(); } }
private int readInt(RandomAccessFileOrArray stream) throws IOException { if (isBigEndian) { return stream.readInt(); } else { return stream.readIntLE(); } }
private long readUnsignedInt(RandomAccessFileOrArray stream) throws IOException { if (isBigEndian) { return stream.readUnsignedInt(); } else { return stream.readUnsignedIntLE(); } }
@SuppressWarnings("unused") private long readLong(RandomAccessFileOrArray stream) throws IOException { if (isBigEndian) { return stream.readLong(); } else { return stream.readLongLE(); } }
private float readFloat(RandomAccessFileOrArray stream) throws IOException { if (isBigEndian) { return stream.readFloat(); } else { return stream.readFloatLE(); } }
private double readDouble(RandomAccessFileOrArray stream) throws IOException { if (isBigEndian) { return stream.readDouble(); } else { return stream.readDoubleLE(); } }
private static int readUnsignedShort(RandomAccessFileOrArray stream, boolean isBigEndian) throws IOException { if (isBigEndian) { return stream.readUnsignedShort(); } else { return stream.readUnsignedShortLE(); } }
private static long readUnsignedInt(RandomAccessFileOrArray stream, boolean isBigEndian) throws IOException { if (isBigEndian) { return stream.readUnsignedInt(); } else { return stream.readUnsignedIntLE(); } }
/** * Returns the number of image directories (subimages) stored in a * given TIFF file, represented by a <code>SeekableStream</code>. */ public static int getNumDirectories(RandomAccessFileOrArray stream) throws IOException{ long pointer = stream.getFilePointer(); // Save stream pointer stream.seek(0L); int endian = stream.readUnsignedShort(); if (!isValidEndianTag(endian)) { throw new IllegalArgumentException("Bad endianness tag (not 0x4949 or 0x4d4d)."); } boolean isBigEndian = (endian == 0x4d4d); int magic = readUnsignedShort(stream, isBigEndian); if (magic != 42) { throw new IllegalArgumentException("Bad magic number, should be 42."); } stream.seek(4L); long offset = readUnsignedInt(stream, isBigEndian); int numDirectories = 0; while (offset != 0L) { ++numDirectories; // EOFException means IFD was probably not properly terminated. try { stream.seek(offset); int entries = readUnsignedShort(stream, isBigEndian); stream.skip(12*entries); offset = readUnsignedInt(stream, isBigEndian); } catch(EOFException eof) { //numDirectories--; break; } } stream.seek(pointer); // Reset stream pointer return numDirectories; }
/** * Combines 2 tiff-files into 1 PDF (similar to tiffmesh). * * @param args * [0] the file with the odd pages [1] the file with the even * pages [2] the resulting file */ public void main(String... args) throws Exception { if (args.length < 3) { System.err.println("OddEven needs 3 Arguments."); System.out .println("Usage: com.lowagie.examples.objects.images.tiff.OddEven odd_file.tif even_file.tif combined_file.pdf"); return; } RandomAccessFileOrArray odd = new RandomAccessFileOrArray(args[0]); RandomAccessFileOrArray even = new RandomAccessFileOrArray(args[1]); Image img = TiffImage.getTiffImage(odd, 1); Document document = new Document(new Rectangle(img.getScaledWidth(), img.getScaledHeight())); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(args[2])); document.open(); PdfContentByte cb = writer.getDirectContent(); int count = Math.max(TiffImage.getNumberOfPages(odd), TiffImage.getNumberOfPages(even)); for (int c = 0; c < count; ++c) { Image imgOdd = TiffImage.getTiffImage(odd, c + 1); Image imgEven = TiffImage.getTiffImage(even, count - c); document.setPageSize(new Rectangle(imgOdd.getScaledWidth(), imgOdd.getScaledHeight())); document.newPage(); imgOdd.setAbsolutePosition(0, 0); cb.addImage(imgOdd); document.setPageSize(new Rectangle(imgEven.getScaledWidth(), imgEven.getScaledHeight())); document.newPage(); imgEven.setAbsolutePosition(0, 0); cb.addImage(imgEven); } odd.close(); even.close(); document.close(); }
public boolean findPdfString(PdfReader reader, String string) throws Exception { byte[] streamBytes = reader.getPageContent(1); LOG.debug("Finding string {} in pdf", string); PRTokeniser tokenizer = new PRTokeniser(new RandomAccessFileOrArray(streamBytes)); while (tokenizer.nextToken()) { if (tokenizer.getTokenType() == PRTokeniser.TK_STRING) { LOG.debug("Found String in pdf: " + tokenizer.getStringValue()); if (tokenizer.getStringValue().equals(string)) { return true; } } } return false; }
public void initialize( String displayName ) throws IOException { int[] tableLocation = (int[]) positionTables.get( "loca" ); int locaLength = tableLocation[1]; int glyphCount = locaLength / head.locaBytesPerEntry - 1; rf = new RandomAccessFileOrArray( fileName ); out.println( "18 dict begin" ); out.println( "/CIDFontName /" + fontName + " def"); out.println( "/PaintType 0 def" ); out.println( "/FontType 42 def" ); out.println( "/CIDFontType 2 def" ); out.println( "/GDBytes 2 def" ); out.println( "/CIDSystemInfo 3 dict dup begin" ); out.println( " /Registry (Adobe) def" ); out.println( " /Ordering (Identity) def" ); out.println( " /Supplement 0 def" ); out.println( "end def" ); out.println( "/FontMatrix matrix def" ); out.println( "/FontBBox " + getFontBBox( ) + " def" ); out.println( "/CIDCount " + glyphCount + " def"); out.println( "/CDevProc {pop pop pop pop pop 0 -1 7 index 2 div .88}bind def"); out.println( "/CharStrings 1 dict dup begin /.notdef 0 def end def" ); out.println( "/Encoding 1 array dup 0 /.notdef put readonly def" ); out.println( "/GlyphDirectory 16 dict def" ); outputSfnts( out ); outputCIDMap( out, glyphCount ); out.println( "CIDFontName currentdict end /CIDFont defineresource pop" ); this.displayName = displayName.replace( ' ', '_' ); out.println( "/" + displayName + " /Identity-H [/" + fontName + "] composefont pop" ); }
private void addTiff(final File file, final Document document, final PdfWriter writer) throws Exception { RandomAccessFileOrArray randomAccess = createRamdomAccessSource(file); int pages = getPageCount(file); for (int i = 1; i <= pages; i++) { Image image = TiffImage.getTiffImage(randomAccess, i); addImage(image, document, writer); } }
private long readLong(RandomAccessFileOrArray stream) throws IOException { if (isBigEndian) { return stream.readLong(); } else { return stream.readLongLE(); } }