|
| 1 | +package com.itextpdf.rups.view.itext; |
| 2 | + |
| 3 | +import com.itextpdf.io.source.PdfTokenizer; |
| 4 | +import com.itextpdf.io.source.RandomAccessFileOrArray; |
| 5 | +import com.itextpdf.io.source.RandomAccessSourceFactory; |
| 6 | +import com.itextpdf.kernel.pdf.PdfName; |
| 7 | +import com.itextpdf.kernel.pdf.PdfStream; |
| 8 | +import com.itextpdf.rups.model.LoggerHelper; |
| 9 | +import com.itextpdf.rups.view.Console; |
| 10 | + |
| 11 | +import java.io.IOException; |
| 12 | +import java.util.Arrays; |
| 13 | + |
| 14 | +/** |
| 15 | + * Utility class to parse ObjectStreams to extract the offset of a given object id within the stream. |
| 16 | + */ |
| 17 | +public class ObjectStreamParser { |
| 18 | + |
| 19 | + /** |
| 20 | + * Parses an ObjectStream to find the offset to the passed parameter, compressedObjectNumber. This offset is |
| 21 | + * relative to the ObjectStream and not to the complete file, as described in the specification. |
| 22 | + * |
| 23 | + * If an Object ID isn't found inside the ObjectStream, this will return -1. |
| 24 | + * |
| 25 | + * @param objStm The ObjectStream to parse |
| 26 | + * @param compressedObjectNumber the ID of the object of which you want the offset |
| 27 | + * @return the offset of the object or -1 if the object is not found |
| 28 | + */ |
| 29 | + public int parseObjectStream(PdfStream objStm, int compressedObjectNumber) { |
| 30 | + byte[] objStmBytes = objStm.getBytes(true); |
| 31 | + int byteOffsetOfFirst = objStm.getAsInt(PdfName.First); |
| 32 | + |
| 33 | + PdfTokenizer pdfTokenizer = new PdfTokenizer( |
| 34 | + new RandomAccessFileOrArray( |
| 35 | + new RandomAccessSourceFactory() |
| 36 | + .createSource( |
| 37 | + Arrays.copyOfRange(objStmBytes, 0, byteOffsetOfFirst)))); |
| 38 | + |
| 39 | + try { |
| 40 | + while (pdfTokenizer.nextToken()) { |
| 41 | + if ( pdfTokenizer.getTokenType().equals(PdfTokenizer.TokenType.Number )) { |
| 42 | + int objNumber = pdfTokenizer.getIntValue(); |
| 43 | + pdfTokenizer.nextToken(); |
| 44 | + if ( objNumber == compressedObjectNumber ) { |
| 45 | + return pdfTokenizer.getIntValue(); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + } catch (IOException e) { |
| 50 | + LoggerHelper.error(e.getMessage(), e, ObjectStreamParser.class); |
| 51 | + return -1; |
| 52 | + } |
| 53 | + |
| 54 | + return -1; |
| 55 | + } |
| 56 | +} |
0 commit comments