740
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
private void writeObject(java.io.ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
type = TYPE_UNKNOWN;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Utilities.java
static public void skip(final InputStream is, int size) throws IOException {
long n;
while (size > 0) {
n = is.skip(size);
if (n <= 0)
break;
size -= n;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Utilities.java
public static String readFileToString(final String path) throws IOException {
return readFileToString(new File(path));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Utilities.java
public static String readFileToString(final File file) throws IOException {
byte[] jsBytes = new byte[(int) file.length()];
FileInputStream f = new FileInputStream(file);
f.read(jsBytes);
return new String(jsBytes);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/XmlToTxt.java
public static String parse(InputStream is) throws IOException {
XmlToTxt handler = new XmlToTxt();
SimpleXMLParser.parse(handler, null, new InputStreamReader(is), true);
return handler.toString();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/SimpleXMLParser.java
private void go(final Reader r) throws IOException {
BufferedReader reader;
if (r instanceof BufferedReader)
reader = (BufferedReader)r;
else
reader = new BufferedReader(r);
doc.startDocument();
while(true) {
// read a new character
if (previousCharacter == -1) {
character = reader.read();
}
// or re-examine the previous character
else {
character = previousCharacter;
previousCharacter = -1;
}
// the end of the file was reached
if (character == -1) {
if (html) {
if (html && state == TEXT)
flush();
doc.endDocument();
} else {
throwException(MessageLocalization.getComposedMessage("missing.end.tag"));
}
return;
}
// dealing with \n and \r
if (character == '\n' && eol) {
eol = false;
continue;
} else if (eol) {
eol = false;
} else if (character == '\n') {
lines++;
columns = 0;
} else if (character == '\r') {
eol = true;
character = '\n';
lines++;
columns = 0;
} else {
columns++;
}
switch(state) {
// we are in an unknown state before there's actual content
case UNKNOWN:
if(character == '<') {
saveState(TEXT);
state = TAG_ENCOUNTERED;
}
break;
// we can encounter any content
case TEXT:
if(character == '<') {
flush();
saveState(state);
state = TAG_ENCOUNTERED;
} else if(character == '&') {
saveState(state);
entity.setLength(0);
state = ENTITY;
nowhite = true;
} else if (character == ' ') {
if (html && nowhite) {
text.append(' ');
nowhite = false;
} else {
if (nowhite){
text.append((char)character);
}
nowhite = false;
}
} else if (Character.isWhitespace((char)character)) {
if (html) {
// totally ignore other whitespace
} else {
if (nowhite){
text.append((char)character);
}
nowhite = false;
}
} else {
text.append((char)character);
nowhite = true;
}
break;
// we have just seen a < and are wondering what we are looking at
// <foo>, </foo>, <!-- ... --->, etc.
case TAG_ENCOUNTERED:
initTag();
if(character == '/') {
state = IN_CLOSETAG;
} else if (character == '?') {
restoreState();
state = PI;
} else {
text.append((char)character);
state = EXAMIN_TAG;
}
break;
// we are processing something like this <foo ... >.
// It could still be a <!-- ... --> or something.
case EXAMIN_TAG:
if(character == '>') {
doTag();
processTag(true);
initTag();
state = restoreState();
} else if(character == '/') {
state = SINGLE_TAG;
} else if(character == '-' && text.toString().equals("!-")) {
flush();
state = COMMENT;
} else if(character == '[' && text.toString().equals("![CDATA")) {
flush();
state = CDATA;
} else if(character == 'E' && text.toString().equals("!DOCTYP")) {
flush();
state = PI;
} else if(Character.isWhitespace((char)character)) {
doTag();
state = TAG_EXAMINED;
} else {
text.append((char)character);
}
break;
// we know the name of the tag now.
case TAG_EXAMINED:
if(character == '>') {
processTag(true);
initTag();
state = restoreState();
} else if(character == '/') {
state = SINGLE_TAG;
} else if(Character.isWhitespace((char)character)) {
// empty
} else {
text.append((char)character);
state = ATTRIBUTE_KEY;
}
break;
// we are processing a closing tag: e.g. </foo>
case IN_CLOSETAG:
if(character == '>') {
doTag();
processTag(false);
if(!html && nested==0) return;
state = restoreState();
} else {
if (!Character.isWhitespace((char)character))
text.append((char)character);
}
break;
// we have just seen something like this: <foo a="b"/
// and are looking for the final >.
case SINGLE_TAG:
if(character != '>')
throwException(MessageLocalization.getComposedMessage("expected.gt.for.tag.lt.1.gt", tag));
doTag();
processTag(true);
processTag(false);
initTag();
if(!html && nested==0) {
doc.endDocument();
return;
}
state = restoreState();
break;
// we are processing CDATA
case CDATA:
if(character == '>'
&& text.toString().endsWith("]]")) {
text.setLength(text.length()-2);
flush();
state = restoreState();
} else
text.append((char)character);
break;
// we are processing a comment. We are inside
// the <!-- .... --> looking for the -->.
case COMMENT:
if(character == '>'
&& text.toString().endsWith("--")) {
text.setLength(text.length() - 2);
flush();
state = restoreState();
} else
text.append((char)character);
break;
// We are inside one of these <? ... ?> or one of these <!DOCTYPE ... >
case PI:
if(character == '>') {
state = restoreState();
if(state == TEXT) state = UNKNOWN;
}
break;
// we are processing an entity, e.g. <, », etc.
case ENTITY:
if(character == ';') {
state = restoreState();
String cent = entity.toString();
entity.setLength(0);
char ce = EntitiesToUnicode.decodeEntity(cent);
if (ce == '\0')
text.append('&').append(cent).append(';');
else
text.append(ce);
} else if (character != '#' && (character < '0' || character > '9') && (character < 'a' || character > 'z')
&& (character < 'A' || character > 'Z') || entity.length() >= 7) {
state = restoreState();
previousCharacter = character;
text.append('&').append(entity.toString());
entity.setLength(0);
}
else {
entity.append((char)character);
}
break;
// We are processing the quoted right-hand side of an element's attribute.
case QUOTE:
if (html && quoteCharacter == ' ' && character == '>') {
flush();
processTag(true);
initTag();
state = restoreState();
}
else if (html && quoteCharacter == ' ' && Character.isWhitespace((char)character)) {
flush();
state = TAG_EXAMINED;
}
else if (html && quoteCharacter == ' ') {
text.append((char)character);
}
else if(character == quoteCharacter) {
flush();
state = TAG_EXAMINED;
} else if(" \r\n\u0009".indexOf(character)>=0) {
text.append(' ');
} else if(character == '&') {
saveState(state);
state = ENTITY;
entity.setLength(0);
} else {
text.append((char)character);
}
break;
case ATTRIBUTE_KEY:
if(Character.isWhitespace((char)character)) {
flush();
state = ATTRIBUTE_EQUAL;
} else if(character == '=') {
flush();
state = ATTRIBUTE_VALUE;
} else if (html && character == '>') {
text.setLength(0);
processTag(true);
initTag();
state = restoreState();
} else {
text.append((char)character);
}
break;
case ATTRIBUTE_EQUAL:
if(character == '=') {
state = ATTRIBUTE_VALUE;
} else if(Character.isWhitespace((char)character)) {
// empty
} else if (html && character == '>') {
text.setLength(0);
processTag(true);
initTag();
state = restoreState();
} else if (html && character == '/') {
flush();
state = SINGLE_TAG;
} else if (html) {
flush();
text.append((char)character);
state = ATTRIBUTE_KEY;
} else {
throwException(MessageLocalization.getComposedMessage("error.in.attribute.processing"));
}
break;
case ATTRIBUTE_VALUE:
if(character == '"' || character == '\'') {
quoteCharacter = character;
state = QUOTE;
} else if(Character.isWhitespace((char)character)) {
// empty
} else if (html && character == '>') {
flush();
processTag(true);
initTag();
state = restoreState();
} else if (html) {
text.append((char)character);
quoteCharacter = ' ';
state = QUOTE;
} else {
throwException(MessageLocalization.getComposedMessage("error.in.attribute.processing"));
}
break;
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/SimpleXMLParser.java
private void throwException(final String s) throws IOException {
throw new IOException(MessageLocalization.getComposedMessage("1.near.line.2.column.3", s, String.valueOf(lines), String.valueOf(columns)));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/SimpleXMLParser.java
public static void parse(final SimpleXMLDocHandler doc, final SimpleXMLDocHandlerComment comment, final Reader r, final boolean html) throws IOException {
SimpleXMLParser parser = new SimpleXMLParser(doc, comment, html);
parser.go(r);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/SimpleXMLParser.java
public static void parse(final SimpleXMLDocHandler doc, final InputStream in) throws IOException {
byte b4[] = new byte[4];
int count = in.read(b4);
if (count != 4)
throw new IOException(MessageLocalization.getComposedMessage("insufficient.length"));
String encoding = XMLUtil.getEncodingName(b4);
String decl = null;
if (encoding.equals("UTF-8")) {
StringBuffer sb = new StringBuffer();
int c;
while ((c = in.read()) != -1) {
if (c == '>')
break;
sb.append((char)c);
}
decl = sb.toString();
}
else if (encoding.equals("CP037")) {
ByteArrayOutputStream bi = new ByteArrayOutputStream();
int c;
while ((c = in.read()) != -1) {
if (c == 0x6e) // that's '>' in ebcdic
break;
bi.write(c);
}
decl = new String(bi.toByteArray(), "CP037");
}
if (decl != null) {
decl = getDeclaredEncoding(decl);
if (decl != null)
encoding = decl;
}
parse(doc, new InputStreamReader(in, IanaEncodings.getJavaEncoding(encoding)));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/SimpleXMLParser.java
public static void parse(final SimpleXMLDocHandler doc,final Reader r) throws IOException {
parse(doc, null, r, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/xmp/XmpReader.java
public byte[] serializeDoc() throws IOException {
XmlDomWriter xw = new XmlDomWriter();
ByteArrayOutputStream fout = new ByteArrayOutputStream();
xw.setOutput(fout, null);
fout.write(XmpWriter.XPACKET_PI_BEGIN.getBytes("UTF-8"));
fout.flush();
NodeList xmpmeta = domDocument.getElementsByTagName("x:xmpmeta");
xw.write(xmpmeta.item(0));
fout.flush();
for (int i = 0; i < 20; i++) {
fout.write(XmpWriter.EXTRASPACE.getBytes());
}
fout.write(XmpWriter.XPACKET_PI_END_W.getBytes());
fout.close();
return fout.toByteArray();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/xmp/XmpWriter.java
public void addRdfDescription(String xmlns, String content) throws IOException {
writer.write("<rdf:Description rdf:about=\"");
writer.write(about);
writer.write("\" ");
writer.write(xmlns);
writer.write(">");
writer.write(content);
writer.write("</rdf:Description>\n");
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/xmp/XmpWriter.java
public void addRdfDescription(XmpSchema s) throws IOException {
writer.write("<rdf:Description rdf:about=\"");
writer.write(about);
writer.write("\" ");
writer.write(s.getXmlns());
writer.write(">");
writer.write(s.toString());
writer.write("</rdf:Description>\n");
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/xmp/XmpWriter.java
public void close() throws IOException {
writer.write("</rdf:RDF>");
writer.write("</x:xmpmeta>\n");
for (int i = 0; i < extraSpace; i++) {
writer.write(EXTRASPACE);
}
writer.write(end == 'r' ? XPACKET_PI_END_R : XPACKET_PI_END_W);
writer.flush();
writer.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/StreamUtil.java
public static byte[] inputStreamToArray(InputStream is) throws IOException {
byte b[] = new byte[8192];
ByteArrayOutputStream out = new ByteArrayOutputStream();
while (true) {
int read = is.read(b);
if (read < 1)
break;
out.write(b, 0, read);
}
out.close();
return out.toByteArray();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/StreamUtil.java
public static void CopyBytes(RandomAccessSource source, long start, long length, OutputStream outs) throws IOException {
if (length <= 0)
return;
long idx = start;
byte[] buf = new byte[8192];
while (length > 0) {
long n = source.get(idx, buf,0, (int)Math.min((long)buf.length, length));
if (n <= 0)
throw new EOFException();
outs.write(buf, 0, (int)n);
idx += n;
length -= n;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/PagedChannelRandomAccessSource.java
private static RandomAccessSource[] buildSources(final FileChannel channel, final int bufferSize) throws IOException{
long size = channel.size();
int bufferCount = (int)(size/bufferSize) + (size % bufferSize == 0 ? 0 : 1);
MappedChannelRandomAccessSource[] sources = new MappedChannelRandomAccessSource[bufferCount];
for (int i = 0; i < bufferCount; i++){
long pageOffset = (long)i*bufferSize;
long pageLength = Math.min(size - pageOffset, bufferSize);
sources[i] = new MappedChannelRandomAccessSource(channel, pageOffset, pageLength);
}
return sources;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/IndependentRandomAccessSource.java
public int get(long position) throws IOException {
return source.get(position);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/IndependentRandomAccessSource.java
public int get(long position, byte[] bytes, int off, int len) throws IOException {
return source.get(position, bytes, off, len);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/IndependentRandomAccessSource.java
public void close() throws IOException {
// do not close the source
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/ByteBufferRandomAccessSource.java
public int get(long position) throws IOException {
if (position > Integer.MAX_VALUE)
throw new IllegalArgumentException("Position must be less than Integer.MAX_VALUE");
try {
if (position >= byteBuffer.limit())
return -1;
byte b = byteBuffer.get((int)position);
int n = b & 0xff;
return n;
} catch (BufferUnderflowException e) {
return -1; // EOF
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/ByteBufferRandomAccessSource.java
public int get(long position, byte[] bytes, int off, int len) throws IOException {
if (position > Integer.MAX_VALUE)
throw new IllegalArgumentException("Position must be less than Integer.MAX_VALUE");
if (position >= byteBuffer.limit())
return -1;
byteBuffer.position((int)position);
int bytesFromThisBuffer = Math.min(len, byteBuffer.remaining());
byteBuffer.get(bytes, off, bytesFromThisBuffer);
return bytesFromThisBuffer;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/ByteBufferRandomAccessSource.java
public void close() throws IOException {
clean(byteBuffer);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/GroupedRandomAccessSource.java
private SourceEntry getSourceEntryForOffset(long offset) throws IOException {
if (offset >= size)
return null;
if (offset >= currentSourceEntry.firstByte && offset <= currentSourceEntry.lastByte)
return currentSourceEntry;
// hook to allow subclasses to release resources if necessary
sourceReleased(currentSourceEntry.source);
int startAt = getStartingSourceIndex(offset);
for(int i = startAt; i < sources.length; i++){
if (offset >= sources[i].firstByte && offset <= sources[i].lastByte){
currentSourceEntry = sources[i];
sourceInUse(currentSourceEntry.source);
return currentSourceEntry;
}
}
return null;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/GroupedRandomAccessSource.java
protected void sourceReleased(RandomAccessSource source) throws IOException{
// by default, do nothing
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/GroupedRandomAccessSource.java
protected void sourceInUse(RandomAccessSource source) throws IOException{
// by default, do nothing
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/GroupedRandomAccessSource.java
public int get(long position) throws IOException {
SourceEntry entry = getSourceEntryForOffset(position);
if (entry == null) // we have run out of data to read from
return -1;
return entry.source.get(entry.offsetN(position));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/GroupedRandomAccessSource.java
public int get(long position, byte[] bytes, int off, int len) throws IOException {
SourceEntry entry = getSourceEntryForOffset(position);
if (entry == null) // we have run out of data to read from
return -1;
long offN = entry.offsetN(position);
int remaining = len;
while(remaining > 0){
if (entry == null) // we have run out of data to read from
break;
if (offN > entry.source.length())
break;
int count = entry.source.get(offN, bytes, off, remaining);
if (count == -1)
break;
off += count;
position += count;
remaining -= count;
offN = 0;
entry = getSourceEntryForOffset(position);
}
return remaining == len ? -1 : len - remaining;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/GroupedRandomAccessSource.java
public void close() throws IOException {
for (SourceEntry entry : sources) {
entry.source.close();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/ArrayRandomAccessSource.java
public void close() throws IOException {
array = null;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/FileChannelRandomAccessSource.java
public void close() throws IOException {
source.close();
channel.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/FileChannelRandomAccessSource.java
public int get(long position) throws IOException {
return source.get(position);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/FileChannelRandomAccessSource.java
public int get(long position, byte[] bytes, int off, int len) throws IOException {
return source.get(position, bytes, off, len);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/WindowRandomAccessSource.java
public int get(long position) throws IOException {
if (position >= length) return -1;
return source.get(offset + position);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/WindowRandomAccessSource.java
public int get(long position, byte[] bytes, int off, int len) throws IOException {
if (position >= length)
return -1;
long toRead = Math.min(len, length - position);
return source.get(offset + position, bytes, off, (int)toRead);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/WindowRandomAccessSource.java
public void close() throws IOException {
source.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
public RandomAccessSource createSource(RandomAccessFile raf) throws IOException {
return new RAFRandomAccessSource(raf);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
public RandomAccessSource createSource(URL url) throws IOException{
InputStream is = url.openStream();
try {
return createSource(is);
}
finally {
try {is.close();}catch(IOException ioe){}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
public RandomAccessSource createSource(InputStream is) throws IOException{
try {
return createSource(StreamUtil.inputStreamToArray(is));
}
finally {
try {is.close();}catch(IOException ioe){}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
public RandomAccessSource createBestSource(String filename) throws IOException{
File file = new File(filename);
if (!file.canRead()){
if (filename.startsWith("file:/")
|| filename.startsWith("http://")
|| filename.startsWith("https://")
|| filename.startsWith("jar:")
|| filename.startsWith("wsjar:")
|| filename.startsWith("wsjar:")
|| filename.startsWith("vfszip:")) {
return createSource(new URL(filename));
} else {
return createByReadingToMemory(filename);
}
}
if (forceRead){
return createByReadingToMemory(new FileInputStream(filename));
}
String openMode = exclusivelyLockFile ? "rw" : "r";
@SuppressWarnings("resource") // the RAF will be closed by the RAFRandomAccessSource, FileChannelRandomAccessSource or PagedChannelRandomAccessSource
RandomAccessFile raf = new RandomAccessFile(file, openMode);
if (exclusivelyLockFile){
raf.getChannel().lock();
}
if (usePlainRandomAccess){
return new RAFRandomAccessSource(raf);
}
try{
FileChannel channel = raf.getChannel();
if (channel.size() <= PagedChannelRandomAccessSource.DEFAULT_TOTAL_BUFSIZE){ // if less than the fully mapped usage of PagedFileChannelRandomAccessSource, just map the whole thing and be done with it
return new GetBufferedRandomAccessSource(new FileChannelRandomAccessSource(channel));
} else {
return new GetBufferedRandomAccessSource(new PagedChannelRandomAccessSource(channel));
}
} catch (MapFailedException e){
return new RAFRandomAccessSource(raf);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
public RandomAccessSource createRanged(RandomAccessSource source, long[] ranges) throws IOException{
RandomAccessSource[] sources = new RandomAccessSource[ranges.length/2];
for(int i = 0; i < ranges.length; i+=2){
sources[i/2] = new WindowRandomAccessSource(source, ranges[i], ranges[i+1]);
}
return new GroupedRandomAccessSource(sources);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
private RandomAccessSource createByReadingToMemory(String filename) throws IOException {
//TODO: seems odd that we are using BaseFont here...
InputStream is = BaseFont.getResourceStream(filename);
if (is == null)
throw new IOException(MessageLocalization.getComposedMessage("1.not.found.as.file.or.resource", filename));
return createByReadingToMemory(is);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
private RandomAccessSource createByReadingToMemory(InputStream is) throws IOException {
try {
return new ArrayRandomAccessSource(StreamUtil.inputStreamToArray(is));
}
finally {
try {is.close();}catch(IOException ioe){}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/GetBufferedRandomAccessSource.java
public int get(long position) throws IOException {
if (position < getBufferStart || position > getBufferEnd){
int count = source.get(position, getBuffer, 0, getBuffer.length);
if (count == -1)
return -1;
getBufferStart = position;
getBufferEnd = position + count - 1;
}
int bufPos = (int)(position-getBufferStart);
return 0xff & getBuffer[bufPos];
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/GetBufferedRandomAccessSource.java
public int get(long position, byte[] bytes, int off, int len) throws IOException {
return source.get(position, bytes, off, len);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/GetBufferedRandomAccessSource.java
public void close() throws IOException {
source.close();
getBufferStart = -1;
getBufferEnd = -1;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
void open() throws IOException {
if (source != null)
return;
if (!channel.isOpen())
throw new IllegalStateException("Channel is closed");
try{
source = new ByteBufferRandomAccessSource(channel.map(FileChannel.MapMode.READ_ONLY, offset, length));
} catch (IOException e){
if (exceptionIsMapFailureException(e))
throw new MapFailedException(e);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
public int get(long position) throws IOException {
return source.get(position);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
public int get(long position, byte[] bytes, int off, int len) throws IOException {
return source.get(position, bytes, off, len);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
public void close() throws IOException {
if (source == null)
return;
source.close();
source = null;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RAFRandomAccessSource.java
public int get(long position) throws IOException {
if (position > raf.length())
return -1;
// Not thread safe!
raf.seek(position);
return raf.read();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RAFRandomAccessSource.java
public int get(long position, byte[] bytes, int off, int len) throws IOException {
if (position > length)
return -1;
// Not thread safe!
raf.seek(position);
return raf.read(bytes, off, len);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RAFRandomAccessSource.java
public void close() throws IOException {
raf.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final URL url) throws BadElementException,
MalformedURLException, IOException {
InputStream is = null;
try {
is = url.openStream();
int c1 = is.read();
int c2 = is.read();
int c3 = is.read();
int c4 = is.read();
// jbig2
int c5 = is.read();
int c6 = is.read();
int c7 = is.read();
int c8 = is.read();
is.close();
is = null;
if (c1 == 'G' && c2 == 'I' && c3 == 'F') {
GifImage gif = new GifImage(url);
Image img = gif.getImage(1);
return img;
}
if (c1 == 0xFF && c2 == 0xD8) {
return new Jpeg(url);
}
if (c1 == 0x00 && c2 == 0x00 && c3 == 0x00 && c4 == 0x0c) {
return new Jpeg2000(url);
}
if (c1 == 0xff && c2 == 0x4f && c3 == 0xff && c4 == 0x51) {
return new Jpeg2000(url);
}
if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) {
return PngImage.getImage(url);
}
if (c1 == 0xD7 && c2 == 0xCD) {
return new ImgWMF(url);
}
if (c1 == 'B' && c2 == 'M') {
return BmpImage.getImage(url);
}
if (c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42
|| c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0) {
RandomAccessFileOrArray ra = null;
try {
if (url.getProtocol().equals("file")) {
String file = url.getFile();
file = Utilities.unEscapeURL(file);
ra = new RandomAccessFileOrArray(file);
} else
ra = new RandomAccessFileOrArray(url);
Image img = TiffImage.getTiffImage(ra, 1);
img.url = url;
return img;
} finally {
if (ra != null)
ra.close();
}
}
if ( c1 == 0x97 && c2 == 'J' && c3 == 'B' && c4 == '2' &&
c5 == '\r' && c6 == '\n' && c7 == 0x1a && c8 == '\n' ) {
RandomAccessFileOrArray ra = null;
try {
if (url.getProtocol().equals("file")) {
String file = url.getFile();
file = Utilities.unEscapeURL(file);
ra = new RandomAccessFileOrArray(file);
} else
ra = new RandomAccessFileOrArray(url);
Image img = JBIG2Image.getJbig2Image(ra, 1);
img.url = url;
return img;
} finally {
if (ra != null)
ra.close();
}
}
throw new IOException(url.toString()
+ " is not a recognized imageformat.");
} finally {
if (is != null) {
is.close();
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final String filename)
throws BadElementException, MalformedURLException, IOException {
return getInstance(Utilities.toURL(filename));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final byte imgb[]) throws BadElementException,
MalformedURLException, IOException {
InputStream is = null;
try {
is = new java.io.ByteArrayInputStream(imgb);
int c1 = is.read();
int c2 = is.read();
int c3 = is.read();
int c4 = is.read();
is.close();
is = null;
if (c1 == 'G' && c2 == 'I' && c3 == 'F') {
GifImage gif = new GifImage(imgb);
return gif.getImage(1);
}
if (c1 == 0xFF && c2 == 0xD8) {
return new Jpeg(imgb);
}
if (c1 == 0x00 && c2 == 0x00 && c3 == 0x00 && c4 == 0x0c) {
return new Jpeg2000(imgb);
}
if (c1 == 0xff && c2 == 0x4f && c3 == 0xff && c4 == 0x51) {
return new Jpeg2000(imgb);
}
if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) {
return PngImage.getImage(imgb);
}
if (c1 == 0xD7 && c2 == 0xCD) {
return new ImgWMF(imgb);
}
if (c1 == 'B' && c2 == 'M') {
return BmpImage.getImage(imgb);
}
if (c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42
|| c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0) {
RandomAccessFileOrArray ra = null;
try {
ra = new RandomAccessFileOrArray(imgb);
Image img = TiffImage.getTiffImage(ra, 1);
if (img.getOriginalData() == null)
img.setOriginalData(imgb);
return img;
} finally {
if (ra != null)
ra.close();
}
}
if ( c1 == 0x97 && c2 == 'J' && c3 == 'B' && c4 == '2' ) {
is = new java.io.ByteArrayInputStream(imgb);
is.skip(4);
int c5 = is.read();
int c6 = is.read();
int c7 = is.read();
int c8 = is.read();
if ( c5 == '\r' && c6 == '\n' && c7 == 0x1a && c8 == '\n' ) {
int file_header_flags = is.read();
// TODO number of pages never read, can be removed?
int number_of_pages = -1;
if ( (file_header_flags & 0x2) == 0x2 ) {
number_of_pages = is.read() << 24 | is.read() << 16 | is.read() << 8 | is.read();
}
is.close();
// a jbig2 file with a file header. the header is the only way we know here.
// embedded jbig2s don't have a header, have to create them by explicit use of Jbig2Image?
// nkerr, 2008-12-05 see also the getInstance(URL)
RandomAccessFileOrArray ra = null;
try {
ra = new RandomAccessFileOrArray(imgb);
Image img = JBIG2Image.getJbig2Image(ra, 1);
if (img.getOriginalData() == null)
img.setOriginalData(imgb);
return img;
} finally {
if (ra != null)
ra.close();
}
}
}
throw new IOException(MessageLocalization.getComposedMessage("the.byte.array.is.not.a.recognized.imageformat"));
} finally {
if (is != null) {
is.close();
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final java.awt.Image image, final java.awt.Color color,
boolean forceBW) throws BadElementException, IOException {
if(image instanceof java.awt.image.BufferedImage){
java.awt.image.BufferedImage bi = (java.awt.image.BufferedImage) image;
if(bi.getType() == java.awt.image.BufferedImage.TYPE_BYTE_BINARY
&& bi.getColorModel().getPixelSize() == 1) {
forceBW=true;
}
}
java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(image,
0, 0, -1, -1, true);
try {
pg.grabPixels();
} catch (InterruptedException e) {
throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels"));
}
if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) {
throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.fetch.aborted.or.errored"));
}
int w = pg.getWidth();
int h = pg.getHeight();
int[] pixels = (int[]) pg.getPixels();
if (forceBW) {
int byteWidth = w / 8 + ((w & 7) != 0 ? 1 : 0);
byte[] pixelsByte = new byte[byteWidth * h];
int index = 0;
int size = h * w;
int transColor = 1;
if (color != null) {
transColor = color.getRed() + color.getGreen()
+ color.getBlue() < 384 ? 0 : 1;
}
int transparency[] = null;
int cbyte = 0x80;
int wMarker = 0;
int currByte = 0;
if (color != null) {
for (int j = 0; j < size; j++) {
int alpha = pixels[j] >> 24 & 0xff;
if (alpha < 250) {
if (transColor == 1)
currByte |= cbyte;
} else {
if ((pixels[j] & 0x888) != 0)
currByte |= cbyte;
}
cbyte >>= 1;
if (cbyte == 0 || wMarker + 1 >= w) {
pixelsByte[index++] = (byte) currByte;
cbyte = 0x80;
currByte = 0;
}
++wMarker;
if (wMarker >= w)
wMarker = 0;
}
} else {
for (int j = 0; j < size; j++) {
if (transparency == null) {
int alpha = pixels[j] >> 24 & 0xff;
if (alpha == 0) {
transparency = new int[2];
/* bugfix by M.P. Liston, ASC, was: ... ? 1: 0; */
transparency[0] = transparency[1] = (pixels[j] & 0x888) != 0 ? 0xff : 0;
}
}
if ((pixels[j] & 0x888) != 0)
currByte |= cbyte;
cbyte >>= 1;
if (cbyte == 0 || wMarker + 1 >= w) {
pixelsByte[index++] = (byte) currByte;
cbyte = 0x80;
currByte = 0;
}
++wMarker;
if (wMarker >= w)
wMarker = 0;
}
}
return Image.getInstance(w, h, 1, 1, pixelsByte, transparency);
} else {
byte[] pixelsByte = new byte[w * h * 3];
byte[] smask = null;
int index = 0;
int size = h * w;
int red = 255;
int green = 255;
int blue = 255;
if (color != null) {
red = color.getRed();
green = color.getGreen();
blue = color.getBlue();
}
int transparency[] = null;
if (color != null) {
for (int j = 0; j < size; j++) {
int alpha = pixels[j] >> 24 & 0xff;
if (alpha < 250) {
pixelsByte[index++] = (byte) red;
pixelsByte[index++] = (byte) green;
pixelsByte[index++] = (byte) blue;
} else {
pixelsByte[index++] = (byte) (pixels[j] >> 16 & 0xff);
pixelsByte[index++] = (byte) (pixels[j] >> 8 & 0xff);
pixelsByte[index++] = (byte) (pixels[j] & 0xff);
}
}
} else {
int transparentPixel = 0;
smask = new byte[w * h];
boolean shades = false;
for (int j = 0; j < size; j++) {
byte alpha = smask[j] = (byte) (pixels[j] >> 24 & 0xff);
/* bugfix by Chris Nokleberg */
if (!shades) {
if (alpha != 0 && alpha != -1) {
shades = true;
} else if (transparency == null) {
if (alpha == 0) {
transparentPixel = pixels[j] & 0xffffff;
transparency = new int[6];
transparency[0] = transparency[1] = transparentPixel >> 16 & 0xff;
transparency[2] = transparency[3] = transparentPixel >> 8 & 0xff;
transparency[4] = transparency[5] = transparentPixel & 0xff;
}
} else if ((pixels[j] & 0xffffff) != transparentPixel) {
shades = true;
}
}
pixelsByte[index++] = (byte) (pixels[j] >> 16 & 0xff);
pixelsByte[index++] = (byte) (pixels[j] >> 8 & 0xff);
pixelsByte[index++] = (byte) (pixels[j] & 0xff);
}
if (shades)
transparency = null;
else
smask = null;
}
Image img = Image.getInstance(w, h, 3, 8, pixelsByte, transparency);
if (smask != null) {
Image sm = Image.getInstance(w, h, 1, 8, smask);
try {
sm.makeMask();
img.setImageMask(sm);
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
return img;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final java.awt.Image image, final java.awt.Color color)
throws BadElementException, IOException {
return Image.getInstance(image, color, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final PdfWriter writer, final java.awt.Image awtImage, final float quality) throws BadElementException, IOException {
return getInstance(new PdfContentByte(writer), awtImage, quality);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final PdfContentByte cb, final java.awt.Image awtImage, final float quality) throws BadElementException, IOException {
java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(awtImage,
0, 0, -1, -1, true);
try {
pg.grabPixels();
} catch (InterruptedException e) {
throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels"));
}
if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) {
throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.fetch.aborted.or.errored"));
}
int w = pg.getWidth();
int h = pg.getHeight();
PdfTemplate tp = cb.createTemplate(w, h);
PdfGraphics2D g2d = new PdfGraphics2D(tp, w, h, null, false, true, quality);
g2d.drawImage(awtImage, 0, 0, null);
g2d.dispose();
return getInstance(tp);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Jpeg.java
private static final int getShort(InputStream is) throws IOException {
return (is.read() << 8) + is.read();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Jpeg.java
private void processParameters() throws BadElementException, IOException {
type = JPEG;
originalType = ORIGINAL_JPEG;
InputStream is = null;
try {
String errorID;
if (rawData == null){
is = url.openStream();
errorID = url.toString();
}
else{
is = new java.io.ByteArrayInputStream(rawData);
errorID = "Byte array";
}
if (is.read() != 0xFF || is.read() != 0xD8) {
throw new BadElementException(MessageLocalization.getComposedMessage("1.is.not.a.valid.jpeg.file", errorID));
}
boolean firstPass = true;
int len;
while (true) {
int v = is.read();
if (v < 0)
throw new IOException(MessageLocalization.getComposedMessage("premature.eof.while.reading.jpg"));
if (v == 0xFF) {
int marker = is.read();
if (firstPass && marker == M_APP0) {
firstPass = false;
len = getShort(is);
if (len < 16) {
Utilities.skip(is, len - 2);
continue;
}
byte bcomp[] = new byte[JFIF_ID.length];
int r = is.read(bcomp);
if (r != bcomp.length)
throw new BadElementException(MessageLocalization.getComposedMessage("1.corrupted.jfif.marker", errorID));
boolean found = true;
for (int k = 0; k < bcomp.length; ++k) {
if (bcomp[k] != JFIF_ID[k]) {
found = false;
break;
}
}
if (!found) {
Utilities.skip(is, len - 2 - bcomp.length);
continue;
}
Utilities.skip(is, 2);
int units = is.read();
int dx = getShort(is);
int dy = getShort(is);
if (units == 1) {
dpiX = dx;
dpiY = dy;
}
else if (units == 2) {
dpiX = (int)(dx * 2.54f + 0.5f);
dpiY = (int)(dy * 2.54f + 0.5f);
}
Utilities.skip(is, len - 2 - bcomp.length - 7);
continue;
}
if (marker == M_APPE) {
len = getShort(is) - 2;
byte[] byteappe = new byte[len];
for (int k = 0; k < len; ++k) {
byteappe[k] = (byte)is.read();
}
if (byteappe.length >= 12) {
String appe = new String(byteappe, 0, 5, "ISO-8859-1");
if (appe.equals("Adobe")) {
invert = true;
}
}
continue;
}
if (marker == M_APP2) {
len = getShort(is) - 2;
byte[] byteapp2 = new byte[len];
for (int k = 0; k < len; ++k) {
byteapp2[k] = (byte)is.read();
}
if (byteapp2.length >= 14) {
String app2 = new String(byteapp2, 0, 11, "ISO-8859-1");
if (app2.equals("ICC_PROFILE")) {
int order = byteapp2[12] & 0xff;
int count = byteapp2[13] & 0xff;
// some jpeg producers don't know how to count to 1
if (order < 1)
order = 1;
if (count < 1)
count = 1;
if (icc == null)
icc = new byte[count][];
icc[order - 1] = byteapp2;
}
}
continue;
}
if (marker == M_APPD) {
len = getShort(is) - 2;
byte[] byteappd = new byte[len];
for (int k = 0; k < len; k++) {
byteappd[k] = (byte)is.read();
}
// search for '8BIM Resolution' marker
int k = 0;
for (k = 0; k < len-PS_8BIM_RESO.length; k++) {
boolean found = true;
for (int j = 0; j < PS_8BIM_RESO.length; j++) {
if (byteappd[k+j] != PS_8BIM_RESO[j]) {
found = false;
break;
}
}
if (found)
break;
}
k+=PS_8BIM_RESO.length;
if (k < len-PS_8BIM_RESO.length) {
// "PASCAL String" for name, i.e. string prefix with length byte
// padded to be even length; 2 null bytes if empty
byte namelength = byteappd[k];
// add length byte
namelength++;
// add padding
if (namelength % 2 == 1)
namelength++;
// just skip name
k += namelength;
// size of the resolution data
int resosize = (byteappd[k] << 24) + (byteappd[k+1] << 16) + (byteappd[k+2] << 8) + byteappd[k+3];
// should be 16
if (resosize != 16) {
// fail silently, for now
//System.err.println("DEBUG: unsupported resolution IRB size");
continue;
}
k+=4;
int dx = (byteappd[k] << 8) + (byteappd[k+1] & 0xff);
k+=2;
// skip 2 unknown bytes
k+=2;
int unitsx = (byteappd[k] << 8) + (byteappd[k+1] & 0xff);
k+=2;
// skip 2 unknown bytes
k+=2;
int dy = (byteappd[k] << 8) + (byteappd[k+1] & 0xff);
k+=2;
// skip 2 unknown bytes
k+=2;
int unitsy = (byteappd[k] << 8) + (byteappd[k+1] & 0xff);
if (unitsx == 1 || unitsx == 2) {
dx = (unitsx == 2 ? (int)(dx * 2.54f + 0.5f) : dx);
// make sure this is consistent with JFIF data
if (dpiX != 0 && dpiX != dx) {
//System.err.println("DEBUG: inconsistent metadata (dpiX: " + dpiX + " vs " + dx + ")");
}
else
dpiX = dx;
}
if (unitsy == 1 || unitsy == 2) {
dy = (unitsy == 2 ? (int)(dy * 2.54f + 0.5f) : dy);
// make sure this is consistent with JFIF data
if (dpiY != 0 && dpiY != dy) {
//System.err.println("DEBUG: inconsistent metadata (dpiY: " + dpiY + " vs " + dy + ")");
}
else
dpiY = dy;
}
}
continue;
}
firstPass = false;
int markertype = marker(marker);
if (markertype == VALID_MARKER) {
Utilities.skip(is, 2);
if (is.read() != 0x08) {
throw new BadElementException(MessageLocalization.getComposedMessage("1.must.have.8.bits.per.component", errorID));
}
scaledHeight = getShort(is);
setTop(scaledHeight);
scaledWidth = getShort(is);
setRight(scaledWidth);
colorspace = is.read();
bpc = 8;
break;
}
else if (markertype == UNSUPPORTED_MARKER) {
throw new BadElementException(MessageLocalization.getComposedMessage("1.unsupported.jpeg.marker.2", errorID, String.valueOf(marker)));
}
else if (markertype != NOPARAM_MARKER) {
Utilities.skip(is, getShort(is) - 2);
}
}
}
}
finally {
if (is != null) {
is.close();
}
}
plainWidth = getWidth();
plainHeight = getHeight();
if (icc != null) {
int total = 0;
for (int k = 0; k < icc.length; ++k) {
if (icc[k] == null) {
icc = null;
return;
}
total += icc[k].length - 14;
}
byte[] ficc = new byte[total];
total = 0;
for (int k = 0; k < icc.length; ++k) {
System.arraycopy(icc[k], 14, ficc, total, icc[k].length - 14);
total += icc[k].length - 14;
}
try {
ICC_Profile icc_prof = ICC_Profile.getInstance(ficc, colorspace);
tagICC(icc_prof);
}
catch(IllegalArgumentException e) {
// ignore ICC profile if it's invalid.
}
icc = null;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/error_messages/MessageLocalization.java
public static boolean setLanguage(String language, String country) throws IOException {
HashMap<String, String> lang = getLanguageMessages(language, country);
if (lang == null)
return false;
currentLanguage = lang;
return true;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/error_messages/MessageLocalization.java
public static void setMessages(Reader r) throws IOException {
currentLanguage = readLanguageStream(r);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/error_messages/MessageLocalization.java
private static HashMap<String, String> getLanguageMessages(String language, String country) throws IOException {
if (language == null)
throw new IllegalArgumentException("The language cannot be null.");
InputStream is = null;
try {
String file;
if (country != null)
file = language + "_" + country + ".lng";
else
file = language + ".lng";
is = BaseFont.getResourceStream(BASE_PATH + file, new MessageLocalization().getClass().getClassLoader());
if (is != null)
return readLanguageStream(is);
if (country == null)
return null;
file = language + ".lng";
is = BaseFont.getResourceStream(BASE_PATH + file, new MessageLocalization().getClass().getClassLoader());
if (is != null)
return readLanguageStream(is);
else
return null;
}
finally {
try {
if (null != is){
is.close();
}
} catch (Exception exx) {
}
// do nothing
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/error_messages/MessageLocalization.java
private static HashMap<String, String> readLanguageStream(InputStream is) throws IOException {
return readLanguageStream(new InputStreamReader(is, "UTF-8"));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/error_messages/MessageLocalization.java
private static HashMap<String, String> readLanguageStream(Reader r) throws IOException {
HashMap<String, String> lang = new HashMap<String, String>();
BufferedReader br = new BufferedReader(r);
String line;
while ((line = br.readLine()) != null) {
int idxeq = line.indexOf('=');
if (idxeq < 0)
continue;
String key = line.substring(0, idxeq).trim();
if (key.startsWith("#"))
continue;
lang.put(key, line.substring(idxeq + 1));
}
return lang;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ImgWMF.java
private void processParameters() throws BadElementException, IOException {
type = IMGTEMPLATE;
originalType = ORIGINAL_WMF;
InputStream is = null;
try {
String errorID;
if (rawData == null){
is = url.openStream();
errorID = url.toString();
}
else{
is = new java.io.ByteArrayInputStream(rawData);
errorID = "Byte array";
}
InputMeta in = new InputMeta(is);
if (in.readInt() != 0x9AC6CDD7) {
throw new BadElementException(MessageLocalization.getComposedMessage("1.is.not.a.valid.placeable.windows.metafile", errorID));
}
in.readWord();
int left = in.readShort();
int top = in.readShort();
int right = in.readShort();
int bottom = in.readShort();
int inch = in.readWord();
dpiX = 72;
dpiY = 72;
scaledHeight = (float)(bottom - top) / inch * 72f;
setTop(scaledHeight);
scaledWidth = (float)(right - left) / inch * 72f;
setRight(scaledWidth);
}
finally {
if (is != null) {
is.close();
}
plainWidth = getWidth();
plainHeight = getHeight();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ImgWMF.java
public void readWMF(PdfTemplate template) throws IOException, DocumentException {
setTemplateData(template);
template.setWidth(getWidth());
template.setHeight(getHeight());
InputStream is = null;
try {
if (rawData == null){
is = url.openStream();
}
else{
is = new java.io.ByteArrayInputStream(rawData);
}
MetaDo meta = new MetaDo(is, template);
meta.readAll();
}
finally {
if (is != null) {
is.close();
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TtfUnicodeWriter.java
public void writeFont(TrueTypeFontUnicode font, PdfIndirectReference ref, Object params[], byte[] rotbits) throws DocumentException, IOException {
HashMap<Integer, int[]> longTag = (HashMap<Integer, int[]>)params[0];
font.addRangeUni(longTag, true, font.subset);
int metrics[][] = longTag.values().toArray(new int[0][]);
Arrays.sort(metrics, font);
PdfIndirectReference ind_font = null;
PdfObject pobj = null;
PdfIndirectObject obj = null;
PdfIndirectReference cidset = null;
// sivan: cff
if (font.cff) {
byte b[] = font.readCffFont();
if (font.subset || font.subsetRanges != null) {
CFFFontSubset cff = new CFFFontSubset(new RandomAccessFileOrArray(b),longTag);
b = cff.Process(cff.getNames()[0]);
}
pobj = new BaseFont.StreamFont(b, "CIDFontType0C", font.compressionLevel);
obj = writer.addToBody(pobj);
ind_font = obj.getIndirectReference();
} else {
byte[] b;
if (font.subset || font.directoryOffset != 0) {
b = font.getSubSet(new HashSet<Integer>(longTag.keySet()), true);
}
else {
b = font.getFullFont();
}
int lengths[] = new int[]{b.length};
pobj = new BaseFont.StreamFont(b, lengths, font.compressionLevel);
obj = writer.addToBody(pobj);
ind_font = obj.getIndirectReference();
}
String subsetPrefix = "";
if (font.subset)
subsetPrefix = font.createSubsetPrefix();
PdfDictionary dic = font.getFontDescriptor(ind_font, subsetPrefix, cidset);
obj = writer.addToBody(dic);
ind_font = obj.getIndirectReference();
pobj = font.getCIDFontType2(ind_font, subsetPrefix, metrics);
obj = writer.addToBody(pobj);
ind_font = obj.getIndirectReference();
pobj = font.getToUnicode(metrics);
PdfIndirectReference toUnicodeRef = null;
if (pobj != null) {
obj = writer.addToBody(pobj);
toUnicodeRef = obj.getIndirectReference();
}
pobj = font.getFontBaseType(ind_font, subsetPrefix, toUnicodeRef);
writer.addToBody(pobj, ref);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
public static Image getImage(URL url) throws IOException {
InputStream is = null;
try {
is = url.openStream();
Image img = getImage(is);
img.setUrl(url);
return img;
}
finally {
if (is != null) {
is.close();
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
public static Image getImage(InputStream is) throws IOException {
return getImage(is, false, 0);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
public static Image getImage(InputStream is, boolean noHeader, int size) throws IOException {
BmpImage bmp = new BmpImage(is, noHeader, size);
try {
Image img = bmp.getImage();
img.setDpi((int)(bmp.xPelsPerMeter * 0.0254d + 0.5d), (int)(bmp.yPelsPerMeter * 0.0254d + 0.5d));
img.setOriginalType(Image.ORIGINAL_BMP);
return img;
}
catch (BadElementException be) {
throw new ExceptionConverter(be);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
public static Image getImage(String file) throws IOException {
return getImage(Utilities.toURL(file));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
public static Image getImage(byte data[]) throws IOException {
ByteArrayInputStream is = new ByteArrayInputStream(data);
Image img = getImage(is);
img.setOriginalData(data);
return img;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
protected void process(InputStream stream, boolean noHeader) throws IOException {
if (noHeader || stream instanceof BufferedInputStream) {
inputStream = stream;
} else {
inputStream = new BufferedInputStream(stream);
}
if (!noHeader) {
// Start File Header
if (!(readUnsignedByte(inputStream) == 'B' &&
readUnsignedByte(inputStream) == 'M')) {
throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.magic.value.for.bmp.file"));
}
// Read file size
bitmapFileSize = readDWord(inputStream);
// Read the two reserved fields
readWord(inputStream);
readWord(inputStream);
// Offset to the bitmap from the beginning
bitmapOffset = readDWord(inputStream);
// End File Header
}
// Start BitmapCoreHeader
long size = readDWord(inputStream);
if (size == 12) {
width = readWord(inputStream);
height = readWord(inputStream);
} else {
width = readLong(inputStream);
height = readLong(inputStream);
}
int planes = readWord(inputStream);
bitsPerPixel = readWord(inputStream);
properties.put("color_planes", Integer.valueOf(planes));
properties.put("bits_per_pixel", Integer.valueOf(bitsPerPixel));
// As BMP always has 3 rgb bands, except for Version 5,
// which is bgra
numBands = 3;
if (bitmapOffset == 0)
bitmapOffset = size;
if (size == 12) {
// Windows 2.x and OS/2 1.x
properties.put("bmp_version", "BMP v. 2.x");
// Classify the image type
if (bitsPerPixel == 1) {
imageType = VERSION_2_1_BIT;
} else if (bitsPerPixel == 4) {
imageType = VERSION_2_4_BIT;
} else if (bitsPerPixel == 8) {
imageType = VERSION_2_8_BIT;
} else if (bitsPerPixel == 24) {
imageType = VERSION_2_24_BIT;
}
// Read in the palette
int numberOfEntries = (int)((bitmapOffset-14-size) / 3);
int sizeOfPalette = numberOfEntries*3;
if (bitmapOffset == size) {
switch (imageType) {
case VERSION_2_1_BIT:
sizeOfPalette = 2 * 3;
break;
case VERSION_2_4_BIT:
sizeOfPalette = 16 * 3;
break;
case VERSION_2_8_BIT:
sizeOfPalette = 256 * 3;
break;
case VERSION_2_24_BIT:
sizeOfPalette = 0;
break;
}
bitmapOffset = size + sizeOfPalette;
}
readPalette(sizeOfPalette);
} else {
compression = readDWord(inputStream);
imageSize = readDWord(inputStream);
xPelsPerMeter = readLong(inputStream);
yPelsPerMeter = readLong(inputStream);
long colorsUsed = readDWord(inputStream);
long colorsImportant = readDWord(inputStream);
switch((int)compression) {
case BI_RGB:
properties.put("compression", "BI_RGB");
break;
case BI_RLE8:
properties.put("compression", "BI_RLE8");
break;
case BI_RLE4:
properties.put("compression", "BI_RLE4");
break;
case BI_BITFIELDS:
properties.put("compression", "BI_BITFIELDS");
break;
}
properties.put("x_pixels_per_meter", Long.valueOf(xPelsPerMeter));
properties.put("y_pixels_per_meter", Long.valueOf(yPelsPerMeter));
properties.put("colors_used", Long.valueOf(colorsUsed));
properties.put("colors_important", Long.valueOf(colorsImportant));
if (size == 40 || size == 52 || size == 56) {
// Windows 3.x and Windows NT
switch((int)compression) {
case BI_RGB: // No compression
case BI_RLE8: // 8-bit RLE compression
case BI_RLE4: // 4-bit RLE compression
if (bitsPerPixel == 1) {
imageType = VERSION_3_1_BIT;
} else if (bitsPerPixel == 4) {
imageType = VERSION_3_4_BIT;
} else if (bitsPerPixel == 8) {
imageType = VERSION_3_8_BIT;
} else if (bitsPerPixel == 24) {
imageType = VERSION_3_24_BIT;
} else if (bitsPerPixel == 16) {
imageType = VERSION_3_NT_16_BIT;
redMask = 0x7C00;
greenMask = 0x3E0;
blueMask = 0x1F;
properties.put("red_mask", Integer.valueOf(redMask));
properties.put("green_mask", Integer.valueOf(greenMask));
properties.put("blue_mask", Integer.valueOf(blueMask));
} else if (bitsPerPixel == 32) {
imageType = VERSION_3_NT_32_BIT;
redMask = 0x00FF0000;
greenMask = 0x0000FF00;
blueMask = 0x000000FF;
properties.put("red_mask", Integer.valueOf(redMask));
properties.put("green_mask", Integer.valueOf(greenMask));
properties.put("blue_mask", Integer.valueOf(blueMask));
}
// 52 and 56 byte header have mandatory R, G and B masks
if (size >= 52) {
redMask = (int)readDWord(inputStream);
greenMask = (int)readDWord(inputStream);
blueMask = (int)readDWord(inputStream);
properties.put("red_mask", Integer.valueOf(redMask));
properties.put("green_mask", Integer.valueOf(greenMask));
properties.put("blue_mask", Integer.valueOf(blueMask));
}
// 56 byte header has mandatory alpha mask
if (size == 56) {
alphaMask = (int)readDWord(inputStream);
properties.put("alpha_mask", Integer.valueOf(alphaMask));
}
// Read in the palette
int numberOfEntries = (int)((bitmapOffset-14-size) / 4);
int sizeOfPalette = numberOfEntries*4;
if (bitmapOffset == size) {
switch (imageType) {
case VERSION_3_1_BIT:
sizeOfPalette = (int)(colorsUsed == 0 ? 2 : colorsUsed) * 4;
break;
case VERSION_3_4_BIT:
sizeOfPalette = (int)(colorsUsed == 0 ? 16 : colorsUsed) * 4;
break;
case VERSION_3_8_BIT:
sizeOfPalette = (int)(colorsUsed == 0 ? 256 : colorsUsed) * 4;
break;
default:
sizeOfPalette = 0;
break;
}
bitmapOffset = size + sizeOfPalette;
}
readPalette(sizeOfPalette);
properties.put("bmp_version", "BMP v. 3.x");
break;
case BI_BITFIELDS:
if (bitsPerPixel == 16) {
imageType = VERSION_3_NT_16_BIT;
} else if (bitsPerPixel == 32) {
imageType = VERSION_3_NT_32_BIT;
}
// BitsField encoding
redMask = (int)readDWord(inputStream);
greenMask = (int)readDWord(inputStream);
blueMask = (int)readDWord(inputStream);
// 56 byte header has mandatory alpha mask
if (size == 56) {
alphaMask = (int)readDWord(inputStream);
properties.put("alpha_mask", Integer.valueOf(alphaMask));
}
properties.put("red_mask", Integer.valueOf(redMask));
properties.put("green_mask", Integer.valueOf(greenMask));
properties.put("blue_mask", Integer.valueOf(blueMask));
if (colorsUsed != 0) {
// there is a palette
sizeOfPalette = (int)colorsUsed*4;
readPalette(sizeOfPalette);
}
properties.put("bmp_version", "BMP v. 3.x NT");
break;
default:
throw new
RuntimeException("Invalid compression specified in BMP file.");
}
} else if (size == 108) {
// Windows 4.x BMP
properties.put("bmp_version", "BMP v. 4.x");
// rgb masks, valid only if comp is BI_BITFIELDS
redMask = (int)readDWord(inputStream);
greenMask = (int)readDWord(inputStream);
blueMask = (int)readDWord(inputStream);
// Only supported for 32bpp BI_RGB argb
alphaMask = (int)readDWord(inputStream);
long csType = readDWord(inputStream);
int redX = readLong(inputStream);
int redY = readLong(inputStream);
int redZ = readLong(inputStream);
int greenX = readLong(inputStream);
int greenY = readLong(inputStream);
int greenZ = readLong(inputStream);
int blueX = readLong(inputStream);
int blueY = readLong(inputStream);
int blueZ = readLong(inputStream);
long gammaRed = readDWord(inputStream);
long gammaGreen = readDWord(inputStream);
long gammaBlue = readDWord(inputStream);
if (bitsPerPixel == 1) {
imageType = VERSION_4_1_BIT;
} else if (bitsPerPixel == 4) {
imageType = VERSION_4_4_BIT;
} else if (bitsPerPixel == 8) {
imageType = VERSION_4_8_BIT;
} else if (bitsPerPixel == 16) {
imageType = VERSION_4_16_BIT;
if ((int)compression == BI_RGB) {
redMask = 0x7C00;
greenMask = 0x3E0;
blueMask = 0x1F;
}
} else if (bitsPerPixel == 24) {
imageType = VERSION_4_24_BIT;
} else if (bitsPerPixel == 32) {
imageType = VERSION_4_32_BIT;
if ((int)compression == BI_RGB) {
redMask = 0x00FF0000;
greenMask = 0x0000FF00;
blueMask = 0x000000FF;
}
}
properties.put("red_mask", Integer.valueOf(redMask));
properties.put("green_mask", Integer.valueOf(greenMask));
properties.put("blue_mask", Integer.valueOf(blueMask));
properties.put("alpha_mask", Integer.valueOf(alphaMask));
// Read in the palette
int numberOfEntries = (int)((bitmapOffset-14-size) / 4);
int sizeOfPalette = numberOfEntries*4;
if (bitmapOffset == size) {
switch (imageType) {
case VERSION_4_1_BIT:
sizeOfPalette = (int)(colorsUsed == 0 ? 2 : colorsUsed) * 4;
break;
case VERSION_4_4_BIT:
sizeOfPalette = (int)(colorsUsed == 0 ? 16 : colorsUsed) * 4;
break;
case VERSION_4_8_BIT:
sizeOfPalette = (int)(colorsUsed == 0 ? 256 : colorsUsed) * 4;
break;
default:
sizeOfPalette = 0;
break;
}
bitmapOffset = size + sizeOfPalette;
}
readPalette(sizeOfPalette);
switch((int)csType) {
case LCS_CALIBRATED_RGB:
// All the new fields are valid only for this case
properties.put("color_space", "LCS_CALIBRATED_RGB");
properties.put("redX", Integer.valueOf(redX));
properties.put("redY", Integer.valueOf(redY));
properties.put("redZ", Integer.valueOf(redZ));
properties.put("greenX", Integer.valueOf(greenX));
properties.put("greenY", Integer.valueOf(greenY));
properties.put("greenZ", Integer.valueOf(greenZ));
properties.put("blueX", Integer.valueOf(blueX));
properties.put("blueY", Integer.valueOf(blueY));
properties.put("blueZ", Integer.valueOf(blueZ));
properties.put("gamma_red", Long.valueOf(gammaRed));
properties.put("gamma_green", Long.valueOf(gammaGreen));
properties.put("gamma_blue", Long.valueOf(gammaBlue));
// break;
throw new
RuntimeException("Not implemented yet.");
case LCS_sRGB:
// Default Windows color space
properties.put("color_space", "LCS_sRGB");
break;
case LCS_CMYK:
properties.put("color_space", "LCS_CMYK");
// break;
throw new
RuntimeException("Not implemented yet.");
}
} else {
properties.put("bmp_version", "BMP v. 5.x");
throw new
RuntimeException("BMP version 5 not implemented yet.");
}
}
if (height > 0) {
// bottom up image
isBottomUp = true;
} else {
// top down image
isBottomUp = false;
height = Math.abs(height);
}
// When number of bitsPerPixel is <= 8, we use IndexColorModel.
if (bitsPerPixel == 1 || bitsPerPixel == 4 || bitsPerPixel == 8) {
numBands = 1;
// Create IndexColorModel from the palette.
byte r[], g[], b[];
int sizep;
if (imageType == VERSION_2_1_BIT ||
imageType == VERSION_2_4_BIT ||
imageType == VERSION_2_8_BIT) {
sizep = palette.length/3;
if (sizep > 256) {
sizep = 256;
}
int off;
r = new byte[sizep];
g = new byte[sizep];
b = new byte[sizep];
for (int i=0; i<sizep; i++) {
off = 3 * i;
b[i] = palette[off];
g[i] = palette[off+1];
r[i] = palette[off+2];
}
} else {
sizep = palette.length/4;
if (sizep > 256) {
sizep = 256;
}
int off;
r = new byte[sizep];
g = new byte[sizep];
b = new byte[sizep];
for (int i=0; i<sizep; i++) {
off = 4 * i;
b[i] = palette[off];
g[i] = palette[off+1];
r[i] = palette[off+2];
}
}
} else if (bitsPerPixel == 16) {
numBands = 3;
} else if (bitsPerPixel == 32) {
numBands = alphaMask == 0 ? 3 : 4;
// The number of bands in the SampleModel is determined by
// the length of the mask array passed in.
} else {
numBands = 3;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private Image getImage() throws IOException, BadElementException {
byte bdata[] = null; // buffer for byte data
// if (sampleModel.getDataType() == DataBuffer.TYPE_BYTE)
// bdata = (byte[])((DataBufferByte)tile.getDataBuffer()).getData();
// else if (sampleModel.getDataType() == DataBuffer.TYPE_USHORT)
// sdata = (short[])((DataBufferUShort)tile.getDataBuffer()).getData();
// else if (sampleModel.getDataType() == DataBuffer.TYPE_INT)
// idata = (int[])((DataBufferInt)tile.getDataBuffer()).getData();
// There should only be one tile.
switch(imageType) {
case VERSION_2_1_BIT:
// no compression
return read1Bit(3);
case VERSION_2_4_BIT:
// no compression
return read4Bit(3);
case VERSION_2_8_BIT:
// no compression
return read8Bit(3);
case VERSION_2_24_BIT:
// no compression
bdata = new byte[width * height * 3];
read24Bit(bdata);
return new ImgRaw(width, height, 3, 8, bdata);
case VERSION_3_1_BIT:
// 1-bit images cannot be compressed.
return read1Bit(4);
case VERSION_3_4_BIT:
switch((int)compression) {
case BI_RGB:
return read4Bit(4);
case BI_RLE4:
return readRLE4();
default:
throw new
RuntimeException("Invalid compression specified for BMP file.");
}
case VERSION_3_8_BIT:
switch((int)compression) {
case BI_RGB:
return read8Bit(4);
case BI_RLE8:
return readRLE8();
default:
throw new
RuntimeException("Invalid compression specified for BMP file.");
}
case VERSION_3_24_BIT:
// 24-bit images are not compressed
bdata = new byte[width * height * 3];
read24Bit(bdata);
return new ImgRaw(width, height, 3, 8, bdata);
case VERSION_3_NT_16_BIT:
return read1632Bit(false);
case VERSION_3_NT_32_BIT:
return read1632Bit(true);
case VERSION_4_1_BIT:
return read1Bit(4);
case VERSION_4_4_BIT:
switch((int)compression) {
case BI_RGB:
return read4Bit(4);
case BI_RLE4:
return readRLE4();
default:
throw new
RuntimeException("Invalid compression specified for BMP file.");
}
case VERSION_4_8_BIT:
switch((int)compression) {
case BI_RGB:
return read8Bit(4);
case BI_RLE8:
return readRLE8();
default:
throw new
RuntimeException("Invalid compression specified for BMP file.");
}
case VERSION_4_16_BIT:
return read1632Bit(false);
case VERSION_4_24_BIT:
bdata = new byte[width * height * 3];
read24Bit(bdata);
return new ImgRaw(width, height, 3, 8, bdata);
case VERSION_4_32_BIT:
return read1632Bit(true);
}
return null;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private void readPalette(int sizeOfPalette) throws IOException {
if (sizeOfPalette == 0) {
return;
}
palette = new byte[sizeOfPalette];
int bytesRead = 0;
while (bytesRead < sizeOfPalette) {
int r = inputStream.read(palette, bytesRead, sizeOfPalette - bytesRead);
if (r < 0) {
throw new RuntimeException(MessageLocalization.getComposedMessage("incomplete.palette"));
}
bytesRead += r;
}
properties.put("palette", palette);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private Image read1Bit(int paletteEntries) throws IOException, BadElementException {
byte bdata[] = new byte[(width + 7) / 8 * height];
int padding = 0;
int bytesPerScanline = (int)Math.ceil(width/8.0d);
int remainder = bytesPerScanline % 4;
if (remainder != 0) {
padding = 4 - remainder;
}
int imSize = (bytesPerScanline + padding) * height;
// Read till we have the whole image
byte values[] = new byte[imSize];
int bytesRead = 0;
while (bytesRead < imSize) {
bytesRead += inputStream.read(values, bytesRead,
imSize - bytesRead);
}
if (isBottomUp) {
// Convert the bottom up image to a top down format by copying
// one scanline from the bottom to the top at a time.
for (int i=0; i<height; i++) {
System.arraycopy(values,
imSize - (i+1)*(bytesPerScanline + padding),
bdata,
i*bytesPerScanline, bytesPerScanline);
}
} else {
for (int i=0; i<height; i++) {
System.arraycopy(values,
i * (bytesPerScanline + padding),
bdata,
i * bytesPerScanline,
bytesPerScanline);
}
}
return indexedModel(bdata, 1, paletteEntries);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private Image read4Bit(int paletteEntries) throws IOException, BadElementException {
byte bdata[] = new byte[(width + 1) / 2 * height];
// Padding bytes at the end of each scanline
int padding = 0;
int bytesPerScanline = (int)Math.ceil(width/2.0d);
int remainder = bytesPerScanline % 4;
if (remainder != 0) {
padding = 4 - remainder;
}
int imSize = (bytesPerScanline + padding) * height;
// Read till we have the whole image
byte values[] = new byte[imSize];
int bytesRead = 0;
while (bytesRead < imSize) {
bytesRead += inputStream.read(values, bytesRead,
imSize - bytesRead);
}
if (isBottomUp) {
// Convert the bottom up image to a top down format by copying
// one scanline from the bottom to the top at a time.
for (int i=0; i<height; i++) {
System.arraycopy(values,
imSize - (i+1)*(bytesPerScanline + padding),
bdata,
i*bytesPerScanline,
bytesPerScanline);
}
} else {
for (int i=0; i<height; i++) {
System.arraycopy(values,
i * (bytesPerScanline + padding),
bdata,
i * bytesPerScanline,
bytesPerScanline);
}
}
return indexedModel(bdata, 4, paletteEntries);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private Image read8Bit(int paletteEntries) throws IOException, BadElementException {
byte bdata[] = new byte[width * height];
// Padding bytes at the end of each scanline
int padding = 0;
// width * bitsPerPixel should be divisible by 32
int bitsPerScanline = width * 8;
if ( bitsPerScanline%32 != 0) {
padding = (bitsPerScanline/32 + 1)*32 - bitsPerScanline;
padding = (int)Math.ceil(padding/8.0);
}
int imSize = (width + padding) * height;
// Read till we have the whole image
byte values[] = new byte[imSize];
int bytesRead = 0;
while (bytesRead < imSize) {
bytesRead += inputStream.read(values, bytesRead, imSize - bytesRead);
}
if (isBottomUp) {
// Convert the bottom up image to a top down format by copying
// one scanline from the bottom to the top at a time.
for (int i=0; i<height; i++) {
System.arraycopy(values,
imSize - (i+1) * (width + padding),
bdata,
i * width,
width);
}
} else {
for (int i=0; i<height; i++) {
System.arraycopy(values,
i * (width + padding),
bdata,
i * width,
width);
}
}
return indexedModel(bdata, 8, paletteEntries);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private Image read1632Bit(boolean is32) throws IOException, BadElementException {
int red_mask = findMask(redMask);
int red_shift = findShift(redMask);
int red_factor = red_mask + 1;
int green_mask = findMask(greenMask);
int green_shift = findShift(greenMask);
int green_factor = green_mask + 1;
int blue_mask = findMask(blueMask);
int blue_shift = findShift(blueMask);
int blue_factor = blue_mask + 1;
byte bdata[] = new byte[width * height * 3];
// Padding bytes at the end of each scanline
int padding = 0;
if (!is32) {
// width * bitsPerPixel should be divisible by 32
int bitsPerScanline = width * 16;
if ( bitsPerScanline%32 != 0) {
padding = (bitsPerScanline/32 + 1)*32 - bitsPerScanline;
padding = (int)Math.ceil(padding/8.0);
}
}
int imSize = (int)imageSize;
if (imSize == 0) {
imSize = (int)(bitmapFileSize - bitmapOffset);
}
int l=0;
int v;
if (isBottomUp) {
for (int i=height - 1; i >= 0; --i) {
l = width * 3 * i;
for (int j=0; j<width; j++) {
if (is32)
v = (int)readDWord(inputStream);
else
v = readWord(inputStream);
bdata[l++] = (byte)((v >>> red_shift & red_mask) * 256 / red_factor);
bdata[l++] = (byte)((v >>> green_shift & green_mask) * 256 / green_factor);
bdata[l++] = (byte)((v >>> blue_shift & blue_mask) * 256 / blue_factor);
}
for (int m=0; m<padding; m++) {
inputStream.read();
}
}
} else {
for (int i=0; i<height; i++) {
for (int j=0; j<width; j++) {
if (is32)
v = (int)readDWord(inputStream);
else
v = readWord(inputStream);
bdata[l++] = (byte)((v >>> red_shift & red_mask) * 256 / red_factor);
bdata[l++] = (byte)((v >>> green_shift & green_mask) * 256 / green_factor);
bdata[l++] = (byte)((v >>> blue_shift & blue_mask) * 256 / blue_factor);
}
for (int m=0; m<padding; m++) {
inputStream.read();
}
}
}
return new ImgRaw(width, height, 3, 8, bdata);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private Image readRLE8() throws IOException, BadElementException {
// If imageSize field is not provided, calculate it.
int imSize = (int)imageSize;
if (imSize == 0) {
imSize = (int)(bitmapFileSize - bitmapOffset);
}
// Read till we have the whole image
byte values[] = new byte[imSize];
int bytesRead = 0;
while (bytesRead < imSize) {
bytesRead += inputStream.read(values, bytesRead,
imSize - bytesRead);
}
// Since data is compressed, decompress it
byte val[] = decodeRLE(true, values);
// Uncompressed data does not have any padding
imSize = width * height;
if (isBottomUp) {
// Convert the bottom up image to a top down format by copying
// one scanline from the bottom to the top at a time.
// int bytesPerScanline = (int)Math.ceil((double)width/8.0);
byte temp[] = new byte[val.length];
int bytesPerScanline = width;
for (int i=0; i<height; i++) {
System.arraycopy(val,
imSize - (i+1)*bytesPerScanline,
temp,
i*bytesPerScanline, bytesPerScanline);
}
val = temp;
}
return indexedModel(val, 8, 4);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private Image readRLE4() throws IOException, BadElementException {
// If imageSize field is not specified, calculate it.
int imSize = (int)imageSize;
if (imSize == 0) {
imSize = (int)(bitmapFileSize - bitmapOffset);
}
// Read till we have the whole image
byte values[] = new byte[imSize];
int bytesRead = 0;
while (bytesRead < imSize) {
bytesRead += inputStream.read(values, bytesRead,
imSize - bytesRead);
}
// Decompress the RLE4 compressed data.
byte val[] = decodeRLE(false, values);
// Invert it as it is bottom up format.
if (isBottomUp) {
byte inverted[] = val;
val = new byte[width * height];
int l = 0, index, lineEnd;
for (int i = height-1; i >= 0; i--) {
index = i * width;
lineEnd = l + width;
while(l != lineEnd) {
val[l++] = inverted[index++];
}
}
}
int stride = (width + 1) / 2;
byte bdata[] = new byte[stride * height];
int ptr = 0;
int sh = 0;
for (int h = 0; h < height; ++h) {
for (int w = 0; w < width; ++w) {
if ((w & 1) == 0)
bdata[sh + w / 2] = (byte)(val[ptr++] << 4);
else
bdata[sh + w / 2] |= (byte)(val[ptr++] & 0x0f);
}
sh += stride;
}
return indexedModel(bdata, 4, 4);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private int readUnsignedByte(InputStream stream) throws IOException {
return stream.read() & 0xff;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private int readUnsignedShort(InputStream stream) throws IOException {
int b1 = readUnsignedByte(stream);
int b2 = readUnsignedByte(stream);
return (b2 << 8 | b1) & 0xffff;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private int readShort(InputStream stream) throws IOException {
int b1 = readUnsignedByte(stream);
int b2 = readUnsignedByte(stream);
return b2 << 8 | b1;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private int readWord(InputStream stream) throws IOException {
return readUnsignedShort(stream);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private long readUnsignedInt(InputStream stream) throws IOException {
int b1 = readUnsignedByte(stream);
int b2 = readUnsignedByte(stream);
int b3 = readUnsignedByte(stream);
int b4 = readUnsignedByte(stream);
long l = b4 << 24 | b3 << 16 | b2 << 8 | b1;
return l & 0xffffffff;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private int readInt(InputStream stream) throws IOException {
int b1 = readUnsignedByte(stream);
int b2 = readUnsignedByte(stream);
int b3 = readUnsignedByte(stream);
int b4 = readUnsignedByte(stream);
return b4 << 24 | b3 << 16 | b2 << 8 | b1;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private long readDWord(InputStream stream) throws IOException {
return readUnsignedInt(stream);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
private int readLong(InputStream stream) throws IOException {
return readInt(stream);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2SegmentReader.java
public byte[] getData(boolean for_embedding) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
for (Integer sn : segs.keySet()) {
JBIG2Segment s = segs.get(sn);
// pdf reference 1.4, section 3.3.6 JBIG2Decode Filter
// D.3 Embedded organisation
if ( for_embedding &&
( s.type == END_OF_FILE || s.type == END_OF_PAGE ) ) {
continue;
}
if ( for_embedding ) {
// change the page association to page 1
byte[] headerData_emb = copyByteArray(s.headerData);
if ( s.page_association_size ) {
headerData_emb[s.page_association_offset] = 0x0;
headerData_emb[s.page_association_offset+1] = 0x0;
headerData_emb[s.page_association_offset+2] = 0x0;
headerData_emb[s.page_association_offset+3] = 0x1;
} else {
headerData_emb[s.page_association_offset] = 0x1;
}
os.write(headerData_emb);
} else {
os.write(s.headerData);
}
os.write(s.data);
}
os.close();
return os.toByteArray();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2SegmentReader.java
public void read() throws IOException {
if ( this.read ) {
throw new IllegalStateException(MessageLocalization.getComposedMessage("already.attempted.a.read.on.this.jbig2.file"));
}
this.read = true;
readFileHeader();
// Annex D
if ( this.sequential ) {
// D.1
do {
JBIG2Segment tmp = readHeader();
readSegment(tmp);
segments.put(Integer.valueOf(tmp.segmentNumber), tmp);
} while ( this.ra.getFilePointer() < this.ra.length() );
} else {
// D.2
JBIG2Segment tmp;
do {
tmp = readHeader();
segments.put(Integer.valueOf(tmp.segmentNumber), tmp);
} while ( tmp.type != END_OF_FILE );
Iterator<Integer> segs = segments.keySet().iterator();
while ( segs.hasNext() ) {
readSegment(segments.get(segs.next()));
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2SegmentReader.java
void readSegment(JBIG2Segment s) throws IOException {
int ptr = (int)ra.getFilePointer();
if ( s.dataLength == 0xffffffffl ) {
// TODO figure this bit out, 7.2.7
return;
}
byte[] data = new byte[(int)s.dataLength];
ra.read(data);
s.data = data;
if ( s.type == PAGE_INFORMATION ) {
int last = (int)ra.getFilePointer();
ra.seek(ptr);
int page_bitmap_width = ra.readInt();
int page_bitmap_height = ra.readInt();
ra.seek(last);
JBIG2Page p = pages.get(Integer.valueOf(s.page));
if ( p == null ) {
throw new IllegalStateException(MessageLocalization.getComposedMessage("referring.to.widht.height.of.page.we.havent.seen.yet.1", s.page));
}
p.pageBitmapWidth = page_bitmap_width;
p.pageBitmapHeight = page_bitmap_height;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2SegmentReader.java
JBIG2Segment readHeader() throws IOException {
int ptr = (int)ra.getFilePointer();
// 7.2.1
int segment_number = ra.readInt();
JBIG2Segment s = new JBIG2Segment(segment_number);
// 7.2.3
int segment_header_flags = ra.read();
boolean deferred_non_retain = ( segment_header_flags & 0x80 ) == 0x80;
s.deferredNonRetain = deferred_non_retain;
boolean page_association_size = ( segment_header_flags & 0x40 ) == 0x40;
int segment_type = segment_header_flags & 0x3f;
s.type = segment_type;
//7.2.4
int referred_to_byte0 = ra.read();
int count_of_referred_to_segments = (referred_to_byte0 & 0xE0) >> 5;
int[] referred_to_segment_numbers = null;
boolean[] segment_retention_flags = null;
if ( count_of_referred_to_segments == 7 ) {
// at least five bytes
ra.seek(ra.getFilePointer() - 1);
count_of_referred_to_segments = ra.readInt() & 0x1fffffff;
segment_retention_flags = new boolean[count_of_referred_to_segments+1];
int i = 0;
int referred_to_current_byte = 0;
do {
int j = i % 8;
if ( j == 0) {
referred_to_current_byte = ra.read();
}
segment_retention_flags[i] = (0x1 << j & referred_to_current_byte) >> j == 0x1;
i++;
} while ( i <= count_of_referred_to_segments );
} else if ( count_of_referred_to_segments <= 4 ) {
// only one byte
segment_retention_flags = new boolean[count_of_referred_to_segments+1];
referred_to_byte0 &= 0x1f;
for ( int i = 0; i <= count_of_referred_to_segments; i++ ) {
segment_retention_flags[i] = (0x1 << i & referred_to_byte0) >> i == 0x1;
}
} else if ( count_of_referred_to_segments == 5 || count_of_referred_to_segments == 6 ) {
throw new IllegalStateException(MessageLocalization.getComposedMessage("count.of.referred.to.segments.had.bad.value.in.header.for.segment.1.starting.at.2", String.valueOf(segment_number), String.valueOf(ptr)));
}
s.segmentRetentionFlags = segment_retention_flags;
s.countOfReferredToSegments = count_of_referred_to_segments;
// 7.2.5
referred_to_segment_numbers = new int[count_of_referred_to_segments+1];
for ( int i = 1; i <= count_of_referred_to_segments; i++ ) {
if ( segment_number <= 256 ) {
referred_to_segment_numbers[i] = ra.read();
} else if ( segment_number <= 65536 ) {
referred_to_segment_numbers[i] = ra.readUnsignedShort();
} else {
referred_to_segment_numbers[i] = (int)ra.readUnsignedInt(); // TODO wtf ack
}
}
s.referredToSegmentNumbers = referred_to_segment_numbers;
// 7.2.6
int segment_page_association;
int page_association_offset = (int)ra.getFilePointer() - ptr;
if ( page_association_size ) {
segment_page_association = ra.readInt();
} else {
segment_page_association = ra.read();
}
if ( segment_page_association < 0 ) {
throw new IllegalStateException(MessageLocalization.getComposedMessage("page.1.invalid.for.segment.2.starting.at.3", String.valueOf(segment_page_association), String.valueOf(segment_number), String.valueOf(ptr)));
}
s.page = segment_page_association;
// so we can change the page association at embedding time.
s.page_association_size = page_association_size;
s.page_association_offset = page_association_offset;
if ( segment_page_association > 0 && ! pages.containsKey(Integer.valueOf(segment_page_association)) ) {
pages.put(Integer.valueOf(segment_page_association), new JBIG2Page(segment_page_association, this));
}
if ( segment_page_association > 0 ) {
pages.get(Integer.valueOf(segment_page_association)).addSegment(s);
} else {
globals.add(s);
}
// 7.2.7
long segment_data_length = ra.readUnsignedInt();
// TODO the 0xffffffff value that might be here, and how to understand those afflicted segments
s.dataLength = segment_data_length;
int end_ptr = (int)ra.getFilePointer();
ra.seek(ptr);
byte[] header_data = new byte[end_ptr - ptr];
ra.read(header_data);
s.headerData = header_data;
return s;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2SegmentReader.java
void readFileHeader() throws IOException {
ra.seek(0);
byte[] idstring = new byte[8];
ra.read(idstring);
byte[] refidstring = {(byte)0x97, 0x4A, 0x42, 0x32, 0x0D, 0x0A, 0x1A, 0x0A};
for ( int i = 0; i < idstring.length; i++ ) {
if ( idstring[i] != refidstring[i] ) {
throw new IllegalStateException(MessageLocalization.getComposedMessage("file.header.idstring.not.good.at.byte.1", i));
}
}
int fileheaderflags = ra.read();
this.sequential = ( fileheaderflags & 0x1 ) == 0x1;
this.number_of_pages_known = ( fileheaderflags & 0x2) == 0x0;
if ( (fileheaderflags & 0xfc) != 0x0 ) {
throw new IllegalStateException(MessageLocalization.getComposedMessage("file.header.flags.bits.2.7.not.0"));
}
if ( this.number_of_pages_known ) {
this.number_of_pages = ra.readInt();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
void process(InputStream is) throws IOException {
in = new DataInputStream(new BufferedInputStream(is));
readHeader();
readContents();
if (frames.isEmpty())
throw new IOException(MessageLocalization.getComposedMessage("the.file.does.not.contain.any.valid.image"));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
protected void readHeader() throws IOException {
StringBuilder id = new StringBuilder("");
for (int i = 0; i < 6; i++)
id.append((char)in.read());
if (!id.toString().startsWith("GIF8")) {
throw new IOException(MessageLocalization.getComposedMessage("gif.signature.nor.found"));
}
readLSD();
if (gctFlag) {
m_global_table = readColorTable(m_gbpc);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
protected void readLSD() throws IOException {
// logical screen size
width = readShort();
height = readShort();
// packed fields
int packed = in.read();
gctFlag = (packed & 0x80) != 0; // 1 : global color table flag
m_gbpc = (packed & 7) + 1;
bgIndex = in.read(); // background color index
pixelAspect = in.read(); // pixel aspect ratio
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
protected int readShort() throws IOException {
// read 16-bit value, LSB first
return in.read() | in.read() << 8;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
protected int readBlock() throws IOException {
blockSize = in.read();
if (blockSize <= 0)
return blockSize = 0;
blockSize = in.read(block, 0, blockSize);
return blockSize;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
protected byte[] readColorTable(int bpc) throws IOException {
int ncolors = 1 << bpc;
int nbytes = 3*ncolors;
bpc = newBpc(bpc);
byte table[] = new byte[(1 << bpc) * 3];
in.readFully(table, 0, nbytes);
return table;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
protected void readContents() throws IOException {
// read GIF file content blocks
boolean done = false;
while (!done) {
int code = in.read();
switch (code) {
case 0x2C: // image separator
readImage();
break;
case 0x21: // extension
code = in.read();
switch (code) {
case 0xf9: // graphics control extension
readGraphicControlExt();
break;
case 0xff: // application extension
readBlock();
skip(); // don't care
break;
default: // uninteresting extension
skip();
}
break;
default:
done = true;
break;
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
protected void readImage() throws IOException {
ix = readShort(); // (sub)image position & size
iy = readShort();
iw = readShort();
ih = readShort();
int packed = in.read();
lctFlag = (packed & 0x80) != 0; // 1 - local color table flag
interlace = (packed & 0x40) != 0; // 2 - interlace flag
// 3 - sort flag
// 4-5 - reserved
lctSize = 2 << (packed & 7); // 6-8 - local color table size
m_bpc = newBpc(m_gbpc);
if (lctFlag) {
m_curr_table = readColorTable((packed & 7) + 1); // read table
m_bpc = newBpc((packed & 7) + 1);
}
else {
m_curr_table = m_global_table;
}
if (transparency && transIndex >= m_curr_table.length / 3)
transparency = false;
if (transparency && m_bpc == 1) { // Acrobat 5.05 doesn't like this combination
byte tp[] = new byte[12];
System.arraycopy(m_curr_table, 0, tp, 0, 6);
m_curr_table = tp;
m_bpc = 2;
}
boolean skipZero = decodeImageData(); // decode pixel data
if (!skipZero)
skip();
Image img = null;
try {
img = new ImgRaw(iw, ih, 1, m_bpc, m_out);
PdfArray colorspace = new PdfArray();
colorspace.add(PdfName.INDEXED);
colorspace.add(PdfName.DEVICERGB);
int len = m_curr_table.length;
colorspace.add(new PdfNumber(len / 3 - 1));
colorspace.add(new PdfString(m_curr_table));
PdfDictionary ad = new PdfDictionary();
ad.put(PdfName.COLORSPACE, colorspace);
img.setAdditional(ad);
if (transparency) {
img.setTransparency(new int[]{transIndex, transIndex});
}
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
img.setOriginalType(Image.ORIGINAL_GIF);
img.setOriginalData(fromData);
img.setUrl(fromUrl);
GifFrame gf = new GifFrame();
gf.image = img;
gf.ix = ix;
gf.iy = iy;
frames.add(gf); // add image to frame list
//resetFrame();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
protected boolean decodeImageData() throws IOException {
int NullCode = -1;
int npix = iw * ih;
int available, clear, code_mask, code_size, end_of_information, in_code, old_code,
bits, code, count, i, datum, data_size, first, top, bi;
boolean skipZero = false;
if (prefix == null)
prefix = new short[MaxStackSize];
if (suffix == null)
suffix = new byte[MaxStackSize];
if (pixelStack == null)
pixelStack = new byte[MaxStackSize+1];
m_line_stride = (iw * m_bpc + 7) / 8;
m_out = new byte[m_line_stride * ih];
int pass = 1;
int inc = interlace ? 8 : 1;
int line = 0;
int xpos = 0;
// Initialize GIF data stream decoder.
data_size = in.read();
clear = 1 << data_size;
end_of_information = clear + 1;
available = clear + 2;
old_code = NullCode;
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
for (code = 0; code < clear; code++) {
prefix[code] = 0;
suffix[code] = (byte) code;
}
// Decode GIF pixel stream.
datum = bits = count = first = top = bi = 0;
for (i = 0; i < npix; ) {
if (top == 0) {
if (bits < code_size) {
// Load bytes until there are enough bits for a code.
if (count == 0) {
// Read a new data block.
count = readBlock();
if (count <= 0) {
skipZero = true;
break;
}
bi = 0;
}
datum += (block[bi] & 0xff) << bits;
bits += 8;
bi++;
count--;
continue;
}
// Get the next code.
code = datum & code_mask;
datum >>= code_size;
bits -= code_size;
// Interpret the code
if (code > available || code == end_of_information)
break;
if (code == clear) {
// Reset decoder.
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
available = clear + 2;
old_code = NullCode;
continue;
}
if (old_code == NullCode) {
pixelStack[top++] = suffix[code];
old_code = code;
first = code;
continue;
}
in_code = code;
if (code == available) {
pixelStack[top++] = (byte) first;
code = old_code;
}
while (code > clear) {
pixelStack[top++] = suffix[code];
code = prefix[code];
}
first = suffix[code] & 0xff;
// Add a new string to the string table,
if (available >= MaxStackSize)
break;
pixelStack[top++] = (byte) first;
prefix[available] = (short) old_code;
suffix[available] = (byte) first;
available++;
if ((available & code_mask) == 0 && available < MaxStackSize) {
code_size++;
code_mask += available;
}
old_code = in_code;
}
// Pop a pixel off the pixel stack.
top--;
i++;
setPixel(xpos, line, pixelStack[top]);
++xpos;
if (xpos >= iw) {
xpos = 0;
line += inc;
if (line >= ih) {
if (interlace) {
do {
pass++;
switch (pass) {
case 2:
line = 4;
break;
case 3:
line = 2;
inc = 4;
break;
case 4:
line = 1;
inc = 2;
break;
default: // this shouldn't happen
line = ih - 1;
inc = 0;
}
} while (line >= ih);
}
else {
line = ih - 1; // this shouldn't happen
inc = 0;
}
}
}
}
return skipZero;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
protected void readGraphicControlExt() throws IOException {
in.read(); // block size
int packed = in.read(); // packed fields
dispose = (packed & 0x1c) >> 2; // disposal method
if (dispose == 0)
dispose = 1; // elect to keep old image if discretionary
transparency = (packed & 1) != 0;
delay = readShort() * 10; // delay in milliseconds
transIndex = in.read(); // transparent color index
in.read(); // block terminator
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
protected void skip() throws IOException {
do {
readBlock();
} while (blockSize > 0);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
public int read() throws java.io.IOException {
// Do we need to get data?
if( position < 0 ) {
if( encode ) {
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for( int i = 0; i < 3; i++ ) {
try {
int b = in.read();
// If end of stream, b is -1.
if( b >= 0 ) {
b3[i] = (byte)b;
numBinaryBytes++;
} // end if: not end of stream
} // end try: read
catch( java.io.IOException e ) {
// Only a problem if we got no data at all.
if( i == 0 )
throw e;
} // end catch
} // end for: each needed input byte
if( numBinaryBytes > 0 ) {
encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
position = 0;
numSigBytes = 4;
} // end if: got data
else {
return -1;
} // end else
} // end if: encoding
// Else decoding
else {
byte[] b4 = new byte[4];
int i = 0;
for( i = 0; i < 4; i++ ) {
// Read four "meaningful" bytes:
int b = 0;
do{ b = in.read(); }
while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
if( b < 0 )
break; // Reads a -1 if end of stream
b4[i] = (byte)b;
} // end for: each needed input byte
if( i == 4 ) {
numSigBytes = decode4to3( b4, 0, buffer, 0, options );
position = 0;
} // end if: got four characters
else if( i == 0 ){
return -1;
} // end else if: also padded correctly
else {
// Must have broken out from above.
throw new java.io.IOException(MessageLocalization.getComposedMessage("improperly.padded.base64.input"));
} // end
} // end else: decode
} // end else: get data
// Got data?
if( position >= 0 ) {
// End of relevant data?
if( /*!encode &&*/ position >= numSigBytes )
return -1;
if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {
lineLength = 0;
return '\n';
} // end if
else {
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[ position++ ];
if( position >= bufferLength )
position = -1;
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else {
// When JDK1.4 is more accepted, use an assertion here.
throw new java.io.IOException(MessageLocalization.getComposedMessage("error.in.base64.code.reading.stream"));
} // end else
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
public int read( byte[] dest, int off, int len ) throws java.io.IOException {
int i;
int b;
for( i = 0; i < len; i++ ) {
b = read();
//if( b < 0 && i == 0 )
// return -1;
if( b >= 0 )
dest[off + i] = (byte)b;
else if( i == 0 )
return -1;
else
break; // Out of 'for' loop
} // end for: each byte read
return i;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
public void write(int theByte) throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
super.out.write( theByte );
return;
} // end if: supsended
// Encode?
if( encode ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) // Enough to encode.
{
out.write( encode3to4( b4, buffer, bufferLength, options ) );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH ) {
out.write( NEW_LINE );
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else {
// Meaningful Base64 character?
if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) // Enough to output.
{
int len = Base64.decode4to3( buffer, 0, b4, 0, options );
out.write( b4, 0, len );
//out.write( Base64.decode4to3( buffer ) );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) {
throw new java.io.IOException(MessageLocalization.getComposedMessage("invalid.character.in.base64.data"));
} // end else: not white space either
} // end else: decoding
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
public void write( byte[] theBytes, int off, int len ) throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
super.out.write( theBytes, off, len );
return;
} // end if: supsended
for( int i = 0; i < len; i++ ) {
write( theBytes[ off + i ] );
} // end for: each byte written
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
public void flushBase64() throws java.io.IOException {
if( position > 0 ) {
if( encode ) {
out.write( encode3to4( b4, buffer, position, options ) );
position = 0;
} // end if: encoding
else {
throw new java.io.IOException(MessageLocalization.getComposedMessage("base64.input.not.properly.padded"));
} // end else: decoding
} // end if: buffer partially full
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
public void close() throws java.io.IOException {
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
public void suspendEncoding() throws java.io.IOException {
flushBase64();
this.suspendEncoding = true;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/LZWCompressor.java
public void compress(byte[] buf, int offset, int length)
throws IOException
{
int idx;
byte c;
short index;
int maxOffset = offset + length;
for (idx = offset; idx < maxOffset; ++idx)
{
c = buf[idx];
if ((index = lzss_.FindCharString(prefix_, c)) != -1)
prefix_ = index;
else
{
bf_.writeBits(prefix_, numBits_);
if (lzss_.AddCharString(prefix_, c) > limit_)
{
if (numBits_ == 12)
{
bf_.writeBits(clearCode_, numBits_);
lzss_.ClearTable(codeSize_);
numBits_ = codeSize_ + 1;
}
else
++numBits_;
limit_ = (1 << numBits_) - 1;
if (tiffFudge_)
--limit_;
}
prefix_ = (short)((short)c & 0xFF);
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/LZWCompressor.java
public void flush() throws IOException
{
if (prefix_ != -1)
bf_.writeBits(prefix_, numBits_);
bf_.writeBits(endOfInfo_, numBits_);
bf_.flush();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BitFile.java
public void flush() throws IOException
{
int numBytes = index_ + (bitsLeft_ == 8 ? 0 : 1);
if (numBytes > 0)
{
if (blocks_)
output_.write(numBytes);
output_.write(buffer_, 0, numBytes);
buffer_[0] = 0;
index_ = 0;
bitsLeft_ = 8;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BitFile.java
public void writeBits(int bits, int numbits) throws IOException
{
int bitsWritten = 0;
int numBytes = 255; // gif block count
do
{
// This handles the GIF block count stuff
if ((index_ == 254 && bitsLeft_ == 0) || index_ > 254)
{
if (blocks_)
output_.write(numBytes);
output_.write(buffer_, 0, numBytes);
buffer_[0] = 0;
index_ = 0;
bitsLeft_ = 8;
}
if (numbits <= bitsLeft_) // bits contents fit in current index byte
{
if (blocks_) // GIF
{
buffer_[index_] |= (bits & ((1 << numbits) - 1)) << (8 - bitsLeft_);
bitsWritten += numbits;
bitsLeft_ -= numbits;
numbits = 0;
}
else
{
buffer_[index_] |= (bits & ((1 << numbits) - 1)) << (bitsLeft_ - numbits);
bitsWritten += numbits;
bitsLeft_ -= numbits;
numbits = 0;
}
}
else // bits overflow from current byte to next.
{
if (blocks_) // GIF
{
// if bits > space left in current byte then the lowest order bits
// of code are taken and put in current byte and rest put in next.
buffer_[index_] |= (bits & ((1 << bitsLeft_) - 1)) << (8 - bitsLeft_);
bitsWritten += bitsLeft_;
bits >>= bitsLeft_;
numbits -= bitsLeft_;
buffer_[++index_] = 0;
bitsLeft_ = 8;
}
else
{
// if bits > space left in current byte then the highest order bits
// of code are taken and put in current byte and rest put in next.
// at highest order bit location !!
int topbits = (bits >>> (numbits - bitsLeft_)) & ((1 << bitsLeft_) - 1);
buffer_[index_] |= topbits;
numbits -= bitsLeft_; // ok this many bits gone off the top
bitsWritten += bitsLeft_;
buffer_[++index_] = 0; // next index
bitsLeft_ = 8;
}
}
} while (numbits != 0);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
public static Image getImage(URL url) throws IOException {
InputStream is = null;
try {
is = url.openStream();
Image img = getImage(is);
img.setUrl(url);
return img;
}
finally {
if (is != null) {
is.close();
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
public static Image getImage(InputStream is) throws IOException {
PngImage png = new PngImage(is);
return png.getImage();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
public static Image getImage(String file) throws IOException {
return getImage(Utilities.toURL(file));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
public static Image getImage(byte data[]) throws IOException {
ByteArrayInputStream is = new ByteArrayInputStream(data);
Image img = getImage(is);
img.setOriginalData(data);
return img;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
void readPng() throws IOException {
for (int i = 0; i < PNGID.length; i++) {
if (PNGID[i] != is.read()) {
throw new IOException(MessageLocalization.getComposedMessage("file.is.not.a.valid.png"));
}
}
byte buffer[] = new byte[TRANSFERSIZE];
while (true) {
int len = getInt(is);
String marker = getString(is);
if (len < 0 || !checkMarker(marker))
throw new IOException(MessageLocalization.getComposedMessage("corrupted.png.file"));
if (IDAT.equals(marker)) {
int size;
while (len != 0) {
size = is.read(buffer, 0, Math.min(len, TRANSFERSIZE));
if (size < 0)
return;
idat.write(buffer, 0, size);
len -= size;
}
}
else if (tRNS.equals(marker)) {
switch (colorType) {
case 0:
if (len >= 2) {
len -= 2;
int gray = getWord(is);
if (bitDepth == 16)
transRedGray = gray;
else
additional.put(PdfName.MASK, new PdfLiteral("["+gray+" "+gray+"]"));
}
break;
case 2:
if (len >= 6) {
len -= 6;
int red = getWord(is);
int green = getWord(is);
int blue = getWord(is);
if (bitDepth == 16) {
transRedGray = red;
transGreen = green;
transBlue = blue;
}
else
additional.put(PdfName.MASK, new PdfLiteral("["+red+" "+red+" "+green+" "+green+" "+blue+" "+blue+"]"));
}
break;
case 3:
if (len > 0) {
trans = new byte[len];
for (int k = 0; k < len; ++k)
trans[k] = (byte)is.read();
len = 0;
}
break;
}
Utilities.skip(is, len);
}
else if (IHDR.equals(marker)) {
width = getInt(is);
height = getInt(is);
bitDepth = is.read();
colorType = is.read();
compressionMethod = is.read();
filterMethod = is.read();
interlaceMethod = is.read();
}
else if (PLTE.equals(marker)) {
if (colorType == 3) {
PdfArray colorspace = new PdfArray();
colorspace.add(PdfName.INDEXED);
colorspace.add(getColorspace());
colorspace.add(new PdfNumber(len / 3 - 1));
ByteBuffer colortable = new ByteBuffer();
while ((len--) > 0) {
colortable.append_i(is.read());
}
colorspace.add(new PdfString(colorTable = colortable.toByteArray()));
additional.put(PdfName.COLORSPACE, colorspace);
}
else {
Utilities.skip(is, len);
}
}
else if (pHYs.equals(marker)) {
int dx = getInt(is);
int dy = getInt(is);
int unit = is.read();
if (unit == 1) {
dpiX = (int)(dx * 0.0254f + 0.5f);
dpiY = (int)(dy * 0.0254f + 0.5f);
}
else {
if (dy != 0)
XYRatio = (float)dx / (float)dy;
}
}
else if (cHRM.equals(marker)) {
xW = getInt(is) / 100000f;
yW = getInt(is) / 100000f;
xR = getInt(is) / 100000f;
yR = getInt(is) / 100000f;
xG = getInt(is) / 100000f;
yG = getInt(is) / 100000f;
xB = getInt(is) / 100000f;
yB = getInt(is) / 100000f;
hasCHRM = !(Math.abs(xW)<0.0001f||Math.abs(yW)<0.0001f||Math.abs(xR)<0.0001f||Math.abs(yR)<0.0001f||Math.abs(xG)<0.0001f||Math.abs(yG)<0.0001f||Math.abs(xB)<0.0001f||Math.abs(yB)<0.0001f);
}
else if (sRGB.equals(marker)) {
int ri = is.read();
intent = intents[ri];
gamma = 2.2f;
xW = 0.3127f;
yW = 0.329f;
xR = 0.64f;
yR = 0.33f;
xG = 0.3f;
yG = 0.6f;
xB = 0.15f;
yB = 0.06f;
hasCHRM = true;
}
else if (gAMA.equals(marker)) {
int gm = getInt(is);
if (gm != 0) {
gamma = 100000f / gm;
if (!hasCHRM) {
xW = 0.3127f;
yW = 0.329f;
xR = 0.64f;
yR = 0.33f;
xG = 0.3f;
yG = 0.6f;
xB = 0.15f;
yB = 0.06f;
hasCHRM = true;
}
}
}
else if (iCCP.equals(marker)) {
do {
--len;
} while (is.read() != 0);
is.read();
--len;
byte icccom[] = new byte[len];
int p = 0;
while (len > 0) {
int r = is.read(icccom, p, len);
if (r < 0)
throw new IOException(MessageLocalization.getComposedMessage("premature.end.of.file"));
p += r;
len -= r;
}
byte iccp[] = PdfReader.FlateDecode(icccom, true);
icccom = null;
try {
icc_profile = ICC_Profile.getInstance(iccp);
}
catch (RuntimeException e) {
icc_profile = null;
}
}
else if (IEND.equals(marker)) {
break;
}
else {
Utilities.skip(is, len);
}
Utilities.skip(is, 4);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
Image getImage() throws IOException {
readPng();
try {
int pal0 = 0;
int palIdx = 0;
palShades = false;
if (trans != null) {
for (int k = 0; k < trans.length; ++k) {
int n = trans[k] & 0xff;
if (n == 0) {
++pal0;
palIdx = k;
}
if (n != 0 && n != 255) {
palShades = true;
break;
}
}
}
if ((colorType & 4) != 0)
palShades = true;
genBWMask = (!palShades && (pal0 > 1 || transRedGray >= 0));
if (!palShades && !genBWMask && pal0 == 1) {
additional.put(PdfName.MASK, new PdfLiteral("["+palIdx+" "+palIdx+"]"));
}
boolean needDecode = (interlaceMethod == 1) || (bitDepth == 16) || ((colorType & 4) != 0) || palShades || genBWMask;
switch (colorType) {
case 0:
inputBands = 1;
break;
case 2:
inputBands = 3;
break;
case 3:
inputBands = 1;
break;
case 4:
inputBands = 2;
break;
case 6:
inputBands = 4;
break;
}
if (needDecode)
decodeIdat();
int components = inputBands;
if ((colorType & 4) != 0)
--components;
int bpc = bitDepth;
if (bpc == 16)
bpc = 8;
Image img;
if (image != null) {
if (colorType == 3)
img = new ImgRaw(width, height, components, bpc, image);
else
img = Image.getInstance(width, height, components, bpc, image);
}
else {
img = new ImgRaw(width, height, components, bpc, idat.toByteArray());
img.setDeflated(true);
PdfDictionary decodeparms = new PdfDictionary();
decodeparms.put(PdfName.BITSPERCOMPONENT, new PdfNumber(bitDepth));
decodeparms.put(PdfName.PREDICTOR, new PdfNumber(15));
decodeparms.put(PdfName.COLUMNS, new PdfNumber(width));
decodeparms.put(PdfName.COLORS, new PdfNumber((colorType == 3 || (colorType & 2) == 0) ? 1 : 3));
additional.put(PdfName.DECODEPARMS, decodeparms);
}
if (additional.get(PdfName.COLORSPACE) == null)
additional.put(PdfName.COLORSPACE, getColorspace());
if (intent != null)
additional.put(PdfName.INTENT, intent);
if (additional.size() > 0)
img.setAdditional(additional);
if (icc_profile != null)
img.tagICC(icc_profile);
if (palShades) {
Image im2 = Image.getInstance(width, height, 1, 8, smask);
im2.makeMask();
img.setImageMask(im2);
}
if (genBWMask) {
Image im2 = Image.getInstance(width, height, 1, 1, smask);
im2.makeMask();
img.setImageMask(im2);
}
img.setDpi(dpiX, dpiY);
img.setXYRatio(XYRatio);
img.setOriginalType(Image.ORIGINAL_PNG);
return img;
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
public static final int getInt(InputStream is) throws IOException {
return (is.read() << 24) + (is.read() << 16) + (is.read() << 8) + is.read();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
public static final int getWord(InputStream is) throws IOException {
return (is.read() << 8) + is.read();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
public static final String getString(InputStream is) throws IOException {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < 4; i++) {
buf.append((char)is.read());
}
return buf.toString();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/InputMeta.java
public int readWord() throws IOException{
length += 2;
int k1 = in.read();
if (k1 < 0)
return 0;
return (k1 + (in.read() << 8)) & 0xffff;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/InputMeta.java
public int readShort() throws IOException{
int k = readWord();
if (k > 0x7fff)
k -= 0x10000;
return k;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/InputMeta.java
public int readInt() throws IOException{
length += 4;
int k1 = in.read();
if (k1 < 0)
return 0;
int k2 = in.read() << 8;
int k3 = in.read() << 16;
return k1 + k2 + k3 + (in.read() << 24);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/InputMeta.java
public int readByte() throws IOException{
++length;
return in.read() & 0xff;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/InputMeta.java
public void skip(int len) throws IOException{
length += len;
Utilities.skip(in, len);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/InputMeta.java
public BaseColor readColor() throws IOException{
int red = readByte();
int green = readByte();
int blue = readByte();
readByte();
return new BaseColor(red, green, blue);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaPen.java
public void init(InputMeta in) throws IOException {
style = in.readWord();
penWidth = in.readShort();
in.readWord();
color = in.readColor();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
public void init(InputMeta in) throws IOException {
height = Math.abs(in.readShort());
in.skip(2);
angle = (float)(in.readShort() / 1800.0 * Math.PI);
in.skip(2);
bold = (in.readShort() >= BOLDTHRESHOLD ? MARKER_BOLD : 0);
italic = (in.readByte() != 0 ? MARKER_ITALIC : 0);
underline = (in.readByte() != 0);
strikeout = (in.readByte() != 0);
charset = in.readByte();
in.skip(3);
pitchAndFamily = in.readByte();
byte name[] = new byte[nameSize];
int k;
for (k = 0; k < nameSize; ++k) {
int c = in.readByte();
if (c == 0) {
break;
}
name[k] = (byte)c;
}
try {
faceName = new String(name, 0, k, "Cp1252");
}
catch (UnsupportedEncodingException e) {
faceName = new String(name, 0, k);
}
faceName = faceName.toLowerCase();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
public void readAll() throws IOException, DocumentException{
if (in.readInt() != 0x9AC6CDD7) {
throw new DocumentException(MessageLocalization.getComposedMessage("not.a.placeable.windows.metafile"));
}
in.readWord();
left = in.readShort();
top = in.readShort();
right = in.readShort();
bottom = in.readShort();
inch = in.readWord();
state.setScalingX((float)(right - left) / (float)inch * 72f);
state.setScalingY((float)(bottom - top) / (float)inch * 72f);
state.setOffsetWx(left);
state.setOffsetWy(top);
state.setExtentWx(right - left);
state.setExtentWy(bottom - top);
in.readInt();
in.readWord();
in.skip(18);
int tsize;
int function;
cb.setLineCap(1);
cb.setLineJoin(1);
for (;;) {
int lenMarker = in.getLength();
tsize = in.readInt();
if (tsize < 3)
break;
function = in.readWord();
switch (function) {
case 0:
break;
case META_CREATEPALETTE:
case META_CREATEREGION:
case META_DIBCREATEPATTERNBRUSH:
state.addMetaObject(new MetaObject());
break;
case META_CREATEPENINDIRECT:
{
MetaPen pen = new MetaPen();
pen.init(in);
state.addMetaObject(pen);
break;
}
case META_CREATEBRUSHINDIRECT:
{
MetaBrush brush = new MetaBrush();
brush.init(in);
state.addMetaObject(brush);
break;
}
case META_CREATEFONTINDIRECT:
{
MetaFont font = new MetaFont();
font.init(in);
state.addMetaObject(font);
break;
}
case META_SELECTOBJECT:
{
int idx = in.readWord();
state.selectMetaObject(idx, cb);
break;
}
case META_DELETEOBJECT:
{
int idx = in.readWord();
state.deleteMetaObject(idx);
break;
}
case META_SAVEDC:
state.saveState(cb);
break;
case META_RESTOREDC:
{
int idx = in.readShort();
state.restoreState(idx, cb);
break;
}
case META_SETWINDOWORG:
state.setOffsetWy(in.readShort());
state.setOffsetWx(in.readShort());
break;
case META_SETWINDOWEXT:
state.setExtentWy(in.readShort());
state.setExtentWx(in.readShort());
break;
case META_MOVETO:
{
int y = in.readShort();
Point p = new Point(in.readShort(), y);
state.setCurrentPoint(p);
break;
}
case META_LINETO:
{
int y = in.readShort();
int x = in.readShort();
Point p = state.getCurrentPoint();
cb.moveTo(state.transformX(p.x), state.transformY(p.y));
cb.lineTo(state.transformX(x), state.transformY(y));
cb.stroke();
state.setCurrentPoint(new Point(x, y));
break;
}
case META_POLYLINE:
{
state.setLineJoinPolygon(cb);
int len = in.readWord();
int x = in.readShort();
int y = in.readShort();
cb.moveTo(state.transformX(x), state.transformY(y));
for (int k = 1; k < len; ++k) {
x = in.readShort();
y = in.readShort();
cb.lineTo(state.transformX(x), state.transformY(y));
}
cb.stroke();
break;
}
case META_POLYGON:
{
if (isNullStrokeFill(false))
break;
int len = in.readWord();
int sx = in.readShort();
int sy = in.readShort();
cb.moveTo(state.transformX(sx), state.transformY(sy));
for (int k = 1; k < len; ++k) {
int x = in.readShort();
int y = in.readShort();
cb.lineTo(state.transformX(x), state.transformY(y));
}
cb.lineTo(state.transformX(sx), state.transformY(sy));
strokeAndFill();
break;
}
case META_POLYPOLYGON:
{
if (isNullStrokeFill(false))
break;
int numPoly = in.readWord();
int lens[] = new int[numPoly];
for (int k = 0; k < lens.length; ++k)
lens[k] = in.readWord();
for (int j = 0; j < lens.length; ++j) {
int len = lens[j];
int sx = in.readShort();
int sy = in.readShort();
cb.moveTo(state.transformX(sx), state.transformY(sy));
for (int k = 1; k < len; ++k) {
int x = in.readShort();
int y = in.readShort();
cb.lineTo(state.transformX(x), state.transformY(y));
}
cb.lineTo(state.transformX(sx), state.transformY(sy));
}
strokeAndFill();
break;
}
case META_ELLIPSE:
{
if (isNullStrokeFill(state.getLineNeutral()))
break;
int b = in.readShort();
int r = in.readShort();
int t = in.readShort();
int l = in.readShort();
cb.arc(state.transformX(l), state.transformY(b), state.transformX(r), state.transformY(t), 0, 360);
strokeAndFill();
break;
}
case META_ARC:
{
if (isNullStrokeFill(state.getLineNeutral()))
break;
float yend = state.transformY(in.readShort());
float xend = state.transformX(in.readShort());
float ystart = state.transformY(in.readShort());
float xstart = state.transformX(in.readShort());
float b = state.transformY(in.readShort());
float r = state.transformX(in.readShort());
float t = state.transformY(in.readShort());
float l = state.transformX(in.readShort());
float cx = (r + l) / 2;
float cy = (t + b) / 2;
float arc1 = getArc(cx, cy, xstart, ystart);
float arc2 = getArc(cx, cy, xend, yend);
arc2 -= arc1;
if (arc2 <= 0)
arc2 += 360;
cb.arc(l, b, r, t, arc1, arc2);
cb.stroke();
break;
}
case META_PIE:
{
if (isNullStrokeFill(state.getLineNeutral()))
break;
float yend = state.transformY(in.readShort());
float xend = state.transformX(in.readShort());
float ystart = state.transformY(in.readShort());
float xstart = state.transformX(in.readShort());
float b = state.transformY(in.readShort());
float r = state.transformX(in.readShort());
float t = state.transformY(in.readShort());
float l = state.transformX(in.readShort());
float cx = (r + l) / 2;
float cy = (t + b) / 2;
float arc1 = getArc(cx, cy, xstart, ystart);
float arc2 = getArc(cx, cy, xend, yend);
arc2 -= arc1;
if (arc2 <= 0)
arc2 += 360;
ArrayList<float[]> ar = PdfContentByte.bezierArc(l, b, r, t, arc1, arc2);
if (ar.isEmpty())
break;
float pt[] = ar.get(0);
cb.moveTo(cx, cy);
cb.lineTo(pt[0], pt[1]);
for (int k = 0; k < ar.size(); ++k) {
pt = ar.get(k);
cb.curveTo(pt[2], pt[3], pt[4], pt[5], pt[6], pt[7]);
}
cb.lineTo(cx, cy);
strokeAndFill();
break;
}
case META_CHORD:
{
if (isNullStrokeFill(state.getLineNeutral()))
break;
float yend = state.transformY(in.readShort());
float xend = state.transformX(in.readShort());
float ystart = state.transformY(in.readShort());
float xstart = state.transformX(in.readShort());
float b = state.transformY(in.readShort());
float r = state.transformX(in.readShort());
float t = state.transformY(in.readShort());
float l = state.transformX(in.readShort());
float cx = (r + l) / 2;
float cy = (t + b) / 2;
float arc1 = getArc(cx, cy, xstart, ystart);
float arc2 = getArc(cx, cy, xend, yend);
arc2 -= arc1;
if (arc2 <= 0)
arc2 += 360;
ArrayList<float[]> ar = PdfContentByte.bezierArc(l, b, r, t, arc1, arc2);
if (ar.isEmpty())
break;
float pt[] = ar.get(0);
cx = pt[0];
cy = pt[1];
cb.moveTo(cx, cy);
for (int k = 0; k < ar.size(); ++k) {
pt = ar.get(k);
cb.curveTo(pt[2], pt[3], pt[4], pt[5], pt[6], pt[7]);
}
cb.lineTo(cx, cy);
strokeAndFill();
break;
}
case META_RECTANGLE:
{
if (isNullStrokeFill(true))
break;
float b = state.transformY(in.readShort());
float r = state.transformX(in.readShort());
float t = state.transformY(in.readShort());
float l = state.transformX(in.readShort());
cb.rectangle(l, b, r - l, t - b);
strokeAndFill();
break;
}
case META_ROUNDRECT:
{
if (isNullStrokeFill(true))
break;
float h = state.transformY(0) - state.transformY(in.readShort());
float w = state.transformX(in.readShort()) - state.transformX(0);
float b = state.transformY(in.readShort());
float r = state.transformX(in.readShort());
float t = state.transformY(in.readShort());
float l = state.transformX(in.readShort());
cb.roundRectangle(l, b, r - l, t - b, (h + w) / 4);
strokeAndFill();
break;
}
case META_INTERSECTCLIPRECT:
{
float b = state.transformY(in.readShort());
float r = state.transformX(in.readShort());
float t = state.transformY(in.readShort());
float l = state.transformX(in.readShort());
cb.rectangle(l, b, r - l, t - b);
cb.eoClip();
cb.newPath();
break;
}
case META_EXTTEXTOUT:
{
int y = in.readShort();
int x = in.readShort();
int count = in.readWord();
int flag = in.readWord();
int x1 = 0;
int y1 = 0;
int x2 = 0;
int y2 = 0;
if ((flag & (MetaFont.ETO_CLIPPED | MetaFont.ETO_OPAQUE)) != 0) {
x1 = in.readShort();
y1 = in.readShort();
x2 = in.readShort();
y2 = in.readShort();
}
byte text[] = new byte[count];
int k;
for (k = 0; k < count; ++k) {
byte c = (byte)in.readByte();
if (c == 0)
break;
text[k] = c;
}
String s;
try {
s = new String(text, 0, k, "Cp1252");
}
catch (UnsupportedEncodingException e) {
s = new String(text, 0, k);
}
outputText(x, y, flag, x1, y1, x2, y2, s);
break;
}
case META_TEXTOUT:
{
int count = in.readWord();
byte text[] = new byte[count];
int k;
for (k = 0; k < count; ++k) {
byte c = (byte)in.readByte();
if (c == 0)
break;
text[k] = c;
}
String s;
try {
s = new String(text, 0, k, "Cp1252");
}
catch (UnsupportedEncodingException e) {
s = new String(text, 0, k);
}
count = count + 1 & 0xfffe;
in.skip(count - k);
int y = in.readShort();
int x = in.readShort();
outputText(x, y, 0, 0, 0, 0, 0, s);
break;
}
case META_SETBKCOLOR:
state.setCurrentBackgroundColor(in.readColor());
break;
case META_SETTEXTCOLOR:
state.setCurrentTextColor(in.readColor());
break;
case META_SETTEXTALIGN:
state.setTextAlign(in.readWord());
break;
case META_SETBKMODE:
state.setBackgroundMode(in.readWord());
break;
case META_SETPOLYFILLMODE:
state.setPolyFillMode(in.readWord());
break;
case META_SETPIXEL:
{
BaseColor color = in.readColor();
int y = in.readShort();
int x = in.readShort();
cb.saveState();
cb.setColorFill(color);
cb.rectangle(state.transformX(x), state.transformY(y), .2f, .2f);
cb.fill();
cb.restoreState();
break;
}
case META_DIBSTRETCHBLT:
case META_STRETCHDIB: {
int rop = in.readInt();
if (function == META_STRETCHDIB) {
/*int usage = */ in.readWord();
}
int srcHeight = in.readShort();
int srcWidth = in.readShort();
int ySrc = in.readShort();
int xSrc = in.readShort();
float destHeight = state.transformY(in.readShort()) - state.transformY(0);
float destWidth = state.transformX(in.readShort()) - state.transformX(0);
float yDest = state.transformY(in.readShort());
float xDest = state.transformX(in.readShort());
byte b[] = new byte[tsize * 2 - (in.getLength() - lenMarker)];
for (int k = 0; k < b.length; ++k)
b[k] = (byte)in.readByte();
try {
ByteArrayInputStream inb = new ByteArrayInputStream(b);
Image bmp = BmpImage.getImage(inb, true, b.length);
cb.saveState();
cb.rectangle(xDest, yDest, destWidth, destHeight);
cb.clip();
cb.newPath();
bmp.scaleAbsolute(destWidth * bmp.getWidth() / srcWidth, -destHeight * bmp.getHeight() / srcHeight);
bmp.setAbsolutePosition(xDest - destWidth * xSrc / srcWidth, yDest + destHeight * ySrc / srcHeight - bmp.getScaledHeight());
cb.addImage(bmp);
cb.restoreState();
}
catch (Exception e) {
// empty on purpose
}
break;
}
}
in.skip(tsize * 2 - (in.getLength() - lenMarker));
}
state.cleanup(cb);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
public static byte[] wrapBMP(Image image) throws IOException {
if (image.getOriginalType() != Image.ORIGINAL_BMP)
throw new IOException(MessageLocalization.getComposedMessage("only.bmp.can.be.wrapped.in.wmf"));
InputStream imgIn;
byte data[] = null;
if (image.getOriginalData() == null) {
imgIn = image.getUrl().openStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int b = 0;
while ((b = imgIn.read()) != -1)
out.write(b);
imgIn.close();
data = out.toByteArray();
}
else
data = image.getOriginalData();
int sizeBmpWords = data.length - 14 + 1 >>> 1;
ByteArrayOutputStream os = new ByteArrayOutputStream();
// write metafile header
writeWord(os, 1);
writeWord(os, 9);
writeWord(os, 0x0300);
writeDWord(os, 9 + 4 + 5 + 5 + 13 + sizeBmpWords + 3); // total metafile size
writeWord(os, 1);
writeDWord(os, 14 + sizeBmpWords); // max record size
writeWord(os, 0);
// write records
writeDWord(os, 4);
writeWord(os, META_SETMAPMODE);
writeWord(os, 8);
writeDWord(os, 5);
writeWord(os, META_SETWINDOWORG);
writeWord(os, 0);
writeWord(os, 0);
writeDWord(os, 5);
writeWord(os, META_SETWINDOWEXT);
writeWord(os, (int)image.getHeight());
writeWord(os, (int)image.getWidth());
writeDWord(os, 13 + sizeBmpWords);
writeWord(os, META_DIBSTRETCHBLT);
writeDWord(os, 0x00cc0020);
writeWord(os, (int)image.getHeight());
writeWord(os, (int)image.getWidth());
writeWord(os, 0);
writeWord(os, 0);
writeWord(os, (int)image.getHeight());
writeWord(os, (int)image.getWidth());
writeWord(os, 0);
writeWord(os, 0);
os.write(data, 14, data.length - 14);
if ((data.length & 1) == 1)
os.write(0);
// writeDWord(os, 14 + sizeBmpWords);
// writeWord(os, META_STRETCHDIB);
// writeDWord(os, 0x00cc0020);
// writeWord(os, 0);
// writeWord(os, (int)image.height());
// writeWord(os, (int)image.width());
// writeWord(os, 0);
// writeWord(os, 0);
// writeWord(os, (int)image.height());
// writeWord(os, (int)image.width());
// writeWord(os, 0);
// writeWord(os, 0);
// os.write(data, 14, data.length - 14);
// if ((data.length & 1) == 1)
// os.write(0);
writeDWord(os, 3);
writeWord(os, 0);
os.close();
return os.toByteArray();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
public static void writeWord(OutputStream os, int v) throws IOException {
os.write(v & 0xff);
os.write(v >>> 8 & 0xff);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
public static void writeDWord(OutputStream os, int v) throws IOException {
writeWord(os, v & 0xffff);
writeWord(os, v >>> 16 & 0xffff);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaBrush.java
public void init(InputMeta in) throws IOException {
style = in.readWord();
color = in.readColor();
hatch = in.readWord();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
private void initialize(RandomAccessFileOrArray stream) throws IOException {
long nextTagOffset = 0L;
long maxOffset = stream.length();
int i, j;
IFDOffset = stream.getFilePointer();
numEntries = readUnsignedShort(stream);
fields = new TIFFField[numEntries];
for (i = 0; i < numEntries && nextTagOffset < maxOffset; i++) {
int tag = readUnsignedShort(stream);
int type = readUnsignedShort(stream);
int count = (int)readUnsignedInt(stream);
boolean processTag = true;
// The place to return to to read the next tag
nextTagOffset = stream.getFilePointer() + 4;
try {
// If the tag data can't fit in 4 bytes, the next 4 bytes
// contain the starting offset of the data
if (count*sizeOfType[type] > 4) {
long valueOffset = readUnsignedInt(stream);
// bounds check offset for EOF
if (valueOffset < maxOffset) {
stream.seek(valueOffset);
}
else {
// bad offset pointer .. skip tag
processTag = false;
}
}
} catch (ArrayIndexOutOfBoundsException ae) {
// if the data type is unknown we should skip this TIFF Field
processTag = false;
}
if (processTag) {
fieldIndex.put(Integer.valueOf(tag), Integer.valueOf(i));
Object obj = null;
switch (type) {
case TIFFField.TIFF_BYTE:
case TIFFField.TIFF_SBYTE:
case TIFFField.TIFF_UNDEFINED:
case TIFFField.TIFF_ASCII:
byte[] bvalues = new byte[count];
stream.readFully(bvalues, 0, count);
if (type == TIFFField.TIFF_ASCII) {
// Can be multiple strings
int index = 0, prevIndex = 0;
ArrayList<String> v = new ArrayList<String>();
while (index < count) {
while (index < count && bvalues[index++] != 0);
// When we encountered zero, means one string has ended
v.add(new String(bvalues, prevIndex,
(index - prevIndex)) );
prevIndex = index;
}
count = v.size();
String strings[] = new String[count];
for (int c = 0 ; c < count; c++) {
strings[c] = v.get(c);
}
obj = strings;
} else {
obj = bvalues;
}
break;
case TIFFField.TIFF_SHORT:
char[] cvalues = new char[count];
for (j = 0; j < count; j++) {
cvalues[j] = (char)readUnsignedShort(stream);
}
obj = cvalues;
break;
case TIFFField.TIFF_LONG:
long[] lvalues = new long[count];
for (j = 0; j < count; j++) {
lvalues[j] = readUnsignedInt(stream);
}
obj = lvalues;
break;
case TIFFField.TIFF_RATIONAL:
long[][] llvalues = new long[count][2];
for (j = 0; j < count; j++) {
llvalues[j][0] = readUnsignedInt(stream);
llvalues[j][1] = readUnsignedInt(stream);
}
obj = llvalues;
break;
case TIFFField.TIFF_SSHORT:
short[] svalues = new short[count];
for (j = 0; j < count; j++) {
svalues[j] = readShort(stream);
}
obj = svalues;
break;
case TIFFField.TIFF_SLONG:
int[] ivalues = new int[count];
for (j = 0; j < count; j++) {
ivalues[j] = readInt(stream);
}
obj = ivalues;
break;
case TIFFField.TIFF_SRATIONAL:
int[][] iivalues = new int[count][2];
for (j = 0; j < count; j++) {
iivalues[j][0] = readInt(stream);
iivalues[j][1] = readInt(stream);
}
obj = iivalues;
break;
case TIFFField.TIFF_FLOAT:
float[] fvalues = new float[count];
for (j = 0; j < count; j++) {
fvalues[j] = readFloat(stream);
}
obj = fvalues;
break;
case TIFFField.TIFF_DOUBLE:
double[] dvalues = new double[count];
for (j = 0; j < count; j++) {
dvalues[j] = readDouble(stream);
}
obj = dvalues;
break;
default:
break;
}
fields[i] = new TIFFField(tag, type, count, obj);
}
stream.seek(nextTagOffset);
}
// Read the offset of the next IFD.
try {
nextIFDOffset = readUnsignedInt(stream);
}
catch (Exception e) {
// broken tiffs may not have this pointer
nextIFDOffset = 0;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
private short readShort(RandomAccessFileOrArray stream)
throws IOException {
if (isBigEndian) {
return stream.readShort();
} else {
return stream.readShortLE();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
private int readUnsignedShort(RandomAccessFileOrArray stream)
throws IOException {
if (isBigEndian) {
return stream.readUnsignedShort();
} else {
return stream.readUnsignedShortLE();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
private int readInt(RandomAccessFileOrArray stream)
throws IOException {
if (isBigEndian) {
return stream.readInt();
} else {
return stream.readIntLE();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
private long readUnsignedInt(RandomAccessFileOrArray stream)
throws IOException {
if (isBigEndian) {
return stream.readUnsignedInt();
} else {
return stream.readUnsignedIntLE();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
private long readLong(RandomAccessFileOrArray stream)
throws IOException {
if (isBigEndian) {
return stream.readLong();
} else {
return stream.readLongLE();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
private float readFloat(RandomAccessFileOrArray stream)
throws IOException {
if (isBigEndian) {
return stream.readFloat();
} else {
return stream.readFloatLE();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
private double readDouble(RandomAccessFileOrArray stream)
throws IOException {
if (isBigEndian) {
return stream.readDouble();
} else {
return stream.readDoubleLE();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
private static int readUnsignedShort(RandomAccessFileOrArray stream,
boolean isBigEndian)
throws IOException {
if (isBigEndian) {
return stream.readUnsignedShort();
} else {
return stream.readUnsignedShortLE();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
private static long readUnsignedInt(RandomAccessFileOrArray stream,
boolean isBigEndian)
throws IOException {
if (isBigEndian) {
return stream.readUnsignedInt();
} else {
return stream.readUnsignedIntLE();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
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(MessageLocalization.getComposedMessage("bad.endianness.tag.not.0x4949.or.0x4d4d"));
}
boolean isBigEndian = endian == 0x4d4d;
int magic = readUnsignedShort(stream, isBigEndian);
if (magic != 42) {
throw new IllegalArgumentException(MessageLocalization.getComposedMessage("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;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
static Image ProcessExtraSamples(DeflaterOutputStream zip, DeflaterOutputStream mzip, byte[] outBuf, int samplePerPixel, int bitsPerSample, int width, int height) throws IOException {
if (bitsPerSample == 8) {
byte[] mask = new byte[width * height];
int mptr = 0;
int optr = 0;
int total = width * height * samplePerPixel;
for (int k = 0; k < total; k += samplePerPixel) {
for (int s = 0; s < samplePerPixel - 1; ++s) {
outBuf[optr++] = outBuf[k + s];
}
mask[mptr++] = outBuf[k + samplePerPixel - 1];
}
zip.write(outBuf, 0, optr);
mzip.write(mask, 0, mptr);
}
else
throw new IllegalArgumentException(MessageLocalization.getComposedMessage("extra.samples.are.not.supported"));
return null;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngWriter.java
public void writeHeader(int width, int height, int bitDepth, int colorType) throws IOException {
ByteArrayOutputStream ms = new ByteArrayOutputStream();
outputInt(width, ms);
outputInt(height, ms);
ms.write(bitDepth);
ms.write(colorType);
ms.write(0);
ms.write(0);
ms.write(0);
writeChunk(IHDR, ms.toByteArray());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngWriter.java
public void writeEnd() throws IOException {
writeChunk(IEND, new byte[0]);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngWriter.java
public void writeData(byte[] data, final int stride) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
DeflaterOutputStream zip = new DeflaterOutputStream(stream);
int k;
for (k = 0; k < data.length-stride; k += stride) {
zip.write(0);
zip.write(data, k, stride);
}
int remaining = data.length - k;
if (remaining > 0){
zip.write(0);
zip.write(data, k, remaining);
}
zip.finish();
writeChunk(IDAT, stream.toByteArray());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngWriter.java
public void writePalette(byte[] data) throws IOException {
writeChunk(PLTE, data);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngWriter.java
public void writeIccProfile(byte[] data) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
stream.write((byte)'I');
stream.write((byte)'C');
stream.write((byte)'C');
stream.write(0);
stream.write(0);
DeflaterOutputStream zip = new DeflaterOutputStream(stream);
zip.write(data);
zip.finish();
writeChunk(iCCP, stream.toByteArray());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngWriter.java
public void outputInt(int n) throws IOException {
outputInt(n, outp);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngWriter.java
public static void outputInt(int n, OutputStream s) throws IOException {
s.write((byte)(n >> 24));
s.write((byte)(n >> 16));
s.write((byte)(n >> 8));
s.write((byte)n);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngWriter.java
public void writeChunk(byte[] chunkType, byte[] data) throws IOException {
outputInt(data.length);
outp.write(chunkType, 0, 4);
outp.write(data);
int c = update_crc(0xffffffff, chunkType, 0, chunkType.length);
c = update_crc(c, data, 0, data.length) ^ 0xffffffff;
outputInt(c);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffWriter.java
public void writeFile(OutputStream stream) throws IOException {
stream.write(0x4d);
stream.write(0x4d);
stream.write(0);
stream.write(42);
writeLong(8, stream);
writeShort(ifd.size(), stream);
int offset = 8 + getIfdSize();
for (FieldBase field : ifd.values()) {
int size = field.getValueSize();
if (size > 4) {
field.setOffset(offset);
offset += size;
}
field.writeField(stream);
}
writeLong(0, stream);
for (FieldBase field : ifd.values()) {
field.writeValue(stream);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffWriter.java
public void writeField(OutputStream stream) throws IOException {
writeShort(tag, stream);
writeShort(fieldType, stream);
writeLong(count, stream);
if (data.length <= 4) {
stream.write(data);
for (int k = data.length; k < 4; ++k) {
stream.write(0);
}
}
else {
writeLong(offset, stream);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffWriter.java
public void writeValue(OutputStream stream) throws IOException {
if (data.length <= 4)
return;
stream.write(data);
if ((data.length & 1) == 1)
stream.write(0);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffWriter.java
public static void writeShort(int v, OutputStream stream) throws IOException {
stream.write((v >> 8) & 0xff);
stream.write(v & 0xff);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffWriter.java
public static void writeLong(int v, OutputStream stream) throws IOException {
stream.write((v >> 24) & 0xff);
stream.write((v >> 16) & 0xff);
stream.write((v >> 8) & 0xff);
stream.write(v & 0xff);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffWriter.java
public static void compressLZW(OutputStream stream, int predictor, byte[] b, int height, int samplesPerPixel, int stride) throws IOException {
LZWCompressor lzwCompressor = new LZWCompressor(stream, 8, true);
boolean usePredictor = predictor == TIFFConstants.PREDICTOR_HORIZONTAL_DIFFERENCING;
if (!usePredictor) {
lzwCompressor.compress(b, 0, b.length);
} else {
int off = 0;
byte[] rowBuf = usePredictor ? new byte[stride] : null;
for (int i = 0; i < height; i++) {
System.arraycopy(b, off, rowBuf, 0, stride);
for (int j = stride - 1; j >= samplesPerPixel; j--) {
rowBuf[j] -= rowBuf[j - samplesPerPixel];
}
lzwCompressor.compress(rowBuf, 0, stride);
off += stride;
}
}
lzwCompressor.flush();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
public byte[] getEncodedRecipient(int index) throws IOException, GeneralSecurityException {
//Certificate certificate = recipient.getX509();
PdfPublicKeyRecipient recipient = recipients.get(index);
byte[] cms = recipient.getCms();
if (cms != null) return cms;
Certificate certificate = recipient.getCertificate();
int permission = recipient.getPermission();//PdfWriter.AllowCopy | PdfWriter.AllowPrinting | PdfWriter.AllowScreenReaders | PdfWriter.AllowAssembly;
int revision = 3;
permission |= revision==3 ? 0xfffff0c0 : 0xffffffc0;
permission &= 0xfffffffc;
permission += 1;
byte[] pkcs7input = new byte[24];
byte one = (byte)permission;
byte two = (byte)(permission >> 8);
byte three = (byte)(permission >> 16);
byte four = (byte)(permission >> 24);
System.arraycopy(seed, 0, pkcs7input, 0, 20); // put this seed in the pkcs7 input
pkcs7input[20] = four;
pkcs7input[21] = three;
pkcs7input[22] = two;
pkcs7input[23] = one;
ASN1Primitive obj = createDERForRecipient(pkcs7input, (X509Certificate)certificate);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DEROutputStream k = new DEROutputStream(baos);
k.writeObject(obj);
cms = baos.toByteArray();
recipient.setCms(cms);
return cms;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
public PdfArray getEncodedRecipients() throws IOException,
GeneralSecurityException {
PdfArray EncodedRecipients = new PdfArray();
byte[] cms = null;
for (int i=0; i<recipients.size(); i++)
try {
cms = getEncodedRecipient(i);
EncodedRecipients.add(new PdfLiteral(PdfContentByte.escapeString(cms)));
} catch (GeneralSecurityException e) {
EncodedRecipients = null;
} catch (IOException e) {
EncodedRecipients = null;
}
return EncodedRecipients;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert)
throws IOException,
GeneralSecurityException
{
String s = "1.2.840.113549.3.2";
AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(algorithmparameters.getEncoded("ASN.1"));
ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
ASN1Primitive derobject = asn1inputstream.readObject();
KeyGenerator keygenerator = KeyGenerator.getInstance(s);
keygenerator.init(128);
SecretKey secretkey = keygenerator.generateKey();
Cipher cipher = Cipher.getInstance(s);
cipher.init(1, secretkey, algorithmparameters);
byte[] abyte1 = cipher.doFinal(in);
DEROctetString deroctetstring = new DEROctetString(abyte1);
KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject);
EncryptedContentInfo encryptedcontentinfo =
new EncryptedContentInfo(PKCSObjectIdentifiers.data, algorithmidentifier, deroctetstring);
EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null);
ContentInfo contentinfo =
new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
return contentinfo.toASN1Primitive();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
throws GeneralSecurityException, IOException
{
ASN1InputStream asn1inputstream =
new ASN1InputStream(new ByteArrayInputStream(x509certificate.getTBSCertificate()));
TBSCertificateStructure tbscertificatestructure =
TBSCertificateStructure.getInstance(asn1inputstream.readObject());
AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithm();
IssuerAndSerialNumber issuerandserialnumber =
new IssuerAndSerialNumber(
tbscertificatestructure.getIssuer(),
tbscertificatestructure.getSerialNumber().getValue());
Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId());
try{
cipher.init(1, x509certificate);
}catch(InvalidKeyException e){
cipher.init(1,x509certificate.getPublicKey());
}
DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
return new KeyTransRecipientInfo( recipId, algorithmidentifier, deroctetstring);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructureTreeRoot.java
private void createNumTree() throws IOException {
if (numTree != null) return;
numTree = new HashMap<Integer, PdfIndirectReference>();
for (Integer i: parentTree.keySet()) {
PdfArray ar = (PdfArray)parentTree.get(i);
numTree.put(i, writer.addToBody(ar).getIndirectReference());
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructureTreeRoot.java
public HashMap<Integer, PdfIndirectReference> getNumTree() throws IOException {
if (numTree == null) createNumTree();
return numTree;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructureTreeRoot.java
private void nodeProcess(PdfDictionary struc, PdfIndirectReference reference) throws IOException {
PdfObject obj = struc.get(PdfName.K);
if (obj != null && obj.isArray()) {
PdfArray ar = (PdfArray)obj;
for (int k = 0; k < ar.size(); ++k) {
PdfDictionary dictionary = ar.getAsDict(k);
if (dictionary == null)
continue;
if (!PdfName.STRUCTELEM.equals(dictionary.get(PdfName.TYPE)))
continue;
if (ar.getPdfObject(k) instanceof PdfStructureElement) {
PdfStructureElement e = (PdfStructureElement) dictionary;
ar.set(k, e.getReference());
nodeProcess(e, e.getReference());
}
}
}
if (reference != null)
writer.addToBody(struc, reference);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructureTreeRoot.java
void buildTree() throws IOException {
createNumTree();
PdfDictionary dicTree = PdfNumberTree.writeTree(numTree, writer);
if (dicTree != null)
put(PdfName.PARENTTREE, writer.addToBody(dicTree).getIndirectReference());
if (classMap != null && !classes.isEmpty()) {
for (Map.Entry<PdfName,PdfObject> entry : classes.entrySet()) {
PdfObject value = entry.getValue();
if (value.isDictionary())
classMap.put(entry.getKey(), writer.addToBody(value).getIndirectReference());
else if (value.isArray()) {
PdfArray newArray = new PdfArray();
PdfArray array = (PdfArray)value;
for (int i = 0; i < array.size(); ++i) {
if (array.getPdfObject(i).isDictionary())
newArray.add(writer.addToBody(array.getAsDict(i)).getIndirectReference());
}
classMap.put(entry.getKey(),newArray);
}
}
put(PdfName.CLASSMAP, writer.addToBody(classMap).getIndirectReference());
}
nodeProcess(this, reference);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfString.java
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {
byte b[] = getBytes();
PdfEncryption crypto = null;
if (writer != null)
crypto = writer.getEncryption();
if (crypto != null && !crypto.isEmbeddedFilesOnly())
b = crypto.encryptByteArray(b);
if (hexWriting) {
ByteBuffer buf = new ByteBuffer();
buf.append('<');
int len = b.length;
for (int k = 0; k < len; ++k)
buf.appendHex(b[k]);
buf.append('>');
os.write(buf.toByteArray());
}
else
os.write(PdfContentByte.escapeString(b));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
Override
void writeFont(PdfWriter writer, PdfIndirectReference ref, Object[] params) throws DocumentException, IOException {
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
public static void exportToXML(List<HashMap<String, Object>> list, OutputStream out, String encoding, boolean onlyASCII) throws IOException {
String jenc = IanaEncodings.getJavaEncoding(encoding);
Writer wrt = new BufferedWriter(new OutputStreamWriter(out, jenc));
exportToXML(list, wrt, encoding, onlyASCII);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
public static void exportToXML(List<HashMap<String, Object>> list, Writer wrt, String encoding, boolean onlyASCII) throws IOException {
wrt.write("<?xml version=\"1.0\" encoding=\"");
wrt.write(XMLUtil.escapeXML(encoding, onlyASCII));
wrt.write("\"?>\n<Bookmark>\n");
exportToXMLNode(list, wrt, 1, onlyASCII);
wrt.write("</Bookmark>\n");
wrt.flush();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
public static List<HashMap<String, Object>> importFromXML(InputStream in) throws IOException {
SimpleBookmark book = new SimpleBookmark();
SimpleXMLParser.parse(book, in);
return book.topList;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
public static List<HashMap<String, Object>> importFromXML(Reader in) throws IOException {
SimpleBookmark book = new SimpleBookmark();
SimpleXMLParser.parse(book, in);
return book.topList;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FdfReader.java
Override
protected void readPdf() throws IOException {
fields = new HashMap<String, PdfDictionary>();
try {
tokens.checkFdfHeader();
rebuildXref();
readDocObj();
}
finally {
try {
tokens.close();
}
catch (Exception e) {
// empty on purpose
}
}
readFields();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FdfReader.java
public byte[] getAttachedFile(String name) throws IOException {
PdfDictionary field = fields.get(name);
if (field != null) {
PdfIndirectReference ir = (PRIndirectReference)field.get(PdfName.V);
PdfDictionary filespec = (PdfDictionary)getPdfObject(ir.getNumber());
PdfDictionary ef = filespec.getAsDict(PdfName.EF);
ir = (PRIndirectReference)ef.get(PdfName.F);
PRStream stream = (PRStream)getPdfObject(ir.getNumber());
return getStreamBytes(stream);
}
return new byte[0];
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
public void close() throws IOException {
finish();
out.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
public void flush() throws IOException {
out.flush();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
public void write(int b) throws IOException {
sb[0] = (byte)b;
write(sb, 0, 1);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
public void write(byte[] b, int off, int len) throws IOException {
if (aes) {
byte[] b2 = cipher.update(b, off, len);
if (b2 == null || b2.length == 0)
return;
out.write(b2, 0, b2.length);
}
else {
byte[] b2 = new byte[Math.min(len, 4192)];
while (len > 0) {
int sz = Math.min(len, b2.length);
arcfour.encryptARCFOUR(b, off, sz, b2, 0);
out.write(b2, 0, sz);
len -= sz;
off += sz;
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
public void finish() throws IOException {
if (!finished) {
finished = true;
if (aes) {
byte[] b;
try {
b = cipher.doFinal();
} catch (Exception ex) {
throw new ExceptionConverter(ex);
}
out.write(b, 0, b.length);
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFields.java
public void addDocument(PdfReader reader) throws DocumentException, IOException {
fc.addDocument(reader);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFields.java
public void addDocument(PdfReader reader, List<Integer> pagesToKeep) throws DocumentException, IOException {
fc.addDocument(reader, pagesToKeep);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFields.java
public void addDocument(PdfReader reader, String ranges) throws DocumentException, IOException {
fc.addDocument(reader, SequenceList.expand(ranges, reader.getNumberOfPages()));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
public void process(RandomAccessFileOrArray rf) throws DocumentException, IOException
{
String line;
boolean isMetrics = false;
while ((line = rf.readLine()) != null)
{
StringTokenizer tok = new StringTokenizer(line, " ,\n\r\t\f");
if (!tok.hasMoreTokens())
continue;
String ident = tok.nextToken();
if (ident.equals("FontName"))
FontName = tok.nextToken("\u00ff").substring(1);
else if (ident.equals("FullName"))
FullName = tok.nextToken("\u00ff").substring(1);
else if (ident.equals("FamilyName"))
FamilyName = tok.nextToken("\u00ff").substring(1);
else if (ident.equals("Weight"))
Weight = tok.nextToken("\u00ff").substring(1);
else if (ident.equals("ItalicAngle"))
ItalicAngle = Float.parseFloat(tok.nextToken());
else if (ident.equals("IsFixedPitch"))
IsFixedPitch = tok.nextToken().equals("true");
else if (ident.equals("CharacterSet"))
CharacterSet = tok.nextToken("\u00ff").substring(1);
else if (ident.equals("FontBBox"))
{
llx = (int)Float.parseFloat(tok.nextToken());
lly = (int)Float.parseFloat(tok.nextToken());
urx = (int)Float.parseFloat(tok.nextToken());
ury = (int)Float.parseFloat(tok.nextToken());
}
else if (ident.equals("UnderlinePosition"))
UnderlinePosition = (int)Float.parseFloat(tok.nextToken());
else if (ident.equals("UnderlineThickness"))
UnderlineThickness = (int)Float.parseFloat(tok.nextToken());
else if (ident.equals("EncodingScheme"))
EncodingScheme = tok.nextToken("\u00ff").substring(1);
else if (ident.equals("CapHeight"))
CapHeight = (int)Float.parseFloat(tok.nextToken());
else if (ident.equals("XHeight"))
XHeight = (int)Float.parseFloat(tok.nextToken());
else if (ident.equals("Ascender"))
Ascender = (int)Float.parseFloat(tok.nextToken());
else if (ident.equals("Descender"))
Descender = (int)Float.parseFloat(tok.nextToken());
else if (ident.equals("StdHW"))
StdHW = (int)Float.parseFloat(tok.nextToken());
else if (ident.equals("StdVW"))
StdVW = (int)Float.parseFloat(tok.nextToken());
else if (ident.equals("StartCharMetrics"))
{
isMetrics = true;
break;
}
}
if (!isMetrics)
throw new DocumentException(MessageLocalization.getComposedMessage("missing.startcharmetrics.in.1", fileName));
while ((line = rf.readLine()) != null)
{
StringTokenizer tok = new StringTokenizer(line);
if (!tok.hasMoreTokens())
continue;
String ident = tok.nextToken();
if (ident.equals("EndCharMetrics"))
{
isMetrics = false;
break;
}
Integer C = Integer.valueOf(-1);
Integer WX = Integer.valueOf(250);
String N = "";
int B[] = null;
tok = new StringTokenizer(line, ";");
while (tok.hasMoreTokens())
{
StringTokenizer tokc = new StringTokenizer(tok.nextToken());
if (!tokc.hasMoreTokens())
continue;
ident = tokc.nextToken();
if (ident.equals("C"))
C = Integer.valueOf(tokc.nextToken());
else if (ident.equals("WX"))
WX = Integer.valueOf((int)Float.parseFloat(tokc.nextToken()));
else if (ident.equals("N"))
N = tokc.nextToken();
else if (ident.equals("B")) {
B = new int[]{Integer.parseInt(tokc.nextToken()),
Integer.parseInt(tokc.nextToken()),
Integer.parseInt(tokc.nextToken()),
Integer.parseInt(tokc.nextToken())};
}
}
Object metrics[] = new Object[]{C, WX, N, B};
if (C.intValue() >= 0)
CharMetrics.put(C, metrics);
CharMetrics.put(N, metrics);
}
if (isMetrics)
throw new DocumentException(MessageLocalization.getComposedMessage("missing.endcharmetrics.in.1", fileName));
if (!CharMetrics.containsKey("nonbreakingspace")) {
Object[] space = CharMetrics.get("space");
if (space != null)
CharMetrics.put("nonbreakingspace", space);
}
while ((line = rf.readLine()) != null)
{
StringTokenizer tok = new StringTokenizer(line);
if (!tok.hasMoreTokens())
continue;
String ident = tok.nextToken();
if (ident.equals("EndFontMetrics"))
return;
if (ident.equals("StartKernPairs"))
{
isMetrics = true;
break;
}
}
if (!isMetrics)
throw new DocumentException(MessageLocalization.getComposedMessage("missing.endfontmetrics.in.1", fileName));
while ((line = rf.readLine()) != null)
{
StringTokenizer tok = new StringTokenizer(line);
if (!tok.hasMoreTokens())
continue;
String ident = tok.nextToken();
if (ident.equals("KPX"))
{
String first = tok.nextToken();
String second = tok.nextToken();
Integer width = Integer.valueOf((int)Float.parseFloat(tok.nextToken()));
Object relates[] = KernPairs.get(first);
if (relates == null)
KernPairs.put(first, new Object[]{second, width});
else
{
int n = relates.length;
Object relates2[] = new Object[n + 2];
System.arraycopy(relates, 0, relates2, 0, n);
relates2[n] = second;
relates2[n + 1] = width;
KernPairs.put(first, relates2);
}
}
else if (ident.equals("EndKernPairs"))
{
isMetrics = false;
break;
}
}
if (isMetrics)
throw new DocumentException(MessageLocalization.getComposedMessage("missing.endkernpairs.in.1", fileName));
rf.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
Override
void writeFont(PdfWriter writer, PdfIndirectReference ref, Object params[]) throws DocumentException, IOException {
int firstChar = ((Integer)params[0]).intValue();
int lastChar = ((Integer)params[1]).intValue();
byte shortTag[] = (byte[])params[2];
boolean subsetp = ((Boolean)params[3]).booleanValue() && subset;
if (!subsetp) {
firstChar = 0;
lastChar = shortTag.length - 1;
for (int k = 0; k < shortTag.length; ++k)
shortTag[k] = 1;
}
PdfIndirectReference ind_font = null;
PdfObject pobj = null;
PdfIndirectObject obj = null;
pobj = getFullFontStream();
if (pobj != null){
obj = writer.addToBody(pobj);
ind_font = obj.getIndirectReference();
}
pobj = getFontDescriptor(ind_font);
if (pobj != null){
obj = writer.addToBody(pobj);
ind_font = obj.getIndirectReference();
}
pobj = getFontBaseType(ind_font, firstChar, lastChar, shortTag);
writer.addToBody(pobj, ref);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseField.java
protected BaseFont getRealFont() throws IOException, DocumentException {
if (font == null)
return BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false);
else
return font;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public void decodeGenericDictionary(PdfDictionary merged, BaseField tx) throws IOException, DocumentException {
int flags = 0;
// the text size and color
PdfString da = merged.getAsString(PdfName.DA);
if (da != null) {
Object dab[] = splitDAelements(da.toUnicodeString());
if (dab[DA_SIZE] != null)
tx.setFontSize(((Float)dab[DA_SIZE]).floatValue());
if (dab[DA_COLOR] != null)
tx.setTextColor((BaseColor)dab[DA_COLOR]);
if (dab[DA_FONT] != null) {
PdfDictionary font = merged.getAsDict(PdfName.DR);
if (font != null) {
font = font.getAsDict(PdfName.FONT);
if (font != null) {
PdfObject po = font.get(new PdfName((String)dab[DA_FONT]));
if (po != null && po.type() == PdfObject.INDIRECT) {
PRIndirectReference por = (PRIndirectReference)po;
BaseFont bp = new DocumentFont((PRIndirectReference)po);
tx.setFont(bp);
Integer porkey = Integer.valueOf(por.getNumber());
BaseFont porf = extensionFonts.get(porkey);
if (porf == null) {
if (!extensionFonts.containsKey(porkey)) {
PdfDictionary fo = (PdfDictionary)PdfReader.getPdfObject(po);
PdfDictionary fd = fo.getAsDict(PdfName.FONTDESCRIPTOR);
if (fd != null) {
PRStream prs = (PRStream)PdfReader.getPdfObject(fd.get(PdfName.FONTFILE2));
if (prs == null)
prs = (PRStream)PdfReader.getPdfObject(fd.get(PdfName.FONTFILE3));
if (prs == null) {
extensionFonts.put(porkey, null);
}
else {
try {
porf = BaseFont.createFont("font.ttf", BaseFont.IDENTITY_H, true, false, PdfReader.getStreamBytes(prs), null);
}
catch (Exception e) {
}
extensionFonts.put(porkey, porf);
}
}
}
}
if (tx instanceof TextField)
((TextField)tx).setExtensionFont(porf);
}
else {
BaseFont bf = localFonts.get(dab[DA_FONT]);
if (bf == null) {
String fn[] = stdFieldFontNames.get(dab[DA_FONT]);
if (fn != null) {
try {
String enc = "winansi";
if (fn.length > 1)
enc = fn[1];
bf = BaseFont.createFont(fn[0], enc, false);
tx.setFont(bf);
}
catch (Exception e) {
// empty
}
}
}
else
tx.setFont(bf);
}
}
}
}
}
//rotation, border and background color
PdfDictionary mk = merged.getAsDict(PdfName.MK);
if (mk != null) {
PdfArray ar = mk.getAsArray(PdfName.BC);
BaseColor border = getMKColor(ar);
tx.setBorderColor(border);
if (border != null)
tx.setBorderWidth(1);
ar = mk.getAsArray(PdfName.BG);
tx.setBackgroundColor(getMKColor(ar));
PdfNumber rotation = mk.getAsNumber(PdfName.R);
if (rotation != null)
tx.setRotation(rotation.intValue());
}
//flags
PdfNumber nfl = merged.getAsNumber(PdfName.F);
flags = 0;
tx.setVisibility(BaseField.VISIBLE_BUT_DOES_NOT_PRINT);
if (nfl != null) {
flags = nfl.intValue();
if ((flags & PdfFormField.FLAGS_PRINT) != 0 && (flags & PdfFormField.FLAGS_HIDDEN) != 0)
tx.setVisibility(BaseField.HIDDEN);
else if ((flags & PdfFormField.FLAGS_PRINT) != 0 && (flags & PdfFormField.FLAGS_NOVIEW) != 0)
tx.setVisibility(BaseField.HIDDEN_BUT_PRINTABLE);
else if ((flags & PdfFormField.FLAGS_PRINT) != 0)
tx.setVisibility(BaseField.VISIBLE);
}
//multiline
nfl = merged.getAsNumber(PdfName.FF);
flags = 0;
if (nfl != null)
flags = nfl.intValue();
tx.setOptions(flags);
if ((flags & PdfFormField.FF_COMB) != 0) {
PdfNumber maxLen = merged.getAsNumber(PdfName.MAXLEN);
int len = 0;
if (maxLen != null)
len = maxLen.intValue();
tx.setMaxCharacterLength(len);
}
//alignment
nfl = merged.getAsNumber(PdfName.Q);
if (nfl != null) {
if (nfl.intValue() == PdfFormField.Q_CENTER)
tx.setAlignment(Element.ALIGN_CENTER);
else if (nfl.intValue() == PdfFormField.Q_RIGHT)
tx.setAlignment(Element.ALIGN_RIGHT);
}
//border styles
PdfDictionary bs = merged.getAsDict(PdfName.BS);
if (bs != null) {
PdfNumber w = bs.getAsNumber(PdfName.W);
if (w != null)
tx.setBorderWidth(w.floatValue());
PdfName s = bs.getAsName(PdfName.S);
if (PdfName.D.equals(s))
tx.setBorderStyle(PdfBorderDictionary.STYLE_DASHED);
else if (PdfName.B.equals(s))
tx.setBorderStyle(PdfBorderDictionary.STYLE_BEVELED);
else if (PdfName.I.equals(s))
tx.setBorderStyle(PdfBorderDictionary.STYLE_INSET);
else if (PdfName.U.equals(s))
tx.setBorderStyle(PdfBorderDictionary.STYLE_UNDERLINE);
}
else {
PdfArray bd = merged.getAsArray(PdfName.BORDER);
if (bd != null) {
if (bd.size() >= 3)
tx.setBorderWidth(bd.getAsNumber(2).floatValue());
if (bd.size() >= 4)
tx.setBorderStyle(PdfBorderDictionary.STYLE_DASHED);
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
PdfAppearance getAppearance(PdfDictionary merged, String values[], String fieldName) throws IOException, DocumentException {
topFirst = 0;
String text = values.length > 0 ? values[0] : null;
TextField tx = null;
if (fieldCache == null || !fieldCache.containsKey(fieldName)) {
tx = new TextField(writer, null, null);
tx.setExtraMargin(extraMarginLeft, extraMarginTop);
tx.setBorderWidth(0);
tx.setSubstitutionFonts(substitutionFonts);
decodeGenericDictionary(merged, tx);
//rect
PdfArray rect = merged.getAsArray(PdfName.RECT);
Rectangle box = PdfReader.getNormalizedRectangle(rect);
if (tx.getRotation() == 90 || tx.getRotation() == 270)
box = box.rotate();
tx.setBox(box);
if (fieldCache != null)
fieldCache.put(fieldName, tx);
}
else {
tx = fieldCache.get(fieldName);
tx.setWriter(writer);
}
PdfName fieldType = merged.getAsName(PdfName.FT);
if (PdfName.TX.equals(fieldType)) {
if (values.length > 0 && values[0] != null) {
tx.setText(values[0]);
}
return tx.getAppearance();
}
if (!PdfName.CH.equals(fieldType))
throw new DocumentException(MessageLocalization.getComposedMessage("an.appearance.was.requested.without.a.variable.text.field"));
PdfArray opt = merged.getAsArray(PdfName.OPT);
int flags = 0;
PdfNumber nfl = merged.getAsNumber(PdfName.FF);
if (nfl != null)
flags = nfl.intValue();
if ((flags & PdfFormField.FF_COMBO) != 0 && opt == null) {
tx.setText(text);
return tx.getAppearance();
}
if (opt != null) {
String choices[] = new String[opt.size()];
String choicesExp[] = new String[opt.size()];
for (int k = 0; k < opt.size(); ++k) {
PdfObject obj = opt.getPdfObject(k);
if (obj.isString()) {
choices[k] = choicesExp[k] = ((PdfString)obj).toUnicodeString();
}
else {
PdfArray a = (PdfArray) obj;
choicesExp[k] = a.getAsString(0).toUnicodeString();
choices[k] = a.getAsString(1).toUnicodeString();
}
}
if ((flags & PdfFormField.FF_COMBO) != 0) {
for (int k = 0; k < choices.length; ++k) {
if (text.equals(choicesExp[k])) {
text = choices[k];
break;
}
}
tx.setText(text);
return tx.getAppearance();
}
ArrayList<Integer> indexes = new ArrayList<Integer>();
for (int k = 0; k < choicesExp.length; ++k) {
for (int j = 0; j < values.length; ++j) {
String val = values[j];
if (val != null && val.equals(choicesExp[k])) {
indexes.add( Integer.valueOf( k ) );
break;
}
}
}
tx.setChoices(choices);
tx.setChoiceExports(choicesExp);
tx.setChoiceSelections( indexes );
}
PdfAppearance app = tx.getListAppearance();
topFirst = tx.getTopFirst();
return app;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
PdfAppearance getAppearance(PdfDictionary merged, String text, String fieldName) throws IOException, DocumentException {
String valueArr[] = new String[1];
valueArr[0] = text;
return getAppearance( merged, valueArr, fieldName );
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public void mergeXfaData(Node n) throws IOException, DocumentException {
XfaForm.Xml2SomDatasets data = new XfaForm.Xml2SomDatasets(n);
for (String string : data.getOrder()) {
String name = string;
String text = XfaForm.getNodeText(data.getName2Node().get(name));
setField(name, text);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public void setFields(FdfReader fdf) throws IOException, DocumentException {
HashMap<String, PdfDictionary> fd = fdf.getFields();
for (String f: fd.keySet()) {
String v = fdf.getFieldValue(f);
if (v != null)
setField(f, v);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public void setFields(XfdfReader xfdf) throws IOException, DocumentException {
HashMap<String, String> fd = xfdf.getFields();
for (String f: fd.keySet()) {
String v = xfdf.getFieldValue(f);
if (v != null)
setField(f, v);
List<String> l = xfdf.getListValues(f);
if (l != null)
setListSelection(v, l.toArray(new String[l.size()]));
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean regenerateField(String name) throws IOException, DocumentException {
String value = getField(name);
return setField(name, value, value);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setField(String name, String value) throws IOException, DocumentException {
return setField(name, value, null);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setFieldRichValue(String name, String richValue) throws DocumentException, IOException {
if (writer == null) {
// can't set field values: fail
throw new DocumentException(MessageLocalization.getComposedMessage("this.acrofields.instance.is.read.only"));
}
AcroFields.Item item = getFieldItem(name);
if (item == null) {
// can't find the field: fail.
return false;
}
if (getFieldType(name) != FIELD_TYPE_TEXT) {
// field isn't a text field: fail
return false;
}
PdfDictionary merged = item.getMerged(0);
PdfNumber ffNum = merged.getAsNumber(PdfName.FF);
int flagVal = 0;
if (ffNum != null) {
flagVal = ffNum.intValue();
}
if ((flagVal & PdfFormField.FF_RICHTEXT) == 0) {
// text field doesn't support rich text: fail
return false;
}
PdfString richString = new PdfString(richValue);
item.writeToAll(PdfName.RV, richString, Item.WRITE_MERGED | Item.WRITE_VALUE);
InputStream is = new ByteArrayInputStream(richValue.getBytes());
PdfString valueString = new PdfString(XmlToTxt.parse(is));
item.writeToAll(PdfName.V, valueString, Item.WRITE_MERGED | Item.WRITE_VALUE);
return true;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setField(String name, String value, String display) throws IOException, DocumentException {
if (writer == null)
throw new DocumentException(MessageLocalization.getComposedMessage("this.acrofields.instance.is.read.only"));
if (xfa.isXfaPresent()) {
name = xfa.findFieldName(name, this);
if (name == null)
return false;
String shortName = XfaForm.Xml2Som.getShortName(name);
Node xn = xfa.findDatasetsNode(shortName);
if (xn == null) {
xn = xfa.getDatasetsSom().insertNode(xfa.getDatasetsNode(), shortName);
}
xfa.setNodeText(xn, value);
}
Item item = fields.get(name);
if (item == null)
return false;
PdfDictionary merged = item.getMerged( 0 );
PdfName type = merged.getAsName(PdfName.FT);
if (PdfName.TX.equals(type)) {
PdfNumber maxLen = merged.getAsNumber(PdfName.MAXLEN);
int len = 0;
if (maxLen != null)
len = maxLen.intValue();
if (len > 0)
value = value.substring(0, Math.min(len, value.length()));
}
if (display == null)
display = value;
if (PdfName.TX.equals(type) || PdfName.CH.equals(type)) {
PdfString v = new PdfString(value, PdfObject.TEXT_UNICODE);
for (int idx = 0; idx < item.size(); ++idx) {
PdfDictionary valueDic = item.getValue(idx);
valueDic.put(PdfName.V, v);
valueDic.remove(PdfName.I);
markUsed(valueDic);
merged = item.getMerged(idx);
merged.remove(PdfName.I);
merged.put(PdfName.V, v);
PdfDictionary widget = item.getWidget(idx);
if (generateAppearances) {
PdfAppearance app = getAppearance(merged, display, name);
if (PdfName.CH.equals(type)) {
PdfNumber n = new PdfNumber(topFirst);
widget.put(PdfName.TI, n);
merged.put(PdfName.TI, n);
}
PdfDictionary appDic = widget.getAsDict(PdfName.AP);
if (appDic == null) {
appDic = new PdfDictionary();
widget.put(PdfName.AP, appDic);
merged.put(PdfName.AP, appDic);
}
appDic.put(PdfName.N, app.getIndirectReference());
writer.releaseTemplate(app);
}
else {
widget.remove(PdfName.AP);
merged.remove(PdfName.AP);
}
markUsed(widget);
}
return true;
}
else if (PdfName.BTN.equals(type)) {
PdfNumber ff = item.getMerged(0).getAsNumber(PdfName.FF);
int flags = 0;
if (ff != null)
flags = ff.intValue();
if ((flags & PdfFormField.FF_PUSHBUTTON) != 0) {
//we'll assume that the value is an image in base64
Image img;
try {
img = Image.getInstance(Base64.decode(value));
}
catch (Exception e) {
return false;
}
PushbuttonField pb = getNewPushbuttonFromField(name);
pb.setImage(img);
replacePushbuttonField(name, pb.getField());
return true;
}
PdfName v = new PdfName(value);
ArrayList<String> lopt = new ArrayList<String>();
PdfArray opts = item.getValue(0).getAsArray(PdfName.OPT);
if (opts != null) {
for (int k = 0; k < opts.size(); ++k) {
PdfString valStr = opts.getAsString(k);
if (valStr != null)
lopt.add(valStr.toUnicodeString());
else
lopt.add(null);
}
}
int vidx = lopt.indexOf(value);
PdfName vt;
if (vidx >= 0)
vt = new PdfName(String.valueOf(vidx));
else
vt = v;
for (int idx = 0; idx < item.size(); ++idx) {
merged = item.getMerged(idx);
PdfDictionary widget = item.getWidget(idx);
PdfDictionary valDict = item.getValue(idx);
markUsed(item.getValue(idx));
valDict.put(PdfName.V, vt);
merged.put(PdfName.V, vt);
markUsed(widget);
if (isInAP(widget, vt)) {
merged.put(PdfName.AS, vt);
widget.put(PdfName.AS, vt);
}
else {
merged.put(PdfName.AS, PdfName.Off);
widget.put(PdfName.AS, PdfName.Off);
}
}
return true;
}
return false;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setListSelection(String name, String[] value) throws IOException, DocumentException {
Item item = getFieldItem(name);
if (item == null)
return false;
PdfDictionary merged = item.getMerged( 0 );
PdfName type = merged.getAsName(PdfName.FT);
if (!PdfName.CH.equals(type)) {
return false;
}
String[] options = getListOptionExport(name);
PdfArray array = new PdfArray();
for (String element : value) {
for (int j = 0; j < options.length; j++) {
if (options[j].equals(element)) {
array.add(new PdfNumber(j));
break;
}
}
}
item.writeToAll(PdfName.I, array, Item.WRITE_MERGED | Item.WRITE_VALUE);
PdfArray vals = new PdfArray();
for (int i = 0; i < value.length; ++i) {
vals.add( new PdfString( value[i] ) );
}
item.writeToAll(PdfName.V, vals, Item.WRITE_MERGED | Item.WRITE_VALUE);
PdfAppearance app = getAppearance( merged, value, name );
PdfDictionary apDic = new PdfDictionary();
apDic.put( PdfName.N, app.getIndirectReference() );
item.writeToAll(PdfName.AP, apDic, Item.WRITE_MERGED | Item.WRITE_WIDGET);
writer.releaseTemplate( app );
item.markUsed( this, Item.WRITE_VALUE | Item.WRITE_WIDGET );
return true;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public InputStream extractRevision(String field) throws IOException {
getSignatureNames();
field = getTranslatedFieldName(field);
if (!sigNames.containsKey(field))
return null;
int length = sigNames.get(field)[0];
RandomAccessFileOrArray raf = reader.getSafeFile();
return new RASInputStream(new WindowRandomAccessSource(raf.createSourceView(), 0, length));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
public void copyStructTreeForPage(PdfNumber sourceArrayNumber, int newArrayNumber) throws BadPdfFormatException, IOException {
// int documentHash = getDocumentHash(reader);
// if (!openedDocuments.contains(documentHash)) {
// openedDocuments.add(documentHash);
//
// }
if (copyPageMarks(parentTree, sourceArrayNumber, newArrayNumber) == returnType.NOTFOUND) {
throw new BadPdfFormatException(MessageLocalization.getComposedMessage("invalid.structparent"));
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
private returnType copyPageMarks(PdfDictionary parentTree, PdfNumber arrayNumber, int newArrayNumber) throws BadPdfFormatException, IOException {
PdfArray pages = (PdfArray) getDirectObject(parentTree.get(PdfName.NUMS));
if (pages == null) {
PdfArray kids = (PdfArray) getDirectObject(parentTree.get(PdfName.KIDS));
if (kids == null)
return returnType.NOTFOUND;
int cur = kids.size() / 2;
int begin = 0;
while (true) {
PdfDictionary kidTree = (PdfDictionary) getDirectObject(kids.getPdfObject(cur + begin));
switch (copyPageMarks(kidTree, arrayNumber, newArrayNumber)) {
case FOUND:
return returnType.FOUND;
case ABOVE:
begin += cur;
cur /= 2;
if (cur == 0)
cur = 1;
if (cur + begin == kids.size())
return returnType.ABOVE;
break;
case BELOW:
if (cur + begin == 0)
return returnType.BELOW;
if (cur == 0)
return returnType.NOTFOUND;
cur /= 2;
break;
default:
return returnType.NOTFOUND;
}
}
} else {
if (pages.size() == 0) return returnType.NOTFOUND;
return findAndCopyMarks(pages, arrayNumber.intValue(), newArrayNumber);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
private returnType findAndCopyMarks(PdfArray pages, int arrayNumber, int newArrayNumber) throws BadPdfFormatException, IOException {
if (pages.getAsNumber(0).intValue() > arrayNumber)
return returnType.BELOW;
if (pages.getAsNumber(pages.size() - 2).intValue() < arrayNumber)
return returnType.ABOVE;
int cur = pages.size() / 4;
int begin = 0;
int curNumber;
while (true) {
curNumber = pages.getAsNumber((begin + cur) * 2).intValue();
if (curNumber == arrayNumber) {
PdfObject obj = pages.getPdfObject((begin + cur) * 2 + 1);
while (obj.isIndirect()) obj = PdfReader.getPdfObjectRelease(obj);
//invalid Nums
if (!obj.isArray()) return returnType.NOTFOUND;
PdfObject firstNotNullKid = null;
for (PdfObject numObj: (PdfArray)obj){
if (numObj.isNull()) continue;
PdfObject res = writer.copyObject(numObj, true, false);
if (firstNotNullKid == null) firstNotNullKid = res;
structureTreeRoot.setPageMark(newArrayNumber, (PdfIndirectReference) res);
}
//Add kid to structureTreeRoot from structTreeRoot
PdfObject structKids = structTreeRoot.get(PdfName.K);
if (structKids == null || (!structKids.isArray() && !structKids.isIndirect())) {
// incorrect syntax of tags
addKid(structureTreeRoot, firstNotNullKid);
} else {
if (structKids.isIndirect()) {
addKid(structKids);
} else { //structKids.isArray()
for (PdfObject kid: (PdfArray)structKids)
addKid(kid);
}
}
return returnType.FOUND;
}
if (curNumber < arrayNumber) {
begin += cur;
cur /= 2;
if (cur == 0)
cur = 1;
if (cur + begin == pages.size())
return returnType.NOTFOUND;
continue;
}
if (cur + begin == 0)
return returnType.BELOW;
if (cur == 0)
return returnType.NOTFOUND;
cur /= 2;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
private void addKid(PdfObject obj) throws IOException, BadPdfFormatException {
if (!obj.isIndirect()) return;
PRIndirectReference currRef = (PRIndirectReference)obj;
PdfCopy.RefKey key = new PdfCopy.RefKey(currRef);
if (!writer.indirects.containsKey(key)) {
writer.copyIndirect(currRef, true, false);
}
PdfIndirectReference newKid = writer.indirects.get(key).getRef();
if (writer.updateRootKids) {
addKid(structureTreeRoot, newKid);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FdfWriter.java
public void writeTo(OutputStream os) throws IOException {
Wrt wrt = new Wrt(os, this);
wrt.writeTo();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FdfWriter.java
void writeTo() throws IOException {
PdfDictionary dic = new PdfDictionary();
dic.put(PdfName.FIELDS, calculate(fdf.fields));
if (fdf.file != null)
dic.put(PdfName.F, new PdfString(fdf.file, PdfObject.TEXT_UNICODE));
PdfDictionary fd = new PdfDictionary();
fd.put(PdfName.FDF, dic);
PdfIndirectReference ref = addToBody(fd).getIndirectReference();
os.write(getISOBytes("trailer\n"));
PdfDictionary trailer = new PdfDictionary();
trailer.put(PdfName.ROOT, ref);
trailer.toPdf(null, os);
os.write(getISOBytes("\n%%EOF\n"));
os.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRIndirectReference.java
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {
int n = writer.getNewObjectNumber(reader, number, generation);
os.write(PdfEncodings.convertToBytes(new StringBuffer().append(n).append(" 0 R").toString(), null));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDictionary.java
Override
public void toPdf(final PdfWriter writer, final OutputStream os) throws IOException {
os.write('<');
os.write('<');
// loop over all the object-pairs in the HashMap
PdfObject value;
int type = 0;
for (Entry<PdfName, PdfObject> e: hashMap.entrySet()) {
e.getKey().toPdf(writer, os);
value = e.getValue();
type = value.type();
if (type != PdfObject.ARRAY && type != PdfObject.DICTIONARY && type != PdfObject.NAME && type != PdfObject.STRING)
os.write(' ');
value.toPdf(writer, os);
}
os.write('>');
os.write('>');
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public void seek(long pos) throws IOException {
file.seek(pos);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public long getFilePointer() throws IOException {
return file.getFilePointer();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public void close() throws IOException {
file.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public long length() throws IOException {
return file.length();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public int read() throws IOException {
return file.read();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public String readString(int size) throws IOException {
StringBuilder buf = new StringBuilder();
int ch;
while ((size--) > 0) {
ch = read();
if (ch == -1)
break;
buf.append((char)ch);
}
return buf.toString();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public void throwError(String error) throws IOException {
throw new InvalidPdfException(MessageLocalization.getComposedMessage("1.at.file.pointer.2", error, String.valueOf(file.getFilePointer())));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public int getHeaderOffset() throws IOException{
String str = readString(1024);
int idx = str.indexOf("%PDF-");
if (idx < 0){
idx = str.indexOf("%FDF-");
if (idx < 0)
throw new InvalidPdfException(MessageLocalization.getComposedMessage("pdf.header.not.found"));
}
return idx;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public char checkPdfHeader() throws IOException {
file.seek(0);
String str = readString(1024);
int idx = str.indexOf("%PDF-");
if (idx != 0)
throw new InvalidPdfException(MessageLocalization.getComposedMessage("pdf.header.not.found"));
return str.charAt(7);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public void checkFdfHeader() throws IOException {
file.seek(0);
String str = readString(1024);
int idx = str.indexOf("%FDF-");
if (idx != 0)
throw new InvalidPdfException(MessageLocalization.getComposedMessage("fdf.header.not.found"));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public long getStartxref() throws IOException {
int arrLength = 1024;
long fileLength = file.length();
long pos = fileLength - arrLength;
if (pos < 1) pos = 1;
while (pos > 0){
file.seek(pos);
String str = readString(arrLength);
int idx = str.lastIndexOf("startxref");
if (idx >= 0) return pos + idx;
pos = pos - arrLength + 9; // 9 = "startxref".length()
}
throw new InvalidPdfException(MessageLocalization.getComposedMessage("pdf.startxref.not.found"));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public void nextValidToken() throws IOException {
int level = 0;
String n1 = null;
String n2 = null;
long ptr = 0;
while (nextToken()) {
if (type == TokenType.COMMENT)
continue;
switch (level) {
case 0:
{
if (type != TokenType.NUMBER)
return;
ptr = file.getFilePointer();
n1 = stringValue;
++level;
break;
}
case 1:
{
if (type != TokenType.NUMBER) {
file.seek(ptr);
type = TokenType.NUMBER;
stringValue = n1;
return;
}
n2 = stringValue;
++level;
break;
}
default:
{
if (type != TokenType.OTHER || !stringValue.equals("R")) {
file.seek(ptr);
type = TokenType.NUMBER;
stringValue = n1;
return;
}
type = TokenType.REF;
reference = Integer.parseInt(n1);
generation = Integer.parseInt(n2);
return;
}
}
}
if (level == 1){ // if the level 1 check returns EOF, then we are still looking at a number - set the type back to NUMBER
type = TokenType.NUMBER;
}
// if we hit here, the file is either corrupt (stream ended unexpectedly),
// or the last token ended exactly at the end of a stream. This last
// case can occur inside an Object Stream.
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public boolean nextToken() throws IOException {
int ch = 0;
do {
ch = file.read();
} while (ch != -1 && isWhitespace(ch));
if (ch == -1){
type = TokenType.ENDOFFILE;
return false;
}
// Note: We have to initialize stringValue here, after we've looked for the end of the stream,
// to ensure that we don't lose the value of a token that might end exactly at the end
// of the stream
final StringBuilder outBuf = new StringBuilder();
stringValue = EMPTY;
switch (ch) {
case '[':
type = TokenType.START_ARRAY;
break;
case ']':
type = TokenType.END_ARRAY;
break;
case '/':
{
outBuf.setLength(0);
type = TokenType.NAME;
while (true) {
ch = file.read();
if (delims[ch + 1])
break;
if (ch == '#') {
ch = (getHex(file.read()) << 4) + getHex(file.read());
}
outBuf.append((char)ch);
}
backOnePosition(ch);
break;
}
case '>':
ch = file.read();
if (ch != '>')
throwError(MessageLocalization.getComposedMessage("greaterthan.not.expected"));
type = TokenType.END_DIC;
break;
case '<':
{
int v1 = file.read();
if (v1 == '<') {
type = TokenType.START_DIC;
break;
}
outBuf.setLength(0);
type = TokenType.STRING;
hexString = true;
int v2 = 0;
while (true) {
while (isWhitespace(v1))
v1 = file.read();
if (v1 == '>')
break;
v1 = getHex(v1);
if (v1 < 0)
break;
v2 = file.read();
while (isWhitespace(v2))
v2 = file.read();
if (v2 == '>') {
ch = v1 << 4;
outBuf.append((char)ch);
break;
}
v2 = getHex(v2);
if (v2 < 0)
break;
ch = (v1 << 4) + v2;
outBuf.append((char)ch);
v1 = file.read();
}
if (v1 < 0 || v2 < 0)
throwError(MessageLocalization.getComposedMessage("error.reading.string"));
break;
}
case '%':
type = TokenType.COMMENT;
do {
ch = file.read();
} while (ch != -1 && ch != '\r' && ch != '\n');
break;
case '(':
{
outBuf.setLength(0);
type = TokenType.STRING;
hexString = false;
int nesting = 0;
while (true) {
ch = file.read();
if (ch == -1)
break;
if (ch == '(') {
++nesting;
}
else if (ch == ')') {
--nesting;
}
else if (ch == '\\') {
boolean lineBreak = false;
ch = file.read();
switch (ch) {
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case '(':
case ')':
case '\\':
break;
case '\r':
lineBreak = true;
ch = file.read();
if (ch != '\n')
backOnePosition(ch);
break;
case '\n':
lineBreak = true;
break;
default:
{
if (ch < '0' || ch > '7') {
break;
}
int octal = ch - '0';
ch = file.read();
if (ch < '0' || ch > '7') {
backOnePosition(ch);
ch = octal;
break;
}
octal = (octal << 3) + ch - '0';
ch = file.read();
if (ch < '0' || ch > '7') {
backOnePosition(ch);
ch = octal;
break;
}
octal = (octal << 3) + ch - '0';
ch = octal & 0xff;
break;
}
}
if (lineBreak)
continue;
if (ch < 0)
break;
}
else if (ch == '\r') {
ch = file.read();
if (ch < 0)
break;
if (ch != '\n') {
backOnePosition(ch);
ch = '\n';
}
}
if (nesting == -1)
break;
outBuf.append((char)ch);
}
if (ch == -1)
throwError(MessageLocalization.getComposedMessage("error.reading.string"));
break;
}
default:
{
outBuf.setLength(0);
if (ch == '-' || ch == '+' || ch == '.' || (ch >= '0' && ch <= '9')) {
type = TokenType.NUMBER;
if (ch == '-') {
// Take care of number like "--234". If Acrobat can read them so must we.
boolean minus = false;
do {
minus = !minus;
ch = file.read();
} while (ch == '-');
if (minus)
outBuf.append('-');
}
else {
outBuf.append((char)ch);
ch = file.read();
}
while (ch != -1 && ((ch >= '0' && ch <= '9') || ch == '.')) {
outBuf.append((char)ch);
ch = file.read();
}
}
else {
type = TokenType.OTHER;
do {
outBuf.append((char)ch);
ch = file.read();
} while (!delims[ch + 1]);
}
if(ch != -1)
backOnePosition(ch);
break;
}
}
if (outBuf != null)
stringValue = outBuf.toString();
return true;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
public boolean readLineSegment(byte input[]) throws IOException {
int c = -1;
boolean eol = false;
int ptr = 0;
int len = input.length;
// ssteward, pdftk-1.10, 040922:
// skip initial whitespace; added this because PdfReader.rebuildXref()
// assumes that line provided by readLineSegment does not have init. whitespace;
if ( ptr < len ) {
while ( isWhitespace( (c = read()) ) );
}
while ( !eol && ptr < len ) {
switch (c) {
case -1:
case '\n':
eol = true;
break;
case '\r':
eol = true;
long cur = getFilePointer();
if ((read()) != '\n') {
seek(cur);
}
break;
default:
input[ptr++] = (byte)c;
break;
}
// break loop? do it before we read() again
if( eol || len <= ptr ) {
break;
}
else {
c = read();
}
}
if (ptr >= len) {
eol = false;
while (!eol) {
switch (c = read()) {
case -1:
case '\n':
eol = true;
break;
case '\r':
eol = true;
long cur = getFilePointer();
if ((read()) != '\n') {
seek(cur);
}
break;
}
}
}
if ((c == -1) && (ptr == 0)) {
return false;
}
if (ptr + 2 <= len) {
input[ptr++] = (byte)' ';
input[ptr] = (byte)'X';
}
return true;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
public static void exportToXML(HashMap<String, String> names, OutputStream out, String encoding, boolean onlyASCII) throws IOException {
String jenc = IanaEncodings.getJavaEncoding(encoding);
Writer wrt = new BufferedWriter(new OutputStreamWriter(out, jenc));
exportToXML(names, wrt, encoding, onlyASCII);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
public static void exportToXML(HashMap<String, String> names, Writer wrt, String encoding, boolean onlyASCII) throws IOException {
wrt.write("<?xml version=\"1.0\" encoding=\"");
wrt.write(XMLUtil.escapeXML(encoding, onlyASCII));
wrt.write("\"?>\n<Destination>\n");
for (Map.Entry<String, String> entry: names.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
wrt.write(" <Name Page=\"");
wrt.write(XMLUtil.escapeXML(value, onlyASCII));
wrt.write("\">");
wrt.write(XMLUtil.escapeXML(escapeBinaryString(key), onlyASCII));
wrt.write("</Name>\n");
}
wrt.write("</Destination>\n");
wrt.flush();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
public static HashMap<String, String> importFromXML(InputStream in) throws IOException {
SimpleNamedDestination names = new SimpleNamedDestination();
SimpleXMLParser.parse(names, in);
return names.xmlNames;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
public static HashMap<String, String> importFromXML(Reader in) throws IOException {
SimpleNamedDestination names = new SimpleNamedDestination();
SimpleXMLParser.parse(names, in);
return names.xmlNames;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
public static PdfDictionary outputNamedDestinationAsStrings(HashMap<String, String> names, PdfWriter writer) throws IOException {
HashMap<String, PdfObject> n2 = new HashMap<String, PdfObject>(names.size());
for (Map.Entry<String, String> entry: names.entrySet()) {
try {
String value = entry.getValue();
PdfArray ar = createDestinationArray(value, writer);
n2.put(entry.getKey(), writer.addToBody(ar).getIndirectReference());
}
catch (Exception e) {
}
}
return PdfNameTree.writeTree(n2, writer);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
public void writeLength() throws IOException {
if (inputStream == null)
throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("writelength.can.only.be.called.in.a.contructed.pdfstream.inputstream.pdfwriter"));
if (inputStreamLength == -1)
throw new IOException(MessageLocalization.getComposedMessage("writelength.can.only.be.called.after.output.of.the.stream.body"));
writer.addToBody(new PdfNumber(inputStreamLength), ref, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
protected void superToPdf(PdfWriter writer, OutputStream os) throws IOException {
super.toPdf(writer, os);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {
if (inputStream != null && compressed)
put(PdfName.FILTER, PdfName.FLATEDECODE);
PdfEncryption crypto = null;
if (writer != null)
crypto = writer.getEncryption();
if (crypto != null) {
PdfObject filter = get(PdfName.FILTER);
if (filter != null) {
if (PdfName.CRYPT.equals(filter))
crypto = null;
else if (filter.isArray()) {
PdfArray a = (PdfArray)filter;
if (!a.isEmpty() && PdfName.CRYPT.equals(a.getPdfObject(0)))
crypto = null;
}
}
}
PdfObject nn = get(PdfName.LENGTH);
if (crypto != null && nn != null && nn.isNumber()) {
int sz = ((PdfNumber)nn).intValue();
put(PdfName.LENGTH, new PdfNumber(crypto.calculateStreamSize(sz)));
superToPdf(writer, os);
put(PdfName.LENGTH, nn);
}
else
superToPdf(writer, os);
os.write(STARTSTREAM);
if (inputStream != null) {
rawLength = 0;
DeflaterOutputStream def = null;
OutputStreamCounter osc = new OutputStreamCounter(os);
OutputStreamEncryption ose = null;
OutputStream fout = osc;
if (crypto != null && !crypto.isEmbeddedFilesOnly())
fout = ose = crypto.getEncryptionStream(fout);
Deflater deflater = null;
if (compressed) {
deflater = new Deflater(compressionLevel);
fout = def = new DeflaterOutputStream(fout, deflater, 0x8000);
}
byte buf[] = new byte[4192];
while (true) {
int n = inputStream.read(buf);
if (n <= 0)
break;
fout.write(buf, 0, n);
rawLength += n;
}
if (def != null) {
def.finish();
deflater.end();
}
if (ose != null)
ose.finish();
inputStreamLength = (int)osc.getCounter();
}
else {
if (crypto != null && !crypto.isEmbeddedFilesOnly()) {
byte b[];
if (streamBytes != null) {
b = crypto.encryptByteArray(streamBytes.toByteArray());
}
else {
b = crypto.encryptByteArray(bytes);
}
os.write(b);
}
else {
if (streamBytes != null)
streamBytes.writeTo(os);
else
os.write(bytes);
}
}
os.write(ENDSTREAM);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
public void writeContent(OutputStream os) throws IOException {
if (streamBytes != null)
streamBytes.writeTo(os);
else if (bytes != null)
os.write(bytes);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
PdfIndirectReference writePageTree() throws IOException {
if (pages.isEmpty())
throw new IOException(MessageLocalization.getComposedMessage("the.document.has.no.pages"));
int leaf = 1;
ArrayList<PdfIndirectReference> tParents = parents;
ArrayList<PdfIndirectReference> tPages = pages;
ArrayList<PdfIndirectReference> nextParents = new ArrayList<PdfIndirectReference>();
while (true) {
leaf *= leafSize;
int stdCount = leafSize;
int rightCount = tPages.size() % leafSize;
if (rightCount == 0)
rightCount = leafSize;
for (int p = 0; p < tParents.size(); ++p) {
int count;
int thisLeaf = leaf;
if (p == tParents.size() - 1) {
count = rightCount;
thisLeaf = pages.size() % leaf;
if (thisLeaf == 0)
thisLeaf = leaf;
}
else
count = stdCount;
PdfDictionary top = new PdfDictionary(PdfName.PAGES);
top.put(PdfName.COUNT, new PdfNumber(thisLeaf));
PdfArray kids = new PdfArray();
ArrayList<PdfObject> internal = kids.getArrayList();
internal.addAll(tPages.subList(p * stdCount, p * stdCount + count));
top.put(PdfName.KIDS, kids);
if (tParents.size() > 1) {
if (p % leafSize == 0)
nextParents.add(writer.getPdfIndirectReference());
top.put(PdfName.PARENT, nextParents.get(p / leafSize));
}
writer.addToBody(top, tParents.get(p));
}
if (tParents.size() == 1) {
topParent = tParents.get(0);
return topParent;
}
tPages = tParents;
tParents = nextParents;
nextParents = new ArrayList<PdfIndirectReference>();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAction.java
public static PdfAction rendition(String file, PdfFileSpecification fs, String mimeType, PdfIndirectReference ref) throws IOException {
PdfAction js = new PdfAction();
js.put(PdfName.S, PdfName.RENDITION);
js.put(PdfName.R, new PdfRendition(file, fs, mimeType));
js.put(new PdfName("OP"), new PdfNumber(0));
js.put(new PdfName("AN"), ref);
return js;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void toPdf(final OutputStream os) throws IOException {
StringBuffer off = new StringBuffer("0000000000").append(offset);
off.delete(0, off.length() - 10);
StringBuffer gen = new StringBuffer("00000").append(generation);
gen.delete(0, gen.length() - 5);
off.append(' ').append(gen).append(generation == GENERATION_MAX ? " f \n" : " n \n");
os.write(getISOBytes(off.toString()));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void toPdf(int midSize, final OutputStream os) throws IOException {
os.write((byte)type);
while (--midSize >= 0)
os.write((byte)(offset >>> 8 * midSize & 0xff));
os.write((byte)(generation >>> 8 & 0xff));
os.write((byte)(generation & 0xff));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected PdfWriter.PdfBody.PdfCrossReference addToObjStm(final PdfObject obj, final int nObj) throws IOException {
if (numObj >= OBJSINSTREAM)
flushObjStm();
if (index == null) {
index = new ByteBuffer();
streamObjects = new ByteBuffer();
currentObjNum = getIndirectReferenceNumber();
numObj = 0;
}
int p = streamObjects.size();
int idx = numObj++;
PdfEncryption enc = writer.crypto;
writer.crypto = null;
obj.toPdf(writer, streamObjects);
writer.crypto = enc;
streamObjects.append(' ');
index.append(nObj).append(' ').append(p).append(' ');
return new PdfWriter.PdfBody.PdfCrossReference(2, nObj, currentObjNum, idx);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void flushObjStm() throws IOException {
if (numObj == 0)
return;
int first = index.size();
index.append(streamObjects);
PdfStream stream = new PdfStream(index.toByteArray());
stream.flateCompress(writer.getCompressionLevel());
stream.put(PdfName.TYPE, PdfName.OBJSTM);
stream.put(PdfName.N, new PdfNumber(numObj));
stream.put(PdfName.FIRST, new PdfNumber(first));
add(stream, currentObjNum);
index = null;
streamObjects = null;
numObj = 0;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectObject add(final PdfObject object) throws IOException {
return add(object, getIndirectReferenceNumber());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectObject add(final PdfObject object, final boolean inObjStm) throws IOException {
return add(object, getIndirectReferenceNumber(), inObjStm);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectObject add(final PdfObject object, final PdfIndirectReference ref) throws IOException {
return add(object, ref.getNumber());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectObject add(final PdfObject object, final PdfIndirectReference ref, final boolean inObjStm) throws IOException {
return add(object, ref.getNumber(), inObjStm);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectObject add(final PdfObject object, final int refNumber) throws IOException {
return add(object, refNumber, true); // to false
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected PdfIndirectObject add(final PdfObject object, final int refNumber, final boolean inObjStm) throws IOException {
if (inObjStm && object.canBeInObjStm() && writer.isFullCompression()) {
PdfCrossReference pxref = addToObjStm(object, refNumber);
PdfIndirectObject indirect = new PdfIndirectObject(refNumber, object, writer);
if (!xrefs.add(pxref)) {
xrefs.remove(pxref);
xrefs.add(pxref);
}
return indirect;
}
else {
PdfIndirectObject indirect = new PdfIndirectObject(refNumber, object, writer);
write(indirect, refNumber);
return indirect;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected void write(final PdfIndirectObject indirect, final int refNumber) throws IOException {
PdfCrossReference pxref = new PdfCrossReference(refNumber, position);
if (!xrefs.add(pxref)) {
xrefs.remove(pxref);
xrefs.add(pxref);
}
indirect.writeTo(writer.getOs());
position = writer.getOs().getCounter();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void writeCrossReferenceTable(final OutputStream os, final PdfIndirectReference root, final PdfIndirectReference info, final PdfIndirectReference encryption, final PdfObject fileID, final long prevxref) throws IOException {
int refNumber = 0;
if (writer.isFullCompression()) {
flushObjStm();
refNumber = getIndirectReferenceNumber();
xrefs.add(new PdfCrossReference(refNumber, position));
}
PdfCrossReference entry = xrefs.first();
int first = entry.getRefnum();
int len = 0;
ArrayList<Integer> sections = new ArrayList<Integer>();
for (PdfCrossReference pdfCrossReference : xrefs) {
entry = pdfCrossReference;
if (first + len == entry.getRefnum())
++len;
else {
sections.add(Integer.valueOf(first));
sections.add(Integer.valueOf(len));
first = entry.getRefnum();
len = 1;
}
}
sections.add(Integer.valueOf(first));
sections.add(Integer.valueOf(len));
if (writer.isFullCompression()) {
int mid = 5;
long mask = 0xff00000000L;
for (; mid > 1; --mid) {
if ((mask & position) != 0)
break;
mask >>>= 8;
}
ByteBuffer buf = new ByteBuffer();
for (Object element : xrefs) {
entry = (PdfCrossReference) element;
entry.toPdf(mid, buf);
}
PdfStream xr = new PdfStream(buf.toByteArray());
buf = null;
xr.flateCompress(writer.getCompressionLevel());
xr.put(PdfName.SIZE, new PdfNumber(size()));
xr.put(PdfName.ROOT, root);
if (info != null) {
xr.put(PdfName.INFO, info);
}
if (encryption != null)
xr.put(PdfName.ENCRYPT, encryption);
if (fileID != null)
xr.put(PdfName.ID, fileID);
xr.put(PdfName.W, new PdfArray(new int[]{1, mid, 2}));
xr.put(PdfName.TYPE, PdfName.XREF);
PdfArray idx = new PdfArray();
for (int k = 0; k < sections.size(); ++k)
idx.add(new PdfNumber(sections.get(k).intValue()));
xr.put(PdfName.INDEX, idx);
if (prevxref > 0)
xr.put(PdfName.PREV, new PdfNumber(prevxref));
PdfEncryption enc = writer.crypto;
writer.crypto = null;
PdfIndirectObject indirect = new PdfIndirectObject(refNumber, xr, writer);
indirect.writeTo(writer.getOs());
writer.crypto = enc;
}
else {
os.write(getISOBytes("xref\n"));
Iterator<PdfCrossReference> i = xrefs.iterator();
for (int k = 0; k < sections.size(); k += 2) {
first = sections.get(k).intValue();
len = sections.get(k + 1).intValue();
os.write(getISOBytes(String.valueOf(first)));
os.write(getISOBytes(" "));
os.write(getISOBytes(String.valueOf(len)));
os.write('\n');
while (len-- > 0) {
entry = i.next();
entry.toPdf(os);
}
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Override
public void toPdf(final PdfWriter writer, final OutputStream os) throws IOException {
os.write(getISOBytes("trailer\n"));
super.toPdf(null, os);
os.write('\n');
writeKeyInfo(os);
os.write(getISOBytes("startxref\n"));
os.write(getISOBytes(String.valueOf(offset)));
os.write(getISOBytes("\n%%EOF\n"));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
void addLocalDestinations(final TreeMap<String, PdfDocument.Destination> desto) throws IOException {
for (Map.Entry<String, PdfDocument.Destination> entry : desto.entrySet()) {
String name = entry.getKey();
PdfDocument.Destination dest = entry.getValue();
PdfDestination destination = dest.destination;
if (dest.reference == null)
dest.reference = getPdfIndirectReference();
if (destination == null)
addToBody(new PdfString("invalid_" + name), dest.reference);
else
addToBody(destination, dest.reference);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfIndirectObject addToBody(final PdfObject object) throws IOException {
PdfIndirectObject iobj = body.add(object);
return iobj;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfIndirectObject addToBody(final PdfObject object, final boolean inObjStm) throws IOException {
PdfIndirectObject iobj = body.add(object, inObjStm);
return iobj;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfIndirectObject addToBody(final PdfObject object, final PdfIndirectReference ref) throws IOException {
PdfIndirectObject iobj = body.add(object, ref);
return iobj;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfIndirectObject addToBody(final PdfObject object, final PdfIndirectReference ref, final boolean inObjStm) throws IOException {
PdfIndirectObject iobj = body.add(object, ref, inObjStm);
return iobj;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfIndirectObject addToBody(final PdfObject object, final int refNumber) throws IOException {
PdfIndirectObject iobj = body.add(object, refNumber);
return iobj;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfIndirectObject addToBody(final PdfObject object, final int refNumber, final boolean inObjStm) throws IOException {
PdfIndirectObject iobj = body.add(object, refNumber, inObjStm);
return iobj;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected void addXFormsToBody() throws IOException {
for (Object objs[] : formXObjects.values()) {
PdfTemplate template = (PdfTemplate)objs[1];
if (template != null && template.getIndirectReference() instanceof PRIndirectReference)
continue;
if (template != null && template.getType() == PdfTemplate.TYPE_TEMPLATE) {
addToBody(template.getFormXObject(compressionLevel), template.getIndirectReference());
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected void addSharedObjectsToBody() throws IOException {
// [F3] add the fonts
for (FontDetails details : documentFonts.values()) {
details.writeFont(this);
}
// [F4] add the form XObjects
addXFormsToBody();
// [F5] add all the dependencies in the imported pages
for (PdfReaderInstance element : readerInstances.values()) {
currentPdfReaderInstance= element;
currentPdfReaderInstance.writeAllPages();
}
currentPdfReaderInstance = null;
// [F6] add the spotcolors
for (ColorDetails color : documentColors.values()) {
addToBody(color.getSpotColor(this), color.getIndirectReference());
}
// [F7] add the pattern
for (PdfPatternPainter pat : documentPatterns.keySet()) {
addToBody(pat.getPattern(compressionLevel), pat.getIndirectReference());
}
// [F8] add the shading patterns
for (PdfShadingPattern shadingPattern : documentShadingPatterns) {
shadingPattern.addToBody();
}
// [F9] add the shadings
for (PdfShading shading : documentShadings) {
shading.addToBody();
}
// [F10] add the extgstate
for (Map.Entry<PdfDictionary, PdfObject[]>entry : documentExtGState.entrySet()) {
PdfDictionary gstate = entry.getKey();
PdfObject obj[] = entry.getValue();
addToBody(gstate, (PdfIndirectReference)obj[1]);
}
// [F11] add the properties
for (Map.Entry<Object, PdfObject[]>entry : documentProperties.entrySet()) {
Object prop = entry.getKey();
PdfObject[] obj = entry.getValue();
if (prop instanceof PdfLayerMembership){
PdfLayerMembership layer = (PdfLayerMembership)prop;
addToBody(layer.getPdfObject(), layer.getRef());
}
else if (prop instanceof PdfDictionary && !(prop instanceof PdfLayer)){
addToBody((PdfDictionary)prop, (PdfIndirectReference)obj[1]);
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected void writeOutlines(final PdfDictionary catalog, final boolean namedAsNames) throws IOException {
if (newBookmarks == null || newBookmarks.isEmpty())
return;
PdfDictionary top = new PdfDictionary();
PdfIndirectReference topRef = getPdfIndirectReference();
Object kids[] = SimpleBookmark.iterateOutlines(this, topRef, newBookmarks, namedAsNames);
top.put(PdfName.FIRST, (PdfIndirectReference)kids[0]);
top.put(PdfName.LAST, (PdfIndirectReference)kids[1]);
top.put(PdfName.COUNT, new PdfNumber(((Integer)kids[2]).intValue()));
addToBody(top, topRef);
catalog.put(PdfName.OUTLINES, topRef);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void addFileAttachment(final String description, final byte fileStore[], final String file, final String fileDisplay) throws IOException {
addFileAttachment(description, PdfFileSpecification.fileEmbedded(this, file, fileDisplay, fileStore));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void addFileAttachment(final String description, final PdfFileSpecification fs) throws IOException {
pdf.addFileAttachment(description, fs);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void addFileAttachment(final PdfFileSpecification fs) throws IOException {
addFileAttachment(null, fs);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setPageXmpMetadata(final byte[] xmpMetadata) throws IOException {
pdf.setXmpMetadata(xmpMetadata);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setOutputIntents(final String outputConditionIdentifier, final String outputCondition, final String registryName, final String info, final ICC_Profile colorProfile) throws IOException {
getExtraCatalog();
PdfDictionary out = new PdfDictionary(PdfName.OUTPUTINTENT);
if (outputCondition != null)
out.put(PdfName.OUTPUTCONDITION, new PdfString(outputCondition, PdfObject.TEXT_UNICODE));
if (outputConditionIdentifier != null)
out.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString(outputConditionIdentifier, PdfObject.TEXT_UNICODE));
if (registryName != null)
out.put(PdfName.REGISTRYNAME, new PdfString(registryName, PdfObject.TEXT_UNICODE));
if (info != null)
out.put(PdfName.INFO, new PdfString(info, PdfObject.TEXT_UNICODE));
if (colorProfile != null) {
PdfStream stream = new PdfICCBased(colorProfile, compressionLevel);
out.put(PdfName.DESTOUTPUTPROFILE, addToBody(stream).getIndirectReference());
}
out.put(PdfName.S, PdfName.GTS_PDFX);
extraCatalog.put(PdfName.OUTPUTINTENTS, new PdfArray(out));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setOutputIntents(final String outputConditionIdentifier, final String outputCondition, final String registryName, final String info, final byte destOutputProfile[]) throws IOException {
ICC_Profile colorProfile = destOutputProfile == null ? null : ICC_Profile.getInstance(destOutputProfile);
setOutputIntents(outputConditionIdentifier, outputCondition, registryName, info, colorProfile);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public boolean setOutputIntents(final PdfReader reader, final boolean checkExistence) throws IOException {
PdfDictionary catalog = reader.getCatalog();
PdfArray outs = catalog.getAsArray(PdfName.OUTPUTINTENTS);
if (outs == null)
return false;
if (outs.isEmpty())
return false;
PdfDictionary out = outs.getAsDict(0);
PdfObject obj = PdfReader.getPdfObject(out.get(PdfName.S));
if (obj == null || !PdfName.GTS_PDFX.equals(obj))
return false;
if (checkExistence)
return true;
PRStream stream = (PRStream)PdfReader.getPdfObject(out.get(PdfName.DESTOUTPUTPROFILE));
byte destProfile[] = null;
if (stream != null) {
destProfile = PdfReader.getStreamBytes(stream);
}
setOutputIntents(getNameString(out, PdfName.OUTPUTCONDITIONIDENTIFIER), getNameString(out, PdfName.OUTPUTCONDITION),
getNameString(out, PdfName.REGISTRYNAME), getNameString(out, PdfName.INFO), destProfile);
return true;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void releaseTemplate(final PdfTemplate tp) throws IOException {
PdfIndirectReference ref = tp.getIndirectReference();
Object[] objs = formXObjects.get(ref);
if (objs == null || objs[1] == null)
return;
PdfTemplate template = (PdfTemplate)objs[1];
if (template.getIndirectReference() instanceof PRIndirectReference)
return;
if (template.getType() == PdfTemplate.TYPE_TEMPLATE) {
addToBody(template.getFormXObject(compressionLevel), template.getIndirectReference());
objs[1] = null;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void freeReader(final PdfReader reader) throws IOException {
currentPdfReaderInstance = readerInstances.get(reader);
if (currentPdfReaderInstance == null)
return;
currentPdfReaderInstance.writeAllPages();
currentPdfReaderInstance = null;
readerInstances.remove(reader);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected void flushTaggedObjects() throws IOException {}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected static void writeKeyInfo(OutputStream os) throws IOException {
Version version = Version.getInstance();
String k = version.getKey();
if (k == null) {
k = "iText";
}
os.write(getISOBytes(String.format("%%%s-%s\n", k, version.getRelease())));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected XmpWriter getXmpWriter(ByteArrayOutputStream baos, PdfDocument.PdfInfo info) throws IOException {
if (xmpWriter == null)
xmpWriter = new XmpWriter(baos, info);
return xmpWriter;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyForms.java
public void addDocument(PdfReader reader) throws DocumentException, IOException {
fc.addDocument(reader);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyForms.java
public void addDocument(PdfReader reader, List<Integer> pagesToKeep) throws DocumentException, IOException {
fc.addDocument(reader, pagesToKeep);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyForms.java
public void addDocument(PdfReader reader, String ranges) throws DocumentException, IOException {
fc.addDocument(reader, SequenceList.expand(ranges, reader.getNumberOfPages()));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
void fillTables() throws DocumentException, IOException {
int table_location[];
table_location = tables.get("head");
if (table_location == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "head", fileName + style));
rf.seek(table_location[0] + 16);
head.flags = rf.readUnsignedShort();
head.unitsPerEm = rf.readUnsignedShort();
rf.skipBytes(16);
head.xMin = rf.readShort();
head.yMin = rf.readShort();
head.xMax = rf.readShort();
head.yMax = rf.readShort();
head.macStyle = rf.readUnsignedShort();
table_location = tables.get("hhea");
if (table_location == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "hhea", fileName + style));
rf.seek(table_location[0] + 4);
hhea.Ascender = rf.readShort();
hhea.Descender = rf.readShort();
hhea.LineGap = rf.readShort();
hhea.advanceWidthMax = rf.readUnsignedShort();
hhea.minLeftSideBearing = rf.readShort();
hhea.minRightSideBearing = rf.readShort();
hhea.xMaxExtent = rf.readShort();
hhea.caretSlopeRise = rf.readShort();
hhea.caretSlopeRun = rf.readShort();
rf.skipBytes(12);
hhea.numberOfHMetrics = rf.readUnsignedShort();
table_location = tables.get("OS/2");
if (table_location == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "OS/2", fileName + style));
rf.seek(table_location[0]);
int version = rf.readUnsignedShort();
os_2.xAvgCharWidth = rf.readShort();
os_2.usWeightClass = rf.readUnsignedShort();
os_2.usWidthClass = rf.readUnsignedShort();
os_2.fsType = rf.readShort();
os_2.ySubscriptXSize = rf.readShort();
os_2.ySubscriptYSize = rf.readShort();
os_2.ySubscriptXOffset = rf.readShort();
os_2.ySubscriptYOffset = rf.readShort();
os_2.ySuperscriptXSize = rf.readShort();
os_2.ySuperscriptYSize = rf.readShort();
os_2.ySuperscriptXOffset = rf.readShort();
os_2.ySuperscriptYOffset = rf.readShort();
os_2.yStrikeoutSize = rf.readShort();
os_2.yStrikeoutPosition = rf.readShort();
os_2.sFamilyClass = rf.readShort();
rf.readFully(os_2.panose);
rf.skipBytes(16);
rf.readFully(os_2.achVendID);
os_2.fsSelection = rf.readUnsignedShort();
os_2.usFirstCharIndex = rf.readUnsignedShort();
os_2.usLastCharIndex = rf.readUnsignedShort();
os_2.sTypoAscender = rf.readShort();
os_2.sTypoDescender = rf.readShort();
if (os_2.sTypoDescender > 0)
os_2.sTypoDescender = (short)-os_2.sTypoDescender;
os_2.sTypoLineGap = rf.readShort();
os_2.usWinAscent = rf.readUnsignedShort();
os_2.usWinDescent = rf.readUnsignedShort();
os_2.ulCodePageRange1 = 0;
os_2.ulCodePageRange2 = 0;
if (version > 0) {
os_2.ulCodePageRange1 = rf.readInt();
os_2.ulCodePageRange2 = rf.readInt();
}
if (version > 1) {
rf.skipBytes(2);
os_2.sCapHeight = rf.readShort();
}
else
os_2.sCapHeight = (int)(0.7 * head.unitsPerEm);
table_location = tables.get("post");
if (table_location == null) {
italicAngle = -Math.atan2(hhea.caretSlopeRun, hhea.caretSlopeRise) * 180 / Math.PI;
return;
}
rf.seek(table_location[0] + 4);
short mantissa = rf.readShort();
int fraction = rf.readUnsignedShort();
italicAngle = mantissa + fraction / 16384.0d;
underlinePosition = rf.readShort();
underlineThickness = rf.readShort();
isFixedPitch = rf.readInt() != 0;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
String getBaseFont() throws DocumentException, IOException {
int table_location[];
table_location = tables.get("name");
if (table_location == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "name", fileName + style));
rf.seek(table_location[0] + 2);
int numRecords = rf.readUnsignedShort();
int startOfStorage = rf.readUnsignedShort();
for (int k = 0; k < numRecords; ++k) {
int platformID = rf.readUnsignedShort();
int platformEncodingID = rf.readUnsignedShort();
int languageID = rf.readUnsignedShort();
int nameID = rf.readUnsignedShort();
int length = rf.readUnsignedShort();
int offset = rf.readUnsignedShort();
if (nameID == 6) {
rf.seek(table_location[0] + startOfStorage + offset);
if (platformID == 0 || platformID == 3)
return readUnicodeString(length);
else
return readStandardString(length);
}
}
File file = new File(fileName);
return file.getName().replace(' ', '-');
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
String[][] getNames(int id) throws DocumentException, IOException {
int table_location[];
table_location = tables.get("name");
if (table_location == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "name", fileName + style));
rf.seek(table_location[0] + 2);
int numRecords = rf.readUnsignedShort();
int startOfStorage = rf.readUnsignedShort();
ArrayList<String[]> names = new ArrayList<String[]>();
for (int k = 0; k < numRecords; ++k) {
int platformID = rf.readUnsignedShort();
int platformEncodingID = rf.readUnsignedShort();
int languageID = rf.readUnsignedShort();
int nameID = rf.readUnsignedShort();
int length = rf.readUnsignedShort();
int offset = rf.readUnsignedShort();
if (nameID == id) {
int pos = (int)rf.getFilePointer();
rf.seek(table_location[0] + startOfStorage + offset);
String name;
if (platformID == 0 || platformID == 3 || platformID == 2 && platformEncodingID == 1){
name = readUnicodeString(length);
}
else {
name = readStandardString(length);
}
names.add(new String[]{String.valueOf(platformID),
String.valueOf(platformEncodingID), String.valueOf(languageID), name});
rf.seek(pos);
}
}
String thisName[][] = new String[names.size()][];
for (int k = 0; k < names.size(); ++k)
thisName[k] = names.get(k);
return thisName;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
String[][] getAllNames() throws DocumentException, IOException {
int table_location[];
table_location = tables.get("name");
if (table_location == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "name", fileName + style));
rf.seek(table_location[0] + 2);
int numRecords = rf.readUnsignedShort();
int startOfStorage = rf.readUnsignedShort();
ArrayList<String[]> names = new ArrayList<String[]>();
for (int k = 0; k < numRecords; ++k) {
int platformID = rf.readUnsignedShort();
int platformEncodingID = rf.readUnsignedShort();
int languageID = rf.readUnsignedShort();
int nameID = rf.readUnsignedShort();
int length = rf.readUnsignedShort();
int offset = rf.readUnsignedShort();
int pos = (int)rf.getFilePointer();
rf.seek(table_location[0] + startOfStorage + offset);
String name;
if (platformID == 0 || platformID == 3 || platformID == 2 && platformEncodingID == 1){
name = readUnicodeString(length);
}
else {
name = readStandardString(length);
}
names.add(new String[]{String.valueOf(nameID), String.valueOf(platformID),
String.valueOf(platformEncodingID), String.valueOf(languageID), name});
rf.seek(pos);
}
String thisName[][] = new String[names.size()][];
for (int k = 0; k < names.size(); ++k)
thisName[k] = names.get(k);
return thisName;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
void process(byte ttfAfm[], boolean preload) throws DocumentException, IOException {
tables = new HashMap<String, int[]>();
if (ttfAfm == null)
rf = new RandomAccessFileOrArray(fileName, preload, Document.plainRandomAccess);
else
rf = new RandomAccessFileOrArray(ttfAfm);
try {
if (ttcIndex.length() > 0) {
int dirIdx = Integer.parseInt(ttcIndex);
if (dirIdx < 0)
throw new DocumentException(MessageLocalization.getComposedMessage("the.font.index.for.1.must.be.positive", fileName));
String mainTag = readStandardString(4);
if (!mainTag.equals("ttcf"))
throw new DocumentException(MessageLocalization.getComposedMessage("1.is.not.a.valid.ttc.file", fileName));
rf.skipBytes(4);
int dirCount = rf.readInt();
if (dirIdx >= dirCount)
throw new DocumentException(MessageLocalization.getComposedMessage("the.font.index.for.1.must.be.between.0.and.2.it.was.3", fileName, String.valueOf(dirCount - 1), String.valueOf(dirIdx)));
rf.skipBytes(dirIdx * 4);
directoryOffset = rf.readInt();
}
rf.seek(directoryOffset);
int ttId = rf.readInt();
if (ttId != 0x00010000 && ttId != 0x4F54544F)
throw new DocumentException(MessageLocalization.getComposedMessage("1.is.not.a.valid.ttf.or.otf.file", fileName));
int num_tables = rf.readUnsignedShort();
rf.skipBytes(6);
for (int k = 0; k < num_tables; ++k) {
String tag = readStandardString(4);
rf.skipBytes(4);
int table_location[] = new int[2];
table_location[0] = rf.readInt();
table_location[1] = rf.readInt();
tables.put(tag, table_location);
}
checkCff();
fontName = getBaseFont();
fullName = getNames(4); //full name
familyName = getNames(1); //family name
allNameEntries = getAllNames();
if (!justNames) {
fillTables();
readGlyphWidths();
readCMaps();
readKerning();
readBbox();
}
}
finally {
//TODO: For embedded fonts, the underlying data source for the font will be left open until this TrueTypeFont object is collected by the Garbage Collector. That may not be optimal.
if (!embedded){
rf.close();
rf = null;
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
protected String readStandardString(int length) throws IOException {
return rf.readString(length, WINANSI);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
protected String readUnicodeString(int length) throws IOException {
StringBuffer buf = new StringBuffer();
length /= 2;
for (int k = 0; k < length; ++k) {
buf.append(rf.readChar());
}
return buf.toString();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
protected void readGlyphWidths() throws DocumentException, IOException {
int table_location[];
table_location = tables.get("hmtx");
if (table_location == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "hmtx", fileName + style));
rf.seek(table_location[0]);
glyphWidthsByIndex = new int[hhea.numberOfHMetrics];
for (int k = 0; k < hhea.numberOfHMetrics; ++k) {
glyphWidthsByIndex[k] = rf.readUnsignedShort() * 1000 / head.unitsPerEm;
@SuppressWarnings("unused")
int leftSideBearing = rf.readShort() * 1000 / head.unitsPerEm;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
private void readBbox() throws DocumentException, IOException {
int tableLocation[];
tableLocation = tables.get("head");
if (tableLocation == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "head", fileName + style));
rf.seek(tableLocation[0] + TrueTypeFontSubSet.HEAD_LOCA_FORMAT_OFFSET);
boolean locaShortTable = rf.readUnsignedShort() == 0;
tableLocation = tables.get("loca");
if (tableLocation == null)
return;
rf.seek(tableLocation[0]);
int locaTable[];
if (locaShortTable) {
int entries = tableLocation[1] / 2;
locaTable = new int[entries];
for (int k = 0; k < entries; ++k)
locaTable[k] = rf.readUnsignedShort() * 2;
}
else {
int entries = tableLocation[1] / 4;
locaTable = new int[entries];
for (int k = 0; k < entries; ++k)
locaTable[k] = rf.readInt();
}
tableLocation = tables.get("glyf");
if (tableLocation == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "glyf", fileName + style));
int tableGlyphOffset = tableLocation[0];
bboxes = new int[locaTable.length - 1][];
for (int glyph = 0; glyph < locaTable.length - 1; ++glyph) {
int start = locaTable[glyph];
if (start != locaTable[glyph + 1]) {
rf.seek(tableGlyphOffset + start + 2);
bboxes[glyph] = new int[]{
rf.readShort() * 1000 / head.unitsPerEm,
rf.readShort() * 1000 / head.unitsPerEm,
rf.readShort() * 1000 / head.unitsPerEm,
rf.readShort() * 1000 / head.unitsPerEm};
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
void readCMaps() throws DocumentException, IOException {
int table_location[];
table_location = tables.get("cmap");
if (table_location == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "cmap", fileName + style));
rf.seek(table_location[0]);
rf.skipBytes(2);
int num_tables = rf.readUnsignedShort();
fontSpecific = false;
int map10 = 0;
int map31 = 0;
int map30 = 0;
int mapExt = 0;
for (int k = 0; k < num_tables; ++k) {
int platId = rf.readUnsignedShort();
int platSpecId = rf.readUnsignedShort();
int offset = rf.readInt();
if (platId == 3 && platSpecId == 0) {
fontSpecific = true;
map30 = offset;
}
else if (platId == 3 && platSpecId == 1) {
map31 = offset;
}
else if (platId == 3 && platSpecId == 10) {
mapExt = offset;
}
if (platId == 1 && platSpecId == 0) {
map10 = offset;
}
}
if (map10 > 0) {
rf.seek(table_location[0] + map10);
int format = rf.readUnsignedShort();
switch (format) {
case 0:
cmap10 = readFormat0();
break;
case 4:
cmap10 = readFormat4();
break;
case 6:
cmap10 = readFormat6();
break;
}
}
if (map31 > 0) {
rf.seek(table_location[0] + map31);
int format = rf.readUnsignedShort();
if (format == 4) {
cmap31 = readFormat4();
}
}
if (map30 > 0) {
rf.seek(table_location[0] + map30);
int format = rf.readUnsignedShort();
if (format == 4) {
cmap10 = readFormat4();
}
}
if (mapExt > 0) {
rf.seek(table_location[0] + mapExt);
int format = rf.readUnsignedShort();
switch (format) {
case 0:
cmapExt = readFormat0();
break;
case 4:
cmapExt = readFormat4();
break;
case 6:
cmapExt = readFormat6();
break;
case 12:
cmapExt = readFormat12();
break;
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
HashMap<Integer, int[]> readFormat12() throws IOException {
HashMap<Integer, int[]> h = new HashMap<Integer, int[]>();
rf.skipBytes(2);
int table_lenght = rf.readInt();
rf.skipBytes(4);
int nGroups = rf.readInt();
for (int k = 0; k < nGroups; k++) {
int startCharCode = rf.readInt();
int endCharCode = rf.readInt();
int startGlyphID = rf.readInt();
for (int i = startCharCode; i <= endCharCode; i++) {
int[] r = new int[2];
r[0] = startGlyphID;
r[1] = getGlyphWidth(r[0]);
h.put(Integer.valueOf(i), r);
startGlyphID++;
}
}
return h;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
HashMap<Integer, int[]> readFormat0() throws IOException {
HashMap<Integer, int[]> h = new HashMap<Integer, int[]>();
rf.skipBytes(4);
for (int k = 0; k < 256; ++k) {
int r[] = new int[2];
r[0] = rf.readUnsignedByte();
r[1] = getGlyphWidth(r[0]);
h.put(Integer.valueOf(k), r);
}
return h;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
HashMap<Integer, int[]> readFormat4() throws IOException {
HashMap<Integer, int[]> h = new HashMap<Integer, int[]>();
int table_lenght = rf.readUnsignedShort();
rf.skipBytes(2);
int segCount = rf.readUnsignedShort() / 2;
rf.skipBytes(6);
int endCount[] = new int[segCount];
for (int k = 0; k < segCount; ++k) {
endCount[k] = rf.readUnsignedShort();
}
rf.skipBytes(2);
int startCount[] = new int[segCount];
for (int k = 0; k < segCount; ++k) {
startCount[k] = rf.readUnsignedShort();
}
int idDelta[] = new int[segCount];
for (int k = 0; k < segCount; ++k) {
idDelta[k] = rf.readUnsignedShort();
}
int idRO[] = new int[segCount];
for (int k = 0; k < segCount; ++k) {
idRO[k] = rf.readUnsignedShort();
}
int glyphId[] = new int[table_lenght / 2 - 8 - segCount * 4];
for (int k = 0; k < glyphId.length; ++k) {
glyphId[k] = rf.readUnsignedShort();
}
for (int k = 0; k < segCount; ++k) {
int glyph;
for (int j = startCount[k]; j <= endCount[k] && j != 0xFFFF; ++j) {
if (idRO[k] == 0) {
glyph = j + idDelta[k] & 0xFFFF;
}
else {
int idx = k + idRO[k] / 2 - segCount + j - startCount[k];
if (idx >= glyphId.length)
continue;
glyph = glyphId[idx] + idDelta[k] & 0xFFFF;
}
int r[] = new int[2];
r[0] = glyph;
r[1] = getGlyphWidth(r[0]);
h.put(Integer.valueOf(fontSpecific ? ((j & 0xff00) == 0xf000 ? j & 0xff : j) : j), r);
}
}
return h;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
HashMap<Integer, int[]> readFormat6() throws IOException {
HashMap<Integer, int[]> h = new HashMap<Integer, int[]>();
rf.skipBytes(4);
int start_code = rf.readUnsignedShort();
int code_count = rf.readUnsignedShort();
for (int k = 0; k < code_count; ++k) {
int r[] = new int[2];
r[0] = rf.readUnsignedShort();
r[1] = getGlyphWidth(r[0]);
h.put(Integer.valueOf(k + start_code), r);
}
return h;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
void readKerning() throws IOException {
int table_location[];
table_location = tables.get("kern");
if (table_location == null)
return;
rf.seek(table_location[0] + 2);
int nTables = rf.readUnsignedShort();
int checkpoint = table_location[0] + 4;
int length = 0;
for (int k = 0; k < nTables; ++k) {
checkpoint += length;
rf.seek(checkpoint);
rf.skipBytes(2);
length = rf.readUnsignedShort();
int coverage = rf.readUnsignedShort();
if ((coverage & 0xfff7) == 0x0001) {
int nPairs = rf.readUnsignedShort();
rf.skipBytes(6);
for (int j = 0; j < nPairs; ++j) {
int pair = rf.readInt();
int value = rf.readShort() * 1000 / head.unitsPerEm;
kerning.put(pair, value);
}
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
protected byte[] getFullFont() throws IOException {
RandomAccessFileOrArray rf2 = null;
try {
rf2 = new RandomAccessFileOrArray(rf);
rf2.reOpen();
byte b[] = new byte[(int)rf2.length()];
rf2.readFully(b);
return b;
}
finally {
try {if (rf2 != null) {rf2.close();}} catch (Exception e) {}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
synchronized protected byte[] getSubSet(HashSet glyphs, boolean subsetp) throws IOException, DocumentException {
TrueTypeFontSubSet sb = new TrueTypeFontSubSet(fileName, new RandomAccessFileOrArray(rf), glyphs, directoryOffset, true, !subsetp);
return sb.process();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
Override
void writeFont(PdfWriter writer, PdfIndirectReference ref, Object params[]) throws DocumentException, IOException {
int firstChar = ((Integer)params[0]).intValue();
int lastChar = ((Integer)params[1]).intValue();
byte shortTag[] = (byte[])params[2];
boolean subsetp = ((Boolean)params[3]).booleanValue() && subset;
if (!subsetp) {
firstChar = 0;
lastChar = shortTag.length - 1;
for (int k = 0; k < shortTag.length; ++k)
shortTag[k] = 1;
}
PdfIndirectReference ind_font = null;
PdfObject pobj = null;
PdfIndirectObject obj = null;
String subsetPrefix = "";
if (embedded) {
if (cff) {
pobj = new StreamFont(readCffFont(), "Type1C", compressionLevel);
obj = writer.addToBody(pobj);
ind_font = obj.getIndirectReference();
}
else {
if (subsetp)
subsetPrefix = createSubsetPrefix();
HashSet<Integer> glyphs = new HashSet<Integer>();
for (int k = firstChar; k <= lastChar; ++k) {
if (shortTag[k] != 0) {
int[] metrics = null;
if (specialMap != null) {
int[] cd = GlyphList.nameToUnicode(differences[k]);
if (cd != null)
metrics = getMetricsTT(cd[0]);
}
else {
if (fontSpecific)
metrics = getMetricsTT(k);
else
metrics = getMetricsTT(unicodeDifferences[k]);
}
if (metrics != null)
glyphs.add(Integer.valueOf(metrics[0]));
}
}
addRangeUni(glyphs, subsetp);
byte[] b = null;
if (subsetp || directoryOffset != 0 || subsetRanges != null) {
b = getSubSet(glyphs, subsetp);
}
else {
b = getFullFont();
}
int lengths[] = new int[]{b.length};
pobj = new StreamFont(b, lengths, compressionLevel);
obj = writer.addToBody(pobj);
ind_font = obj.getIndirectReference();
}
}
pobj = getFontDescriptor(ind_font, subsetPrefix, null);
if (pobj != null){
obj = writer.addToBody(pobj);
ind_font = obj.getIndirectReference();
}
pobj = getFontBaseType(ind_font, subsetPrefix, firstChar, lastChar, shortTag);
writer.addToBody(pobj, ref);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
protected byte[] readCffFont() throws IOException {
RandomAccessFileOrArray rf2 = new RandomAccessFileOrArray(rf);
byte b[] = new byte[cffLength];
try {
rf2.reOpen();
rf2.seek(cffOffset);
rf2.readFully(b);
}
finally {
try {
rf2.close();
}
catch (Exception e) {
// empty on purpose
}
}
return b;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
Override
public PdfStream getFullFontStream() throws IOException, DocumentException {
if (cff) {
return new StreamFont(readCffFont(), "Type1C", compressionLevel);
}
else {
byte[] b = getFullFont();
int lengths[] = new int[]{b.length};
return new StreamFont(b, lengths, compressionLevel);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImportedPage.java
public PdfStream getFormXObject(int compressionLevel) throws IOException {
return readerInstance.getFormXObject(pageNumber, compressionLevel);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
public InputStream getRangeStream() throws IOException {
RandomAccessSourceFactory fac = new RandomAccessSourceFactory();
return new RASInputStream(fac.createRanged(getUnderlyingSource(), range));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
private RandomAccessSource getUnderlyingSource() throws IOException {
//TODO: get rid of separate byte[] and RandomAccessFile objects and just store a RandomAccessSource
RandomAccessSourceFactory fac = new RandomAccessSourceFactory();
return raf == null ? fac.createSource(bout) : fac.createSource(raf);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
public void preClose(HashMap<PdfName, Integer> exclusionSizes) throws IOException, DocumentException {
if (preClosed)
throw new DocumentException(MessageLocalization.getComposedMessage("document.already.pre.closed"));
stamper.mergeVerification();
preClosed = true;
AcroFields af = writer.getAcroFields();
String name = getFieldName();
boolean fieldExists = !(isInvisible() || isNewField());
PdfIndirectReference refSig = writer.getPdfIndirectReference();
writer.setSigFlags(3);
PdfDictionary fieldLock = null;
if (fieldExists) {
PdfDictionary widget = af.getFieldItem(name).getWidget(0);
writer.markUsed(widget);
fieldLock = widget.getAsDict(PdfName.LOCK);
widget.put(PdfName.P, writer.getPageReference(getPage()));
widget.put(PdfName.V, refSig);
PdfObject obj = PdfReader.getPdfObjectRelease(widget.get(PdfName.F));
int flags = 0;
if (obj != null && obj.isNumber())
flags = ((PdfNumber)obj).intValue();
flags |= PdfAnnotation.FLAGS_LOCKED;
widget.put(PdfName.F, new PdfNumber(flags));
PdfDictionary ap = new PdfDictionary();
ap.put(PdfName.N, getAppearance().getIndirectReference());
widget.put(PdfName.AP, ap);
}
else {
PdfFormField sigField = PdfFormField.createSignature(writer);
sigField.setFieldName(name);
sigField.put(PdfName.V, refSig);
sigField.setFlags(PdfAnnotation.FLAGS_PRINT | PdfAnnotation.FLAGS_LOCKED);
int pagen = getPage();
if (!isInvisible())
sigField.setWidget(getPageRect(), null);
else
sigField.setWidget(new Rectangle(0, 0), null);
sigField.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, getAppearance());
sigField.setPage(pagen);
writer.addAnnotation(sigField, pagen);
}
exclusionLocations = new HashMap<PdfName, PdfLiteral>();
if (cryptoDictionary == null) {
throw new DocumentException("No crypto dictionary defined.");
}
else {
PdfLiteral lit = new PdfLiteral(80);
exclusionLocations.put(PdfName.BYTERANGE, lit);
cryptoDictionary.put(PdfName.BYTERANGE, lit);
for (Map.Entry<PdfName, Integer> entry: exclusionSizes.entrySet()) {
PdfName key = entry.getKey();
Integer v = entry.getValue();
lit = new PdfLiteral(v.intValue());
exclusionLocations.put(key, lit);
cryptoDictionary.put(key, lit);
}
if (certificationLevel > 0)
addDocMDP(cryptoDictionary);
if (fieldLock != null)
addFieldMDP(cryptoDictionary, fieldLock);
if (signatureEvent != null)
signatureEvent.getSignatureDictionary(cryptoDictionary);
writer.addToBody(cryptoDictionary, refSig, false);
}
if (certificationLevel > 0) {
// add DocMDP entry to root
PdfDictionary docmdp = new PdfDictionary();
docmdp.put(new PdfName("DocMDP"), refSig);
writer.reader.getCatalog().put(new PdfName("Perms"), docmdp);
}
writer.close(stamper.getMoreInfo());
range = new long[exclusionLocations.size() * 2];
long byteRangePosition = exclusionLocations.get(PdfName.BYTERANGE).getPosition();
exclusionLocations.remove(PdfName.BYTERANGE);
int idx = 1;
for (PdfLiteral lit: exclusionLocations.values()) {
long n = lit.getPosition();
range[idx++] = n;
range[idx++] = lit.getPosLength() + n;
}
Arrays.sort(range, 1, range.length - 1);
for (int k = 3; k < range.length - 2; k += 2)
range[k] -= range[k - 1];
if (tempFile == null) {
bout = sigout.getBuffer();
boutLen = sigout.size();
range[range.length - 1] = boutLen - range[range.length - 2];
ByteBuffer bf = new ByteBuffer();
bf.append('[');
for (int k = 0; k < range.length; ++k)
bf.append(range[k]).append(' ');
bf.append(']');
System.arraycopy(bf.getBuffer(), 0, bout, (int)byteRangePosition, bf.size());
}
else {
try {
raf = new RandomAccessFile(tempFile, "rw");
long len = raf.length();
range[range.length - 1] = len - range[range.length - 2];
ByteBuffer bf = new ByteBuffer();
bf.append('[');
for (int k = 0; k < range.length; ++k)
bf.append(range[k]).append(' ');
bf.append(']');
raf.seek(byteRangePosition);
raf.write(bf.getBuffer(), 0, bf.size());
}
catch (IOException e) {
try{raf.close();}catch(Exception ee){}
try{tempFile.delete();}catch(Exception ee){}
throw e;
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
public void close(PdfDictionary update) throws IOException, DocumentException {
try {
if (!preClosed)
throw new DocumentException(MessageLocalization.getComposedMessage("preclose.must.be.called.first"));
ByteBuffer bf = new ByteBuffer();
for (PdfName key: update.getKeys()) {
PdfObject obj = update.get(key);
PdfLiteral lit = exclusionLocations.get(key);
if (lit == null)
throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.key.1.didn.t.reserve.space.in.preclose", key.toString()));
bf.reset();
obj.toPdf(null, bf);
if (bf.size() > lit.getPosLength())
throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.key.1.is.too.big.is.2.reserved.3", key.toString(), String.valueOf(bf.size()), String.valueOf(lit.getPosLength())));
if (tempFile == null)
System.arraycopy(bf.getBuffer(), 0, bout, (int)lit.getPosition(), bf.size());
else {
raf.seek(lit.getPosition());
raf.write(bf.getBuffer(), 0, bf.size());
}
}
if (update.size() != exclusionLocations.size())
throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.update.dictionary.has.less.keys.than.required"));
if (tempFile == null) {
originalout.write(bout, 0, boutLen);
}
else {
if (originalout != null) {
raf.seek(0);
long length = raf.length();
byte buf[] = new byte[8192];
while (length > 0) {
int r = raf.read(buf, 0, (int)Math.min((long)buf.length, length));
if (r < 0)
throw new EOFException(MessageLocalization.getComposedMessage("unexpected.eof"));
originalout.write(buf, 0, r);
length -= r;
}
}
}
}
finally {
writer.reader.close();
if (tempFile != null) {
try{raf.close();}catch(Exception ee){}
if (originalout != null)
try{tempFile.delete();}catch(Exception ee){}
}
if (originalout != null)
try{originalout.close();}catch(Exception e){}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
protected void close(Map<String, String> moreInfo) throws IOException {
if (closed)
return;
if (useVp) {
setViewerPreferences();
}
if (flat)
flatFields();
if (flatFreeText)
flatFreeTextFields();
addFieldResources();
PdfDictionary catalog = reader.getCatalog();
PdfDictionary acroForm = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.ACROFORM), reader.getCatalog());
if (acroFields != null && acroFields.getXfa().isChanged()) {
markUsed(acroForm);
if (!flat)
acroFields.getXfa().setXfa(this);
}
if (sigFlags != 0) {
if (acroForm != null) {
acroForm.put(PdfName.SIGFLAGS, new PdfNumber(sigFlags));
markUsed(acroForm);
markUsed(catalog);
}
}
closed = true;
addSharedObjectsToBody();
setOutlines();
setJavaScript();
addFileAttachments();
if (openAction != null) {
catalog.put(PdfName.OPENACTION, openAction);
}
if (pdf.pageLabels != null)
catalog.put(PdfName.PAGELABELS, pdf.pageLabels.getDictionary(this));
// OCG
if (!documentOCG.isEmpty()) {
fillOCProperties(false);
PdfDictionary ocdict = catalog.getAsDict(PdfName.OCPROPERTIES);
if (ocdict == null) {
reader.getCatalog().put(PdfName.OCPROPERTIES, OCProperties);
}
else {
ocdict.put(PdfName.OCGS, OCProperties.get(PdfName.OCGS));
PdfDictionary ddict = ocdict.getAsDict(PdfName.D);
if (ddict == null) {
ddict = new PdfDictionary();
ocdict.put(PdfName.D, ddict);
}
ddict.put(PdfName.ORDER, OCProperties.getAsDict(PdfName.D).get(PdfName.ORDER));
ddict.put(PdfName.RBGROUPS, OCProperties.getAsDict(PdfName.D).get(PdfName.RBGROUPS));
ddict.put(PdfName.OFF, OCProperties.getAsDict(PdfName.D).get(PdfName.OFF));
ddict.put(PdfName.AS, OCProperties.getAsDict(PdfName.D).get(PdfName.AS));
}
}
// metadata
int skipInfo = -1;
PdfObject oInfo = reader.getTrailer().get(PdfName.INFO);
PRIndirectReference iInfo = null;
PdfDictionary oldInfo = null;
if (oInfo instanceof PRIndirectReference)
iInfo = (PRIndirectReference)oInfo;
if (iInfo != null)
oldInfo = (PdfDictionary)PdfReader.getPdfObject(iInfo);
else if (oInfo instanceof PdfDictionary)
oldInfo = (PdfDictionary)oInfo;
String producer = null;
if (iInfo != null)
skipInfo = iInfo.getNumber();
if (oldInfo != null && oldInfo.get(PdfName.PRODUCER) != null)
producer = oldInfo.getAsString(PdfName.PRODUCER).toUnicodeString();
Version version = Version.getInstance();
if (producer == null) {
producer = version.getVersion();
}
else if (producer.indexOf(version.getProduct()) == -1) {
StringBuffer buf = new StringBuffer(producer);
buf.append("; modified using ");
buf.append(version.getVersion());
producer = buf.toString();
}
PdfIndirectReference info = null;
PdfDictionary newInfo = new PdfDictionary();
if (oldInfo != null) {
for (Object element : oldInfo.getKeys()) {
PdfName key = (PdfName)element;
PdfObject value = PdfReader.getPdfObject(oldInfo.get(key));
newInfo.put(key, value);
}
}
if (moreInfo != null) {
for (Map.Entry<String, String> entry: moreInfo.entrySet()) {
String key = entry.getKey();
PdfName keyName = new PdfName(key);
String value = entry.getValue();
if (value == null)
newInfo.remove(keyName);
else
newInfo.put(keyName, new PdfString(value, PdfObject.TEXT_UNICODE));
}
}
PdfDate date = new PdfDate();
newInfo.put(PdfName.MODDATE, date);
newInfo.put(PdfName.PRODUCER, new PdfString(producer, PdfObject.TEXT_UNICODE));
if (append) {
if (iInfo == null)
info = addToBody(newInfo, false).getIndirectReference();
else
info = addToBody(newInfo, iInfo.getNumber(), false).getIndirectReference();
}
else {
info = addToBody(newInfo, false).getIndirectReference();
}
// XMP
byte[] altMetadata = null;
PdfObject xmpo = PdfReader.getPdfObject(catalog.get(PdfName.METADATA));
if (xmpo != null && xmpo.isStream()) {
altMetadata = PdfReader.getStreamBytesRaw((PRStream)xmpo);
PdfReader.killIndirect(catalog.get(PdfName.METADATA));
}
if (xmpMetadata != null) {
altMetadata = xmpMetadata;
}
if (altMetadata != null) {
PdfStream xmp;
try {
XmpReader xmpr;
if (moreInfo == null || xmpMetadata != null) {
xmpr = new XmpReader(altMetadata);
if (!(xmpr.replaceNode("http://ns.adobe.com/pdf/1.3/", "Producer", producer)
|| xmpr.replaceDescriptionAttribute("http://ns.adobe.com/pdf/1.3/", "Producer", producer)))
xmpr.add("rdf:Description", "http://ns.adobe.com/pdf/1.3/", "Producer", producer);
if (!(xmpr.replaceNode("http://ns.adobe.com/xap/1.0/", "ModifyDate", date.getW3CDate())
|| xmpr.replaceDescriptionAttribute("http://ns.adobe.com/xap/1.0/", "ModifyDate", date.getW3CDate())))
xmpr.add("rdf:Description", "http://ns.adobe.com/xap/1.0/", "ModifyDate", date.getW3CDate());
if (!(xmpr.replaceNode("http://ns.adobe.com/xap/1.0/", "MetadataDate", date.getW3CDate())
|| xmpr.replaceDescriptionAttribute("http://ns.adobe.com/xap/1.0/", "MetadataDate", date.getW3CDate()))) {
}
}
else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
XmpWriter xmpw = new XmpWriter(baos, newInfo, getPDFXConformance());
xmpw.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
xmpr = new XmpReader(baos.toByteArray());
}
xmp = new PdfStream(xmpr.serializeDoc());
}
catch(SAXException e) {
xmp = new PdfStream(altMetadata);
}
catch(IOException e) {
xmp = new PdfStream(altMetadata);
}
xmp.put(PdfName.TYPE, PdfName.METADATA);
xmp.put(PdfName.SUBTYPE, PdfName.XML);
if (crypto != null && !crypto.isMetadataEncrypted()) {
PdfArray ar = new PdfArray();
ar.add(PdfName.CRYPT);
xmp.put(PdfName.FILTER, ar);
}
if (append && xmpo != null) {
body.add(xmp, xmpo.getIndRef());
}
else {
catalog.put(PdfName.METADATA, body.add(xmp).getIndirectReference());
markUsed(catalog);
}
}
close(info, skipInfo);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
protected void close(PdfIndirectReference info, int skipInfo) throws IOException {
alterContents();
int rootN = ((PRIndirectReference)reader.trailer.get(PdfName.ROOT)).getNumber();
if (append) {
int keys[] = marked.getKeys();
for (int k = 0; k < keys.length; ++k) {
int j = keys[k];
PdfObject obj = reader.getPdfObjectRelease(j);
if (obj != null && skipInfo != j && j < initialXrefSize) {
addToBody(obj, j, j != rootN);
}
}
for (int k = initialXrefSize; k < reader.getXrefSize(); ++k) {
PdfObject obj = reader.getPdfObject(k);
if (obj != null) {
addToBody(obj, getNewObjectNumber(reader, k, 0));
}
}
}
else {
for (int k = 1; k < reader.getXrefSize(); ++k) {
PdfObject obj = reader.getPdfObjectRelease(k);
if (obj != null && skipInfo != k) {
addToBody(obj, getNewObjectNumber(reader, k, 0), k != rootN);
}
}
}
PdfIndirectReference encryption = null;
PdfObject fileID = null;
if (crypto != null) {
if (append) {
encryption = reader.getCryptoRef();
}
else {
PdfIndirectObject encryptionObject = addToBody(crypto.getEncryptionDictionary(), false);
encryption = encryptionObject.getIndirectReference();
}
fileID = crypto.getFileID();
}
else
fileID = PdfEncryption.createInfoId(PdfEncryption.createDocumentId());
PRIndirectReference iRoot = (PRIndirectReference)reader.trailer.get(PdfName.ROOT);
PdfIndirectReference root = new PdfIndirectReference(0, getNewObjectNumber(reader, iRoot.getNumber(), 0));
// write the cross-reference table of the body
body.writeCrossReferenceTable(os, root, info, encryption, fileID, prevxref);
if (fullCompression) {
writeKeyInfo(os);
os.write(getISOBytes("startxref\n"));
os.write(getISOBytes(String.valueOf(body.offset())));
os.write(getISOBytes("\n%%EOF\n"));
}
else {
PdfTrailer trailer = new PdfTrailer(body.size(),
body.offset(),
root,
info,
encryption,
fileID, prevxref);
trailer.toPdf(this, os);
}
os.flush();
if (isCloseStream())
os.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
protected void alterContents() throws IOException {
for (Object element : pagesToContent.values()) {
PageStamp ps = (PageStamp)element;
PdfDictionary pageN = ps.pageN;
markUsed(pageN);
PdfArray ar = null;
PdfObject content = PdfReader.getPdfObject(pageN.get(PdfName.CONTENTS), pageN);
if (content == null) {
ar = new PdfArray();
pageN.put(PdfName.CONTENTS, ar);
}
else if (content.isArray()) {
ar = (PdfArray)content;
markUsed(ar);
}
else if (content.isStream()) {
ar = new PdfArray();
ar.add(pageN.get(PdfName.CONTENTS));
pageN.put(PdfName.CONTENTS, ar);
}
else {
ar = new PdfArray();
pageN.put(PdfName.CONTENTS, ar);
}
ByteBuffer out = new ByteBuffer();
if (ps.under != null) {
out.append(PdfContents.SAVESTATE);
applyRotation(pageN, out);
out.append(ps.under.getInternalBuffer());
out.append(PdfContents.RESTORESTATE);
}
if (ps.over != null)
out.append(PdfContents.SAVESTATE);
PdfStream stream = new PdfStream(out.toByteArray());
stream.flateCompress(compressionLevel);
ar.addFirst(addToBody(stream).getIndirectReference());
out.reset();
if (ps.over != null) {
out.append(' ');
out.append(PdfContents.RESTORESTATE);
ByteBuffer buf = ps.over.getInternalBuffer();
out.append(buf.getBuffer(), 0, ps.replacePoint);
out.append(PdfContents.SAVESTATE);
applyRotation(pageN, out);
out.append(buf.getBuffer(), ps.replacePoint, buf.size() - ps.replacePoint);
out.append(PdfContents.RESTORESTATE);
stream = new PdfStream(out.toByteArray());
stream.flateCompress(compressionLevel);
ar.add(addToBody(stream).getIndirectReference());
}
alterResources(ps);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
public void registerReader(PdfReader reader, boolean openFile) throws IOException {
if (readers2intrefs.containsKey(reader))
return;
readers2intrefs.put(reader, new IntHashtable());
if (openFile) {
RandomAccessFileOrArray raf = reader.getSafeFile();
readers2file.put(reader, raf);
raf.reOpen();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
public void addComments(FdfReader fdf) throws IOException{
if (readers2intrefs.containsKey(fdf))
return;
PdfDictionary catalog = fdf.getCatalog();
catalog = catalog.getAsDict(PdfName.FDF);
if (catalog == null)
return;
PdfArray annots = catalog.getAsArray(PdfName.ANNOTS);
if (annots == null || annots.size() == 0)
return;
registerReader(fdf, false);
IntHashtable hits = new IntHashtable();
HashMap<String, PdfObject> irt = new HashMap<String, PdfObject>();
ArrayList<PdfObject> an = new ArrayList<PdfObject>();
for (int k = 0; k < annots.size(); ++k) {
PdfObject obj = annots.getPdfObject(k);
PdfDictionary annot = (PdfDictionary)PdfReader.getPdfObject(obj);
PdfNumber page = annot.getAsNumber(PdfName.PAGE);
if (page == null || page.intValue() >= reader.getNumberOfPages())
continue;
findAllObjects(fdf, obj, hits);
an.add(obj);
if (obj.type() == PdfObject.INDIRECT) {
PdfObject nm = PdfReader.getPdfObject(annot.get(PdfName.NM));
if (nm != null && nm.type() == PdfObject.STRING)
irt.put(nm.toString(), obj);
}
}
int arhits[] = hits.getKeys();
for (int k = 0; k < arhits.length; ++k) {
int n = arhits[k];
PdfObject obj = fdf.getPdfObject(n);
if (obj.type() == PdfObject.DICTIONARY) {
PdfObject str = PdfReader.getPdfObject(((PdfDictionary)obj).get(PdfName.IRT));
if (str != null && str.type() == PdfObject.STRING) {
PdfObject i = irt.get(str.toString());
if (i != null) {
PdfDictionary dic2 = new PdfDictionary();
dic2.merge((PdfDictionary)obj);
dic2.put(PdfName.IRT, i);
obj = dic2;
}
}
}
addToBody(obj, getNewObjectNumber(fdf, n, 0));
}
for (int k = 0; k < an.size(); ++k) {
PdfObject obj = an.get(k);
PdfDictionary annot = (PdfDictionary)PdfReader.getPdfObject(obj);
PdfNumber page = annot.getAsNumber(PdfName.PAGE);
PdfDictionary dic = reader.getPageN(page.intValue() + 1);
PdfArray annotsp = (PdfArray)PdfReader.getPdfObject(dic.get(PdfName.ANNOTS), dic);
if (annotsp == null) {
annotsp = new PdfArray();
dic.put(PdfName.ANNOTS, annotsp);
markUsed(dic);
}
markUsed(annotsp);
annotsp.add(obj);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
protected void addFieldResources() throws IOException {
if (fieldTemplates.isEmpty())
return;
PdfDictionary catalog = reader.getCatalog();
PdfDictionary acroForm = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.ACROFORM), catalog);
if (acroForm == null) {
acroForm = new PdfDictionary();
catalog.put(PdfName.ACROFORM, acroForm);
markUsed(catalog);
}
PdfDictionary dr = (PdfDictionary)PdfReader.getPdfObject(acroForm.get(PdfName.DR), acroForm);
if (dr == null) {
dr = new PdfDictionary();
acroForm.put(PdfName.DR, dr);
markUsed(acroForm);
}
markUsed(dr);
for (PdfTemplate template: fieldTemplates) {
PdfFormField.mergeResources(dr, (PdfDictionary)template.getResources(), this);
}
// if (dr.get(PdfName.ENCODING) == null) dr.put(PdfName.ENCODING, PdfName.WIN_ANSI_ENCODING);
PdfDictionary fonts = dr.getAsDict(PdfName.FONT);
if (fonts == null) {
fonts = new PdfDictionary();
dr.put(PdfName.FONT, fonts);
}
if (!fonts.contains(PdfName.HELV)) {
PdfDictionary dic = new PdfDictionary(PdfName.FONT);
dic.put(PdfName.BASEFONT, PdfName.HELVETICA);
dic.put(PdfName.ENCODING, PdfName.WIN_ANSI_ENCODING);
dic.put(PdfName.NAME, PdfName.HELV);
dic.put(PdfName.SUBTYPE, PdfName.TYPE1);
fonts.put(PdfName.HELV, addToBody(dic).getIndirectReference());
}
if (!fonts.contains(PdfName.ZADB)) {
PdfDictionary dic = new PdfDictionary(PdfName.FONT);
dic.put(PdfName.BASEFONT, PdfName.ZAPFDINGBATS);
dic.put(PdfName.NAME, PdfName.ZADB);
dic.put(PdfName.SUBTYPE, PdfName.TYPE1);
fonts.put(PdfName.ZADB, addToBody(dic).getIndirectReference());
}
if (acroForm.get(PdfName.DA) == null) {
acroForm.put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g "));
markUsed(acroForm);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
protected void setJavaScript() throws IOException {
HashMap<String, PdfObject> djs = pdf.getDocumentLevelJS();
if (djs.isEmpty())
return;
PdfDictionary catalog = reader.getCatalog();
PdfDictionary names = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.NAMES), catalog);
if (names == null) {
names = new PdfDictionary();
catalog.put(PdfName.NAMES, names);
markUsed(catalog);
}
markUsed(names);
PdfDictionary tree = PdfNameTree.writeTree(djs, this);
names.put(PdfName.JAVASCRIPT, addToBody(tree).getIndirectReference());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
protected void addFileAttachments() throws IOException {
HashMap<String, PdfObject> fs = pdf.getDocumentFileAttachment();
if (fs.isEmpty())
return;
PdfDictionary catalog = reader.getCatalog();
PdfDictionary names = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.NAMES), catalog);
if (names == null) {
names = new PdfDictionary();
catalog.put(PdfName.NAMES, names);
markUsed(catalog);
}
markUsed(names);
HashMap<String, PdfObject> old = PdfNameTree.readTree((PdfDictionary)PdfReader.getPdfObjectRelease(names.get(PdfName.EMBEDDEDFILES)));
for (Map.Entry<String, PdfObject> entry: fs.entrySet()) {
String name = entry.getKey();
int k = 0;
StringBuilder nn = new StringBuilder(name);
while (old.containsKey(nn.toString())) {
++k;
nn.append(" ").append(k);
}
old.put(nn.toString(), entry.getValue());
}
PdfDictionary tree = PdfNameTree.writeTree(old, this);
// Remove old EmbeddedFiles object if preset
PdfObject oldEmbeddedFiles = names.get(PdfName.EMBEDDEDFILES);
if (oldEmbeddedFiles != null) {
PdfReader.killIndirect(oldEmbeddedFiles);
}
// Add new EmbeddedFiles object
names.put(PdfName.EMBEDDEDFILES, addToBody(tree).getIndirectReference());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
protected void setOutlines() throws IOException {
if (newBookmarks == null)
return;
deleteOutlines();
if (newBookmarks.isEmpty())
return;
PdfDictionary catalog = reader.getCatalog();
boolean namedAsNames = catalog.get(PdfName.DESTS) != null;
writeOutlines(catalog, namedAsNames);
markUsed(catalog);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamCounter.java
public void close() throws IOException {
out.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamCounter.java
public void flush() throws IOException {
out.flush();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamCounter.java
public void write(byte[] b) throws IOException {
counter += b.length;
out.write(b);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamCounter.java
public void write(int b) throws IOException {
++counter;
out.write(b);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamCounter.java
public void write(byte[] b, int off, int len) throws IOException {
counter += len;
out.write(b, off, len);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfShadingPattern.java
public void addToBody() throws IOException {
put(PdfName.SHADING, getShadingReference());
put(PdfName.MATRIX, new PdfArray(matrix));
writer.addToBody(this, getPatternReference());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
void addDocument(PdfReader reader, List<Integer> pagesToKeep) throws DocumentException, IOException {
if (!readers2intrefs.containsKey(reader) && reader.isTampered())
throw new DocumentException(MessageLocalization.getComposedMessage("the.document.was.reused"));
reader = new PdfReader(reader);
reader.selectPages(pagesToKeep);
if (reader.getNumberOfPages() == 0)
return;
reader.setTampered(false);
addDocument(reader);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
void addDocument(PdfReader reader) throws DocumentException, IOException {
if (!reader.isOpenedWithFullPermissions())
throw new BadPasswordException(MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password"));
openDoc();
if (readers2intrefs.containsKey(reader)) {
reader = new PdfReader(reader);
}
else {
if (reader.isTampered())
throw new DocumentException(MessageLocalization.getComposedMessage("the.document.was.reused"));
reader.consolidateNamedDestinations();
reader.setTampered(true);
}
reader.shuffleSubsetNames();
readers2intrefs.put(reader, new IntHashtable());
readers.add(reader);
int len = reader.getNumberOfPages();
IntHashtable refs = new IntHashtable();
for (int p = 1; p <= len; ++p) {
refs.put(reader.getPageOrigRef(p).getNumber(), 1);
reader.releasePage(p);
}
pages2intrefs.put(reader, refs);
visited.put(reader, new IntHashtable());
fields.add(reader.getAcroFields());
updateCalculationOrder(reader);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
void propagate(PdfObject obj, PdfIndirectReference refo, boolean restricted) throws IOException {
if (obj == null)
return;
// if (refo != null)
// addToBody(obj, refo);
if (obj instanceof PdfIndirectReference)
return;
switch (obj.type()) {
case PdfObject.DICTIONARY:
case PdfObject.STREAM: {
PdfDictionary dic = (PdfDictionary)obj;
for (PdfName key: dic.getKeys()) {
if (restricted && (key.equals(PdfName.PARENT) || key.equals(PdfName.KIDS)))
continue;
PdfObject ob = dic.get(key);
if (ob != null && ob.isIndirect()) {
PRIndirectReference ind = (PRIndirectReference)ob;
if (!setVisited(ind) && !isPage(ind)) {
PdfIndirectReference ref = getNewReference(ind);
propagate(PdfReader.getPdfObjectRelease(ind), ref, restricted);
}
}
else
propagate(ob, null, restricted);
}
break;
}
case PdfObject.ARRAY: {
//PdfArray arr = new PdfArray();
for (Iterator<PdfObject> it = ((PdfArray)obj).listIterator(); it.hasNext();) {
PdfObject ob = it.next();
if (ob != null && ob.isIndirect()) {
PRIndirectReference ind = (PRIndirectReference)ob;
if (!isVisited(ind) && !isPage(ind)) {
PdfIndirectReference ref = getNewReference(ind);
propagate(PdfReader.getPdfObjectRelease(ind), ref, restricted);
}
}
else
propagate(ob, null, restricted);
}
break;
}
case PdfObject.INDIRECT: {
throw new RuntimeException(MessageLocalization.getComposedMessage("reference.pointing.to.reference"));
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
protected void createAcroForms() throws IOException {
if (fieldTree.isEmpty())
return;
form = new PdfDictionary();
form.put(PdfName.DR, resources);
propagate(resources, null, false);
form.put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g "));
tabOrder = new HashMap<PdfArray, ArrayList<Integer>>();
calculationOrderRefs = new ArrayList<Object>(calculationOrder);
form.put(PdfName.FIELDS, branchForm(fieldTree, null, ""));
if (hasSignature)
form.put(PdfName.SIGFLAGS, new PdfNumber(3));
PdfArray co = new PdfArray();
for (int k = 0; k < calculationOrderRefs.size(); ++k) {
Object obj = calculationOrderRefs.get(k);
if (obj instanceof PdfIndirectReference)
co.add((PdfIndirectReference)obj);
}
if (co.size() > 0)
form.put(PdfName.CO, co);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
protected void closeIt() throws IOException {
for (int k = 0; k < readers.size(); ++k) {
readers.get(k).removeFields();
}
for (int r = 0; r < readers.size(); ++r) {
PdfReader reader = readers.get(r);
for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
pageRefs.add(getNewReference(reader.getPageOrigRef(page)));
pageDics.add(reader.getPageN(page));
}
}
mergeFields();
createAcroForms();
for (int r = 0; r < readers.size(); ++r) {
PdfReader reader = readers.get(r);
for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
PdfDictionary dic = reader.getPageN(page);
PdfIndirectReference pageRef = getNewReference(reader.getPageOrigRef(page));
PdfIndirectReference parent = root.addPageRef(pageRef);
dic.put(PdfName.PARENT, parent);
propagate(dic, pageRef, false);
}
}
for (Map.Entry<PdfReader, IntHashtable>entry: readers2intrefs.entrySet()) {
PdfReader reader = entry.getKey();
try {
file = reader.getSafeFile();
file.reOpen();
IntHashtable t = entry.getValue();
int keys[] = t.toOrderedKeys();
for (int k = 0; k < keys.length; ++k) {
PRIndirectReference ref = new PRIndirectReference(reader, keys[k]);
addToBody(PdfReader.getPdfObjectRelease(ref), t.get(keys[k]));
}
}
finally {
try {
file.close();
// TODO: Removed - the user should be responsible for closing all PdfReaders. But, this could cause a lot of memory leaks in code out there that hasn't been properly closing things - maybe add a finalizer to PdfReader that calls PdfReader#close() ??
// reader.close();
}
catch (Exception e) {
// empty on purpose
}
}
}
pdf.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfOutline.java
Override
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {
if (color != null && !color.equals(BaseColor.BLACK)) {
put(PdfName.C, new PdfArray(new float[]{color.getRed()/255f,color.getGreen()/255f,color.getBlue()/255f}));
}
int flag = 0;
if ((style & Font.BOLD) != 0)
flag |= 2;
if ((style & Font.ITALIC) != 0)
flag |= 1;
if (flag != 0)
put(PdfName.F, new PdfNumber(flag));
if (parent != null) {
put(PdfName.PARENT, parent.indirectReference());
}
if (destination != null && destination.hasPage()) {
put(PdfName.DEST, destination);
}
if (action != null)
put(PdfName.A, action);
if (count != 0) {
put(PdfName.COUNT, new PdfNumber(count));
}
super.toPdf(writer, os);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfVersionImp.java
public void writeHeader(OutputStreamCounter os) throws IOException {
if (appendmode) {
os.write(HEADER[0]);
}
else {
os.write(HEADER[1]);
os.write(getVersionAsByteArray(header_version));
os.write(HEADER[2]);
headerWasWritten = true;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfAnnotationsImp.java
public static PdfAnnotation convertAnnotation(PdfWriter writer, Annotation annot, Rectangle defaultRect) throws IOException {
switch(annot.annotationType()) {
case Annotation.URL_NET:
return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction((URL) annot.attributes().get(Annotation.URL)));
case Annotation.URL_AS_STRING:
return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction((String) annot.attributes().get(Annotation.FILE)));
case Annotation.FILE_DEST:
return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction((String) annot.attributes().get(Annotation.FILE), (String) annot.attributes().get(Annotation.DESTINATION)));
case Annotation.SCREEN:
boolean sparams[] = (boolean[])annot.attributes().get(Annotation.PARAMETERS);
String fname = (String) annot.attributes().get(Annotation.FILE);
String mimetype = (String) annot.attributes().get(Annotation.MIMETYPE);
PdfFileSpecification fs;
if (sparams[0])
fs = PdfFileSpecification.fileEmbedded(writer, fname, fname, null);
else
fs = PdfFileSpecification.fileExtern(writer, fname);
PdfAnnotation ann = PdfAnnotation.createScreen(writer, new Rectangle(annot.llx(), annot.lly(), annot.urx(), annot.ury()),
fname, fs, mimetype, sparams[1]);
return ann;
case Annotation.FILE_PAGE:
return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction((String) annot.attributes().get(Annotation.FILE), ((Integer) annot.attributes().get(Annotation.PAGE)).intValue()));
case Annotation.NAMED_DEST:
return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction(((Integer) annot.attributes().get(Annotation.NAMED)).intValue()));
case Annotation.LAUNCH:
return new PdfAnnotation(writer, annot.llx(), annot.lly(), annot.urx(), annot.ury(), new PdfAction((String) annot.attributes().get(Annotation.APPLICATION),(String) annot.attributes().get(Annotation.PARAMETERS),(String) annot.attributes().get(Annotation.OPERATION),(String) annot.attributes().get(Annotation.DEFAULTDIR)));
default:
return new PdfAnnotation(writer, defaultRect.getLeft(), defaultRect.getBottom(), defaultRect.getRight(), defaultRect.getTop(), new PdfString(annot.title(), PdfObject.TEXT_UNICODE), new PdfString(annot.content(), PdfObject.TEXT_UNICODE));
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
private static PRTokeniser getOffsetTokeniser(RandomAccessSource byteSource) throws IOException{
PRTokeniser tok = new PRTokeniser(new RandomAccessFileOrArray(byteSource));
int offset = tok.getHeaderOffset();
if (offset != 0){
RandomAccessSource offsetSource = new WindowRandomAccessSource(byteSource, offset);
tok = new PRTokeniser(new RandomAccessFileOrArray(offsetSource));
}
return tok;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected void readPdf() throws IOException {
fileLength = tokens.getFile().length();
pdfVersion = tokens.checkPdfHeader();
try {
readXref();
}
catch (Exception e) {
try {
rebuilt = true;
rebuildXref();
lastXref = -1;
}
catch (Exception ne) {
throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()));
}
}
try {
readDocObj();
}
catch (Exception e) {
if (e instanceof BadPasswordException)
throw new BadPasswordException(e.getMessage());
if (rebuilt || encryptionError)
throw new InvalidPdfException(e.getMessage());
rebuilt = true;
encrypted = false;
try{
rebuildXref();
lastXref = -1;
readDocObj();
} catch (Exception ne){
throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()));
}
}
strings.clear();
readPages();
//eliminateSharedStreams();
removeUnusedObjects();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected void readPdfPartial() throws IOException {
try {
fileLength = tokens.getFile().length();
pdfVersion = tokens.checkPdfHeader();
try {
readXref();
}
catch (Exception e) {
try {
rebuilt = true;
rebuildXref();
lastXref = -1;
}
catch (Exception ne) {
throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()), ne);
}
}
readDocObjPartial();
readPages();
}
catch (IOException e) {
try{tokens.close();}catch(Exception ee){}
throw e;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected void readPages() throws IOException {
catalog = trailer.getAsDict(PdfName.ROOT);
rootPages = catalog.getAsDict(PdfName.PAGES);
pageRefs = new PageRefs(this);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected void readDocObjPartial() throws IOException {
xrefObj = new ArrayList<PdfObject>(xref.length / 2);
xrefObj.addAll(Collections.<PdfObject>nCopies(xref.length / 2, null));
readDecryptedDocObj();
if (objStmToOffset != null) {
long keys[] = objStmToOffset.getKeys();
for (int k = 0; k < keys.length; ++k) {
long n = keys[k];
objStmToOffset.put(n, xref[(int)(n * 2)]);
xref[(int)(n * 2)] = -1;
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected PdfObject readSingleObject(final int k) throws IOException {
strings.clear();
int k2 = k * 2;
long pos = xref[k2];
if (pos < 0)
return null;
if (xref[k2 + 1] > 0)
pos = objStmToOffset.get(xref[k2 + 1]);
if (pos == 0)
return null;
tokens.seek(pos);
tokens.nextValidToken();
if (tokens.getTokenType() != TokenType.NUMBER)
tokens.throwError(MessageLocalization.getComposedMessage("invalid.object.number"));
objNum = tokens.intValue();
tokens.nextValidToken();
if (tokens.getTokenType() != TokenType.NUMBER)
tokens.throwError(MessageLocalization.getComposedMessage("invalid.generation.number"));
objGen = tokens.intValue();
tokens.nextValidToken();
if (!tokens.getStringValue().equals("obj"))
tokens.throwError(MessageLocalization.getComposedMessage("token.obj.expected"));
PdfObject obj;
try {
obj = readPRObject();
for (int j = 0; j < strings.size(); ++j) {
PdfString str = strings.get(j);
str.decrypt(this);
}
if (obj.isStream()) {
checkPRStreamLength((PRStream)obj);
}
}
catch (Exception e) {
obj = null;
}
if (xref[k2 + 1] > 0) {
obj = readOneObjStm((PRStream)obj, (int)xref[k2]);
}
xrefObj.set(k, obj);
return obj;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected PdfObject readOneObjStm(final PRStream stream, int idx) throws IOException {
int first = stream.getAsNumber(PdfName.FIRST).intValue();
byte b[] = getStreamBytes(stream, tokens.getFile());
PRTokeniser saveTokens = tokens;
tokens = new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(b)));
try {
int address = 0;
boolean ok = true;
++idx;
for (int k = 0; k < idx; ++k) {
ok = tokens.nextToken();
if (!ok)
break;
if (tokens.getTokenType() != TokenType.NUMBER) {
ok = false;
break;
}
ok = tokens.nextToken();
if (!ok)
break;
if (tokens.getTokenType() != TokenType.NUMBER) {
ok = false;
break;
}
address = tokens.intValue() + first;
}
if (!ok)
throw new InvalidPdfException(MessageLocalization.getComposedMessage("error.reading.objstm"));
tokens.seek(address);
tokens.nextToken();
PdfObject obj;
if (tokens.getTokenType() == PRTokeniser.TokenType.NUMBER) {
obj = new PdfNumber(tokens.getStringValue());
}
else {
tokens.seek(address);
obj = readPRObject();
}
return obj;
//return readPRObject();
}
finally {
tokens = saveTokens;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected void readDocObj() throws IOException {
ArrayList<PRStream> streams = new ArrayList<PRStream>();
xrefObj = new ArrayList<PdfObject>(xref.length / 2);
xrefObj.addAll(Collections.<PdfObject>nCopies(xref.length / 2, null));
for (int k = 2; k < xref.length; k += 2) {
long pos = xref[k];
if (pos <= 0 || xref[k + 1] > 0)
continue;
tokens.seek(pos);
tokens.nextValidToken();
if (tokens.getTokenType() != TokenType.NUMBER)
tokens.throwError(MessageLocalization.getComposedMessage("invalid.object.number"));
objNum = tokens.intValue();
tokens.nextValidToken();
if (tokens.getTokenType() != TokenType.NUMBER)
tokens.throwError(MessageLocalization.getComposedMessage("invalid.generation.number"));
objGen = tokens.intValue();
tokens.nextValidToken();
if (!tokens.getStringValue().equals("obj"))
tokens.throwError(MessageLocalization.getComposedMessage("token.obj.expected"));
PdfObject obj;
try {
obj = readPRObject();
if (obj.isStream()) {
streams.add((PRStream)obj);
}
}
catch (Exception e) {
obj = null;
}
xrefObj.set(k / 2, obj);
}
for (int k = 0; k < streams.size(); ++k) {
checkPRStreamLength(streams.get(k));
}
readDecryptedDocObj();
if (objStmMark != null) {
for (Map.Entry<Integer, IntHashtable>entry: objStmMark.entrySet()) {
int n = entry.getKey().intValue();
IntHashtable h = entry.getValue();
readObjStm((PRStream)xrefObj.get(n), h);
xrefObj.set(n, null);
}
objStmMark = null;
}
xref = null;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
private void checkPRStreamLength(final PRStream stream) throws IOException {
long fileLength = tokens.length();
long start = stream.getOffset();
boolean calc = false;
long streamLength = 0;
PdfObject obj = getPdfObjectRelease(stream.get(PdfName.LENGTH));
if (obj != null && obj.type() == PdfObject.NUMBER) {
streamLength = ((PdfNumber)obj).intValue();
if (streamLength + start > fileLength - 20)
calc = true;
else {
tokens.seek(start + streamLength);
String line = tokens.readString(20);
if (!line.startsWith("\nendstream") &&
!line.startsWith("\r\nendstream") &&
!line.startsWith("\rendstream") &&
!line.startsWith("endstream"))
calc = true;
}
}
else
calc = true;
if (calc) {
byte tline[] = new byte[16];
tokens.seek(start);
while (true) {
long pos = tokens.getFilePointer();
if (!tokens.readLineSegment(tline))
break;
if (equalsn(tline, endstream)) {
streamLength = pos - start;
break;
}
if (equalsn(tline, endobj)) {
tokens.seek(pos - 16);
String s = tokens.readString(16);
int index = s.indexOf("endstream");
if (index >= 0)
pos = pos - 16 + index;
streamLength = pos - start;
break;
}
}
}
stream.setLength((int)streamLength);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected void readObjStm(final PRStream stream, final IntHashtable map) throws IOException {
int first = stream.getAsNumber(PdfName.FIRST).intValue();
int n = stream.getAsNumber(PdfName.N).intValue();
byte b[] = getStreamBytes(stream, tokens.getFile());
PRTokeniser saveTokens = tokens;
tokens = new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(b)));
try {
int address[] = new int[n];
int objNumber[] = new int[n];
boolean ok = true;
for (int k = 0; k < n; ++k) {
ok = tokens.nextToken();
if (!ok)
break;
if (tokens.getTokenType() != TokenType.NUMBER) {
ok = false;
break;
}
objNumber[k] = tokens.intValue();
ok = tokens.nextToken();
if (!ok)
break;
if (tokens.getTokenType() != TokenType.NUMBER) {
ok = false;
break;
}
address[k] = tokens.intValue() + first;
}
if (!ok)
throw new InvalidPdfException(MessageLocalization.getComposedMessage("error.reading.objstm"));
for (int k = 0; k < n; ++k) {
if (map.containsKey(k)) {
tokens.seek(address[k]);
tokens.nextToken();
PdfObject obj;
if (tokens.getTokenType() == PRTokeniser.TokenType.NUMBER) {
obj = new PdfNumber(tokens.getStringValue());
}
else {
tokens.seek(address[k]);
obj = readPRObject();
}
xrefObj.set(objNumber[k], obj);
}
}
}
finally {
tokens = saveTokens;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected void readXref() throws IOException {
hybridXref = false;
newXrefType = false;
tokens.seek(tokens.getStartxref());
tokens.nextToken();
if (!tokens.getStringValue().equals("startxref"))
throw new InvalidPdfException(MessageLocalization.getComposedMessage("startxref.not.found"));
tokens.nextToken();
if (tokens.getTokenType() != TokenType.NUMBER)
throw new InvalidPdfException(MessageLocalization.getComposedMessage("startxref.is.not.followed.by.a.number"));
long startxref = tokens.longValue();
lastXref = startxref;
eofPos = tokens.getFilePointer();
try {
if (readXRefStream(startxref)) {
newXrefType = true;
return;
}
}
catch (Exception e) {}
xref = null;
tokens.seek(startxref);
trailer = readXrefSection();
PdfDictionary trailer2 = trailer;
while (true) {
PdfNumber prev = (PdfNumber)trailer2.get(PdfName.PREV);
if (prev == null)
break;
tokens.seek(prev.longValue());
trailer2 = readXrefSection();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected PdfDictionary readXrefSection() throws IOException {
tokens.nextValidToken();
if (!tokens.getStringValue().equals("xref"))
tokens.throwError(MessageLocalization.getComposedMessage("xref.subsection.not.found"));
int start = 0;
int end = 0;
long pos = 0;
int gen = 0;
while (true) {
tokens.nextValidToken();
if (tokens.getStringValue().equals("trailer"))
break;
if (tokens.getTokenType() != TokenType.NUMBER)
tokens.throwError(MessageLocalization.getComposedMessage("object.number.of.the.first.object.in.this.xref.subsection.not.found"));
start = tokens.intValue();
tokens.nextValidToken();
if (tokens.getTokenType() != TokenType.NUMBER)
tokens.throwError(MessageLocalization.getComposedMessage("number.of.entries.in.this.xref.subsection.not.found"));
end = tokens.intValue() + start;
if (start == 1) { // fix incorrect start number
long back = tokens.getFilePointer();
tokens.nextValidToken();
pos = tokens.longValue();
tokens.nextValidToken();
gen = tokens.intValue();
if (pos == 0 && gen == PdfWriter.GENERATION_MAX) {
--start;
--end;
}
tokens.seek(back);
}
ensureXrefSize(end * 2);
for (int k = start; k < end; ++k) {
tokens.nextValidToken();
pos = tokens.longValue();
tokens.nextValidToken();
gen = tokens.intValue();
tokens.nextValidToken();
int p = k * 2;
if (tokens.getStringValue().equals("n")) {
if (xref[p] == 0 && xref[p + 1] == 0) {
// if (pos == 0)
// tokens.throwError(MessageLocalization.getComposedMessage("file.position.0.cross.reference.entry.in.this.xref.subsection"));
xref[p] = pos;
}
}
else if (tokens.getStringValue().equals("f")) {
if (xref[p] == 0 && xref[p + 1] == 0)
xref[p] = -1;
}
else
tokens.throwError(MessageLocalization.getComposedMessage("invalid.cross.reference.entry.in.this.xref.subsection"));
}
}
PdfDictionary trailer = (PdfDictionary)readPRObject();
PdfNumber xrefSize = (PdfNumber)trailer.get(PdfName.SIZE);
ensureXrefSize(xrefSize.intValue() * 2);
PdfObject xrs = trailer.get(PdfName.XREFSTM);
if (xrs != null && xrs.isNumber()) {
int loc = ((PdfNumber)xrs).intValue();
try {
readXRefStream(loc);
newXrefType = true;
hybridXref = true;
}
catch (IOException e) {
xref = null;
throw e;
}
}
return trailer;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected boolean readXRefStream(final long ptr) throws IOException {
tokens.seek(ptr);
int thisStream = 0;
if (!tokens.nextToken())
return false;
if (tokens.getTokenType() != TokenType.NUMBER)
return false;
thisStream = tokens.intValue();
if (!tokens.nextToken() || tokens.getTokenType() != TokenType.NUMBER)
return false;
if (!tokens.nextToken() || !tokens.getStringValue().equals("obj"))
return false;
PdfObject object = readPRObject();
PRStream stm = null;
if (object.isStream()) {
stm = (PRStream)object;
if (!PdfName.XREF.equals(stm.get(PdfName.TYPE)))
return false;
}
else
return false;
if (trailer == null) {
trailer = new PdfDictionary();
trailer.putAll(stm);
}
stm.setLength(((PdfNumber)stm.get(PdfName.LENGTH)).intValue());
int size = ((PdfNumber)stm.get(PdfName.SIZE)).intValue();
PdfArray index;
PdfObject obj = stm.get(PdfName.INDEX);
if (obj == null) {
index = new PdfArray();
index.add(new int[]{0, size});
}
else
index = (PdfArray)obj;
PdfArray w = (PdfArray)stm.get(PdfName.W);
long prev = -1;
obj = stm.get(PdfName.PREV);
if (obj != null)
prev = ((PdfNumber)obj).longValue();
// Each xref pair is a position
// type 0 -> -1, 0
// type 1 -> offset, 0
// type 2 -> index, obj num
ensureXrefSize(size * 2);
if (objStmMark == null && !partial)
objStmMark = new HashMap<Integer, IntHashtable>();
if (objStmToOffset == null && partial)
objStmToOffset = new LongHashtable();
byte b[] = getStreamBytes(stm, tokens.getFile());
int bptr = 0;
int wc[] = new int[3];
for (int k = 0; k < 3; ++k)
wc[k] = w.getAsNumber(k).intValue();
for (int idx = 0; idx < index.size(); idx += 2) {
int start = index.getAsNumber(idx).intValue();
int length = index.getAsNumber(idx + 1).intValue();
ensureXrefSize((start + length) * 2);
while (length-- > 0) {
int type = 1;
if (wc[0] > 0) {
type = 0;
for (int k = 0; k < wc[0]; ++k)
type = (type << 8) + (b[bptr++] & 0xff);
}
long field2 = 0;
for (int k = 0; k < wc[1]; ++k)
field2 = (field2 << 8) + (b[bptr++] & 0xff);
int field3 = 0;
for (int k = 0; k < wc[2]; ++k)
field3 = (field3 << 8) + (b[bptr++] & 0xff);
int base = start * 2;
if (xref[base] == 0 && xref[base + 1] == 0) {
switch (type) {
case 0:
xref[base] = -1;
break;
case 1:
xref[base] = field2;
break;
case 2:
xref[base] = field3;
xref[base + 1] = field2;
if (partial) {
objStmToOffset.put(field2, 0);
}
else {
Integer on = Integer.valueOf((int)field2);
IntHashtable seq = objStmMark.get(on);
if (seq == null) {
seq = new IntHashtable();
seq.put(field3, 1);
objStmMark.put(on, seq);
}
else
seq.put(field3, 1);
}
break;
}
}
++start;
}
}
thisStream *= 2;
if (thisStream + 1 < xref.length && xref[thisStream] == 0 && xref[thisStream + 1] == 0)
xref[thisStream] = -1;
if (prev == -1)
return true;
return readXRefStream(prev);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected void rebuildXref() throws IOException {
hybridXref = false;
newXrefType = false;
tokens.seek(0);
long xr[][] = new long[1024][];
long top = 0;
trailer = null;
byte line[] = new byte[64];
for (;;) {
long pos = tokens.getFilePointer();
if (!tokens.readLineSegment(line))
break;
if (line[0] == 't') {
if (!PdfEncodings.convertToString(line, null).startsWith("trailer"))
continue;
tokens.seek(pos);
tokens.nextToken();
pos = tokens.getFilePointer();
try {
PdfDictionary dic = (PdfDictionary)readPRObject();
if (dic.get(PdfName.ROOT) != null)
trailer = dic;
else
tokens.seek(pos);
}
catch (Exception e) {
tokens.seek(pos);
}
}
else if (line[0] >= '0' && line[0] <= '9') {
long obj[] = PRTokeniser.checkObjectStart(line);
if (obj == null)
continue;
long num = obj[0];
long gen = obj[1];
if (num >= xr.length) {
long newLength = num * 2;
long xr2[][] = new long[(int)newLength][];
System.arraycopy(xr, 0, xr2, 0, (int)top);
xr = xr2;
}
if (num >= top)
top = num + 1;
if (xr[(int)num] == null || gen >= xr[(int)num][1]) {
obj[0] = pos;
xr[(int)num] = obj;
}
}
}
if (trailer == null)
throw new InvalidPdfException(MessageLocalization.getComposedMessage("trailer.not.found"));
xref = new long[(int)(top * 2)];
for (int k = 0; k < top; ++k) {
long obj[] = xr[k];
if (obj != null)
xref[k * 2] = obj[0];
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected PdfDictionary readDictionary() throws IOException {
PdfDictionary dic = new PdfDictionary();
while (true) {
tokens.nextValidToken();
if (tokens.getTokenType() == TokenType.END_DIC)
break;
if (tokens.getTokenType() != TokenType.NAME)
tokens.throwError(MessageLocalization.getComposedMessage("dictionary.key.is.not.a.name"));
PdfName name = new PdfName(tokens.getStringValue(), false);
PdfObject obj = readPRObject();
int type = obj.type();
if (-type == TokenType.END_DIC.ordinal())
tokens.throwError(MessageLocalization.getComposedMessage("unexpected.gt.gt"));
if (-type == TokenType.END_ARRAY.ordinal())
tokens.throwError(MessageLocalization.getComposedMessage("unexpected.close.bracket"));
dic.put(name, obj);
}
return dic;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected PdfArray readArray() throws IOException {
PdfArray array = new PdfArray();
while (true) {
PdfObject obj = readPRObject();
int type = obj.type();
if (-type == TokenType.END_ARRAY.ordinal())
break;
if (-type == TokenType.END_DIC.ordinal())
tokens.throwError(MessageLocalization.getComposedMessage("unexpected.gt.gt"));
array.add(obj);
}
return array;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
protected PdfObject readPRObject() throws IOException {
tokens.nextValidToken();
TokenType type = tokens.getTokenType();
switch (type) {
case START_DIC: {
++readDepth;
PdfDictionary dic = readDictionary();
--readDepth;
long pos = tokens.getFilePointer();
// be careful in the trailer. May not be a "next" token.
boolean hasNext;
do {
hasNext = tokens.nextToken();
} while (hasNext && tokens.getTokenType() == TokenType.COMMENT);
if (hasNext && tokens.getStringValue().equals("stream")) {
//skip whitespaces
int ch;
do {
ch = tokens.read();
} while (ch == 32 || ch == 9 || ch == 0 || ch == 12);
if (ch != '\n')
ch = tokens.read();
if (ch != '\n')
tokens.backOnePosition(ch);
PRStream stream = new PRStream(this, tokens.getFilePointer());
stream.putAll(dic);
// crypto handling
stream.setObjNum(objNum, objGen);
return stream;
}
else {
tokens.seek(pos);
return dic;
}
}
case START_ARRAY: {
++readDepth;
PdfArray arr = readArray();
--readDepth;
return arr;
}
case NUMBER:
return new PdfNumber(tokens.getStringValue());
case STRING:
PdfString str = new PdfString(tokens.getStringValue(), null).setHexWriting(tokens.isHexString());
// crypto handling
str.setObjNum(objNum, objGen);
if (strings != null)
strings.add(str);
return str;
case NAME: {
PdfName cachedName = PdfName.staticNames.get( tokens.getStringValue() );
if (readDepth > 0 && cachedName != null) {
return cachedName;
} else {
// an indirect name (how odd...), or a non-standard one
return new PdfName(tokens.getStringValue(), false);
}
}
case REF:
int num = tokens.getReference();
PRIndirectReference ref = new PRIndirectReference(this, num, tokens.getGeneration());
return ref;
case ENDOFFILE:
throw new IOException(MessageLocalization.getComposedMessage("unexpected.end.of.file"));
default:
String sv = tokens.getStringValue();
if ("null".equals(sv)) {
if (readDepth == 0) {
return new PdfNull();
} //else
return PdfNull.PDFNULL;
}
else if ("true".equals(sv)) {
if (readDepth == 0) {
return new PdfBoolean( true );
} //else
return PdfBoolean.PDFTRUE;
}
else if ("false".equals(sv)) {
if (readDepth == 0) {
return new PdfBoolean( false );
} //else
return PdfBoolean.PDFFALSE;
}
return new PdfLiteral(-type.ordinal(), tokens.getStringValue());
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public byte[] getPageContent(final int pageNum, final RandomAccessFileOrArray file) throws IOException{
PdfDictionary page = getPageNRelease(pageNum);
if (page == null)
return null;
PdfObject contents = getPdfObjectRelease(page.get(PdfName.CONTENTS));
if (contents == null)
return new byte[0];
ByteArrayOutputStream bout = null;
if (contents.isStream()) {
return getStreamBytes((PRStream)contents, file);
}
else if (contents.isArray()) {
PdfArray array = (PdfArray)contents;
bout = new ByteArrayOutputStream();
for (int k = 0; k < array.size(); ++k) {
PdfObject item = getPdfObjectRelease(array.getPdfObject(k));
if (item == null || !item.isStream())
continue;
byte[] b = getStreamBytes((PRStream)item, file);
bout.write(b);
if (k != array.size() - 1)
bout.write('\n');
}
return bout.toByteArray();
}
else
return new byte[0];
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] getPageContent(final PdfDictionary page) throws IOException{
if (page == null)
return null;
RandomAccessFileOrArray rf = null;
try {
PdfObject contents = getPdfObjectRelease(page.get(PdfName.CONTENTS));
if (contents == null)
return new byte[0];
if (contents.isStream()) {
if (rf == null) {
rf = ((PRStream)contents).getReader().getSafeFile();
rf.reOpen();
}
return getStreamBytes((PRStream)contents, rf);
}
else if (contents.isArray()) {
PdfArray array = (PdfArray)contents;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
for (int k = 0; k < array.size(); ++k) {
PdfObject item = getPdfObjectRelease(array.getPdfObject(k));
if (item == null || !item.isStream())
continue;
if (rf == null) {
rf = ((PRStream)item).getReader().getSafeFile();
rf.reOpen();
}
byte[] b = getStreamBytes((PRStream)item, rf);
bout.write(b);
if (k != array.size() - 1)
bout.write('\n');
}
return bout.toByteArray();
}
else
return new byte[0];
}
finally {
try {
if (rf != null)
rf.close();
}catch(Exception e){}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public byte[] getPageContent(final int pageNum) throws IOException{
RandomAccessFileOrArray rf = getSafeFile();
try {
rf.reOpen();
return getPageContent(pageNum, rf);
}
finally {
try{rf.close();}catch(Exception e){}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] decodeBytes(byte[] b, final PdfDictionary streamDictionary) throws IOException {
return decodeBytes(b, streamDictionary, FilterHandlers.getDefaultFilterHandlers());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] decodeBytes(byte[] b, final PdfDictionary streamDictionary, Map<PdfName, FilterHandlers.FilterHandler> filterHandlers) throws IOException {
PdfObject filter = getPdfObjectRelease(streamDictionary.get(PdfName.FILTER));
ArrayList<PdfObject> filters = new ArrayList<PdfObject>();
if (filter != null) {
if (filter.isName())
filters.add(filter);
else if (filter.isArray())
filters = ((PdfArray)filter).getArrayList();
}
ArrayList<PdfObject> dp = new ArrayList<PdfObject>();
PdfObject dpo = getPdfObjectRelease(streamDictionary.get(PdfName.DECODEPARMS));
if (dpo == null || !dpo.isDictionary() && !dpo.isArray())
dpo = getPdfObjectRelease(streamDictionary.get(PdfName.DP));
if (dpo != null) {
if (dpo.isDictionary())
dp.add(dpo);
else if (dpo.isArray())
dp = ((PdfArray)dpo).getArrayList();
}
for (int j = 0; j < filters.size(); ++j) {
PdfName filterName = (PdfName)filters.get(j);
FilterHandlers.FilterHandler filterHandler = filterHandlers.get(filterName);
if (filterHandler == null)
throw new UnsupportedPdfException(MessageLocalization.getComposedMessage("the.filter.1.is.not.supported", filterName));
PdfDictionary decodeParams;
if (j < dp.size()){
PdfObject dpEntry = getPdfObject(dp.get(j));
if (dpEntry instanceof PdfDictionary){
decodeParams = (PdfDictionary)dpEntry;
} else if (dpEntry == null || dpEntry instanceof PdfNull) {
decodeParams = null;
} else {
throw new UnsupportedPdfException(MessageLocalization.getComposedMessage("the.decode.parameter.type.1.is.not.supported", dpEntry.getClass().toString()));
}
} else {
decodeParams = null;
}
b = filterHandler.decode(b, filterName, decodeParams, streamDictionary);
}
return b;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] getStreamBytes(final PRStream stream, final RandomAccessFileOrArray file) throws IOException {
byte[] b = getStreamBytesRaw(stream, file);
return decodeBytes(b, stream);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] getStreamBytes(final PRStream stream) throws IOException {
RandomAccessFileOrArray rf = stream.getReader().getSafeFile();
try {
rf.reOpen();
return getStreamBytes(stream, rf);
}
finally {
try{rf.close();}catch(Exception e){}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] getStreamBytesRaw(final PRStream stream, final RandomAccessFileOrArray file) throws IOException {
PdfReader reader = stream.getReader();
byte b[];
if (stream.getOffset() < 0)
b = stream.getBytes();
else {
b = new byte[stream.getLength()];
file.seek(stream.getOffset());
file.readFully(b);
PdfEncryption decrypt = reader.getDecrypt();
if (decrypt != null) {
PdfObject filter = getPdfObjectRelease(stream.get(PdfName.FILTER));
ArrayList<PdfObject> filters = new ArrayList<PdfObject>();
if (filter != null) {
if (filter.isName())
filters.add(filter);
else if (filter.isArray())
filters = ((PdfArray)filter).getArrayList();
}
boolean skip = false;
for (int k = 0; k < filters.size(); ++k) {
PdfObject obj = getPdfObjectRelease(filters.get(k));
if (obj != null && obj.toString().equals("/Crypt")) {
skip = true;
break;
}
}
if (!skip) {
decrypt.setHashKey(stream.getObjNum(), stream.getObjGen());
b = decrypt.decryptByteArray(b);
}
}
}
return b;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] getStreamBytesRaw(final PRStream stream) throws IOException {
RandomAccessFileOrArray rf = stream.getReader().getSafeFile();
try {
rf.reOpen();
return getStreamBytesRaw(stream, rf);
}
finally {
try{rf.close();}catch(Exception e){}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public byte[] getMetadata() throws IOException {
PdfObject obj = getPdfObject(catalog.get(PdfName.METADATA));
if (!(obj instanceof PRStream))
return null;
RandomAccessFileOrArray rf = getSafeFile();
byte b[] = null;
try {
rf.reOpen();
b = getStreamBytes((PRStream)obj, rf);
}
finally {
try {
rf.close();
}
catch (Exception e) {
// empty on purpose
}
}
return b;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public String getJavaScript(final RandomAccessFileOrArray file) throws IOException {
PdfDictionary names = (PdfDictionary)getPdfObjectRelease(catalog.get(PdfName.NAMES));
if (names == null)
return null;
PdfDictionary js = (PdfDictionary)getPdfObjectRelease(names.get(PdfName.JAVASCRIPT));
if (js == null)
return null;
HashMap<String, PdfObject> jscript = PdfNameTree.readTree(js);
String sortedNames[] = new String[jscript.size()];
sortedNames = jscript.keySet().toArray(sortedNames);
Arrays.sort(sortedNames);
StringBuffer buf = new StringBuffer();
for (int k = 0; k < sortedNames.length; ++k) {
PdfDictionary j = (PdfDictionary)getPdfObjectRelease(jscript.get(sortedNames[k]));
if (j == null)
continue;
PdfObject obj = getPdfObjectRelease(j.get(PdfName.JS));
if (obj != null) {
if (obj.isString())
buf.append(((PdfString)obj).toUnicodeString()).append('\n');
else if (obj.isStream()) {
byte bytes[] = getStreamBytes((PRStream)obj, file);
if (bytes.length >= 2 && bytes[0] == (byte)254 && bytes[1] == (byte)255)
buf.append(PdfEncodings.convertToString(bytes, PdfObject.TEXT_UNICODE));
else
buf.append(PdfEncodings.convertToString(bytes, PdfObject.TEXT_PDFDOCENCODING));
buf.append('\n');
}
}
}
return buf.toString();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public String getJavaScript() throws IOException {
RandomAccessFileOrArray rf = getSafeFile();
try {
rf.reOpen();
return getJavaScript(rf);
}
finally {
try{rf.close();}catch(Exception e){}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
void readPages() throws IOException {
if (refsn != null)
return;
refsp = null;
refsn = new ArrayList<PRIndirectReference>();
pageInh = new ArrayList<PdfDictionary>();
iteratePages((PRIndirectReference)reader.catalog.get(PdfName.PAGES));
pageInh = null;
reader.rootPages.put(PdfName.COUNT, new PdfNumber(refsn.size()));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
void reReadPages() throws IOException {
refsn = null;
readPages();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
private void iteratePages(final PRIndirectReference rpage) throws IOException {
PdfDictionary page = (PdfDictionary)getPdfObject(rpage);
if (page == null)
return;
PdfArray kidsPR = page.getAsArray(PdfName.KIDS);
// reference to a leaf
if (kidsPR == null) {
page.put(PdfName.TYPE, PdfName.PAGE);
PdfDictionary dic = pageInh.get(pageInh.size() - 1);
PdfName key;
for (Object element : dic.getKeys()) {
key = (PdfName)element;
if (page.get(key) == null)
page.put(key, dic.get(key));
}
if (page.get(PdfName.MEDIABOX) == null) {
PdfArray arr = new PdfArray(new float[]{0,0,PageSize.LETTER.getRight(),PageSize.LETTER.getTop()});
page.put(PdfName.MEDIABOX, arr);
}
refsn.add(rpage);
}
// reference to a branch
else {
page.put(PdfName.TYPE, PdfName.PAGES);
pushPageAttributes(page);
for (int k = 0; k < kidsPR.size(); ++k){
PdfObject obj = kidsPR.getPdfObject(k);
if (!obj.isIndirect()) {
while (k < kidsPR.size())
kidsPR.remove(k);
break;
}
iteratePages((PRIndirectReference)obj);
}
popPageAttributes();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDashPattern.java
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {
os.write('[');
if (dash >= 0) {
new PdfNumber(dash).toPdf(writer, os);
if (gap >= 0) {
os.write(' ');
new PdfNumber(gap).toPdf(writer, os);
}
}
os.write(']');
if (phase >=0) {
os.write(' ');
new PdfNumber(phase).toPdf(writer, os);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public static void setXfa(XfaForm form, PdfReader reader, PdfWriter writer) throws IOException {
PdfDictionary af = (PdfDictionary)PdfReader.getPdfObjectRelease(reader.getCatalog().get(PdfName.ACROFORM));
if (af == null) {
return;
}
PdfObject xfa = getXfaObject(reader);
if (xfa.isArray()) {
PdfArray ar = (PdfArray)xfa;
int t = -1;
int d = -1;
for (int k = 0; k < ar.size(); k += 2) {
PdfString s = ar.getAsString(k);
if ("template".equals(s.toString())) {
t = k + 1;
}
if ("datasets".equals(s.toString())) {
d = k + 1;
}
}
if (t > -1 && d > -1) {
reader.killXref(ar.getAsIndirectObject(t));
reader.killXref(ar.getAsIndirectObject(d));
PdfStream tStream = new PdfStream(serializeDoc(form.templateNode));
tStream.flateCompress(writer.getCompressionLevel());
ar.set(t, writer.addToBody(tStream).getIndirectReference());
PdfStream dStream = new PdfStream(serializeDoc(form.datasetsNode));
dStream.flateCompress(writer.getCompressionLevel());
ar.set(d, writer.addToBody(dStream).getIndirectReference());
af.put(PdfName.XFA, new PdfArray(ar));
return;
}
}
reader.killXref(af.get(PdfName.XFA));
PdfStream str = new PdfStream(serializeDoc(form.domDocument));
str.flateCompress(writer.getCompressionLevel());
PdfIndirectReference ref = writer.addToBody(str).getIndirectReference();
af.put(PdfName.XFA, ref);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public void setXfa(PdfWriter writer) throws IOException {
setXfa(this, reader, writer);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public static byte[] serializeDoc(Node n) throws IOException {
XmlDomWriter xw = new XmlDomWriter();
ByteArrayOutputStream fout = new ByteArrayOutputStream();
xw.setOutput(fout, null);
xw.setCanonical(false);
xw.write(n);
fout.close();
return fout.toByteArray();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public void fillXfaForm(File file) throws IOException {
fillXfaForm(file, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public void fillXfaForm(File file, boolean readOnly) throws IOException {
fillXfaForm(new FileInputStream(file), readOnly);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public void fillXfaForm(InputStream is) throws IOException {
fillXfaForm(is, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public void fillXfaForm(InputStream is, boolean readOnly) throws IOException {
fillXfaForm(new InputSource(is), readOnly);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public void fillXfaForm(InputSource is) throws IOException {
fillXfaForm(is, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public void fillXfaForm(InputSource is, boolean readOnly) throws IOException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
Document newdoc = db.parse(is);
fillXfaForm(newdoc.getDocumentElement(), readOnly);
} catch (ParserConfigurationException e) {
throw new ExceptionConverter(e);
} catch (SAXException e) {
throw new ExceptionConverter(e);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
public static BaseFont createFont() throws DocumentException, IOException {
return createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
public static BaseFont createFont(String name, String encoding, boolean embedded) throws DocumentException, IOException {
return createFont(name, encoding, embedded, true, null, null, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
public static BaseFont createFont(String name, String encoding, boolean embedded, boolean forceRead) throws DocumentException, IOException {
return createFont(name, encoding, embedded, true, null, null, forceRead);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
public static BaseFont createFont(String name, String encoding, boolean embedded, boolean cached, byte ttfAfm[], byte pfb[]) throws DocumentException, IOException {
return createFont(name, encoding, embedded, cached, ttfAfm, pfb, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
public static BaseFont createFont(String name, String encoding, boolean embedded, boolean cached, byte ttfAfm[], byte pfb[], boolean noThrow) throws DocumentException, IOException {
return createFont(name, encoding, embedded, cached, ttfAfm, pfb, noThrow, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
public static BaseFont createFont(String name, String encoding, boolean embedded, boolean cached, byte ttfAfm[], byte pfb[], boolean noThrow, boolean forceRead) throws DocumentException, IOException {
String nameBase = getBaseName(name);
encoding = normalizeEncoding(encoding);
boolean isBuiltinFonts14 = BuiltinFonts14.containsKey(name);
boolean isCJKFont = isBuiltinFonts14 ? false : CJKFont.isCJKFont(nameBase, encoding);
if (isBuiltinFonts14 || isCJKFont)
embedded = false;
else if (encoding.equals(IDENTITY_H) || encoding.equals(IDENTITY_V))
embedded = true;
BaseFont fontFound = null;
BaseFont fontBuilt = null;
String key = name + "\n" + encoding + "\n" + embedded;
if (cached) {
synchronized (fontCache) {
fontFound = fontCache.get(key);
}
if (fontFound != null)
return fontFound;
}
if (isBuiltinFonts14 || name.toLowerCase().endsWith(".afm") || name.toLowerCase().endsWith(".pfm")) {
fontBuilt = new Type1Font(name, encoding, embedded, ttfAfm, pfb, forceRead);
fontBuilt.fastWinansi = encoding.equals(CP1252);
}
else if (nameBase.toLowerCase().endsWith(".ttf") || nameBase.toLowerCase().endsWith(".otf") || nameBase.toLowerCase().indexOf(".ttc,") > 0) {
if (encoding.equals(IDENTITY_H) || encoding.equals(IDENTITY_V))
fontBuilt = new TrueTypeFontUnicode(name, encoding, embedded, ttfAfm, forceRead);
else {
fontBuilt = new TrueTypeFont(name, encoding, embedded, ttfAfm, false, forceRead);
fontBuilt.fastWinansi = encoding.equals(CP1252);
}
}
else if (isCJKFont)
fontBuilt = new CJKFont(name, encoding, embedded);
else if (noThrow)
return null;
else
throw new DocumentException(MessageLocalization.getComposedMessage("font.1.with.2.is.not.recognized", name, encoding));
if (cached) {
synchronized (fontCache) {
fontFound = fontCache.get(key);
if (fontFound != null)
return fontFound;
fontCache.put(key, fontBuilt);
}
}
return fontBuilt;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
public static String[][] getFullFontName(String name, String encoding, byte ttfAfm[]) throws DocumentException, IOException {
String nameBase = getBaseName(name);
BaseFont fontBuilt = null;
if (nameBase.toLowerCase().endsWith(".ttf") || nameBase.toLowerCase().endsWith(".otf") || nameBase.toLowerCase().indexOf(".ttc,") > 0)
fontBuilt = new TrueTypeFont(name, CP1252, false, ttfAfm, true, false);
else
fontBuilt = createFont(name, encoding, false, false, ttfAfm, null);
return fontBuilt.getFullFontName();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
public static Object[] getAllFontNames(String name, String encoding, byte ttfAfm[]) throws DocumentException, IOException {
String nameBase = getBaseName(name);
BaseFont fontBuilt = null;
if (nameBase.toLowerCase().endsWith(".ttf") || nameBase.toLowerCase().endsWith(".otf") || nameBase.toLowerCase().indexOf(".ttc,") > 0)
fontBuilt = new TrueTypeFont(name, CP1252, false, ttfAfm, true, false);
else
fontBuilt = createFont(name, encoding, false, false, ttfAfm, null);
return new Object[]{fontBuilt.getPostscriptFontName(), fontBuilt.getFamilyFontName(), fontBuilt.getFullFontName()};
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
public static String[][] getAllNameEntries(String name, String encoding, byte ttfAfm[]) throws DocumentException, IOException {
String nameBase = getBaseName(name);
BaseFont fontBuilt = null;
if (nameBase.toLowerCase().endsWith(".ttf") || nameBase.toLowerCase().endsWith(".otf") || nameBase.toLowerCase().indexOf(".ttc,") > 0)
fontBuilt = new TrueTypeFont(name, CP1252, false, ttfAfm, true, false);
else
fontBuilt = createFont(name, encoding, false, false, ttfAfm, null);
return fontBuilt.getAllNameEntries();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
public static String[] enumerateTTCNames(String ttcFile) throws DocumentException, IOException {
return new EnumerateTTC(ttcFile).getNames();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
public static String[] enumerateTTCNames(byte ttcArray[]) throws DocumentException, IOException {
return new EnumerateTTC(ttcArray).getNames();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFontSubset.java
public byte[] Process(String fontName)throws IOException{
try
{
// Verify that the file is open
buf.reOpen();
// Find the Font that we will be dealing with
int j;
for (j=0; j<fonts.length; j++)
if (fontName.equals(fonts[j].name)) break;
if (j==fonts.length) return null;
// Calc the bias for the global subrs
if (gsubrIndexOffset >= 0)
GBias = CalcBias(gsubrIndexOffset,j);
// Prepare the new CharStrings Index
BuildNewCharString(j);
// Prepare the new Global and Local Subrs Indices
BuildNewLGSubrs(j);
// Build the new file
byte[] Ret = BuildNewFile(j);
return Ret;
}
finally {
try {
buf.close();
}
catch (Exception e) {
// empty on purpose
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFontSubset.java
protected void BuildNewCharString(int FontIndex) throws IOException
{
NewCharStringsIndex = BuildNewIndex(fonts[FontIndex].charstringsOffsets,GlyphsUsed,ENDCHAR_OP);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFontSubset.java
protected byte[] BuildNewIndex(int[] Offsets,HashMap<Integer, int[]> Used,byte OperatorForUnusedEntries) throws IOException
{
int unusedCount = 0;
int Offset=0;
int[] NewOffsets = new int[Offsets.length];
// Build the Offsets Array for the Subset
for (int i=0;i<Offsets.length;++i)
{
NewOffsets[i] = Offset;
// If the object in the offset is also present in the used
// HashMap then increment the offset var by its size
if (Used.containsKey(Integer.valueOf(i))) {
Offset += Offsets[i+1] - Offsets[i];
} else {
// Else the same offset is kept in i+1.
unusedCount++;
}
}
// Offset var determines the size of the object array
byte[] NewObjects = new byte[Offset+unusedCount];
// Build the new Object array
int unusedOffset = 0;
for (int i=0;i<Offsets.length-1;++i)
{
int start = NewOffsets[i];
int end = NewOffsets[i+1];
NewOffsets[i] = start+unusedOffset;
// If start != End then the Object is used
// So, we will copy the object data from the font file
if (start != end)
{
// All offsets are Global Offsets relative to the beginning of the font file.
// Jump the file pointer to the start address to read from.
buf.seek(Offsets[i]);
// Read from the buffer and write into the array at start.
buf.readFully(NewObjects, start+unusedOffset, end-start);
} else {
NewObjects[start+unusedOffset] = OperatorForUnusedEntries;
unusedOffset++;
}
}
NewOffsets[Offsets.length-1] += unusedOffset;
// Use AssembleIndex to build the index from the offset & object arrays
return AssembleIndex(NewOffsets,NewObjects);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryptor.java
public static void encrypt(PdfReader reader, OutputStream os, byte userPassword[], byte ownerPassword[], int permissions, boolean strength128Bits) throws DocumentException, IOException {
PdfStamper stamper = new PdfStamper(reader, os);
stamper.setEncryption(userPassword, ownerPassword, permissions, strength128Bits);
stamper.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryptor.java
public static void encrypt(PdfReader reader, OutputStream os, byte userPassword[], byte ownerPassword[], int permissions, boolean strength128Bits, HashMap<String, String> newInfo) throws DocumentException, IOException {
PdfStamper stamper = new PdfStamper(reader, os);
stamper.setEncryption(userPassword, ownerPassword, permissions, strength128Bits);
stamper.setMoreInfo(newInfo);
stamper.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryptor.java
public static void encrypt(PdfReader reader, OutputStream os, boolean strength, String userPassword, String ownerPassword, int permissions) throws DocumentException, IOException {
PdfStamper stamper = new PdfStamper(reader, os);
stamper.setEncryption(strength, userPassword, ownerPassword, permissions);
stamper.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryptor.java
public static void encrypt(PdfReader reader, OutputStream os, boolean strength, String userPassword, String ownerPassword, int permissions, HashMap<String, String> newInfo) throws DocumentException, IOException {
PdfStamper stamper = new PdfStamper(reader, os);
stamper.setEncryption(strength, userPassword, ownerPassword, permissions);
stamper.setMoreInfo(newInfo);
stamper.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryptor.java
public static void encrypt(PdfReader reader, OutputStream os, int type, String userPassword, String ownerPassword, int permissions, HashMap<String, String> newInfo) throws DocumentException, IOException {
PdfStamper stamper = new PdfStamper(reader, os);
stamper.setEncryption(type, userPassword, ownerPassword, permissions);
stamper.setMoreInfo(newInfo);
stamper.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryptor.java
public static void encrypt(PdfReader reader, OutputStream os, int type, String userPassword, String ownerPassword, int permissions) throws DocumentException, IOException {
PdfStamper stamper = new PdfStamper(reader, os);
stamper.setEncryption(type, userPassword, ownerPassword, permissions);
stamper.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfArray.java
Override
public void toPdf(final PdfWriter writer, final OutputStream os) throws IOException {
os.write('[');
Iterator<PdfObject> i = arrayList.iterator();
PdfObject object;
int type = 0;
if (i.hasNext()) {
object = i.next();
if (object == null)
object = PdfNull.PDFNULL;
object.toPdf(writer, os);
}
while (i.hasNext()) {
object = i.next();
if (object == null)
object = PdfNull.PDFNULL;
type = object.type();
if (type != PdfObject.ARRAY && type != PdfObject.DICTIONARY && type != PdfObject.NAME && type != PdfObject.STRING)
os.write(' ');
object.toPdf(writer, os);
}
os.write(']');
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CompareTool.java
public String compare(String outPath, String differenceImage) throws IOException, InterruptedException {
if (gsExec == null || gsExec.length() == 0) {
return undefinedGsPath;
}
File targetDir = new File(outPath);
File[] imageFiles;
File[] cmpImageFiles;
if (!targetDir.exists()) {
targetDir.mkdir();
} else {
imageFiles = targetDir.listFiles(new PngFileFilter());
for (File file : imageFiles) {
file.delete();
}
cmpImageFiles = targetDir.listFiles(new CmpPngFileFilter());
for (File file : cmpImageFiles) {
file.delete();
}
}
File diffFile = new File(differenceImage);
if (diffFile.exists()) {
diffFile.delete();
}
if (targetDir.exists()) {
String gsParams = this.gsParams.replace("<outputfile>", outPath + cmpImage).replace("<inputfile>", cmpPdf);
Process p = Runtime.getRuntime().exec(gsExec + gsParams);
BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line;
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
if (p.waitFor() == 0) {
gsParams = this.gsParams.replace("<outputfile>", outPath + outImage).replace("<inputfile>", outPdf);
p = Runtime.getRuntime().exec(gsExec + gsParams);
bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = bri.readLine()) != null) {
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
int exitValue = p.waitFor();
if (exitValue == 0) {
imageFiles = targetDir.listFiles(new PngFileFilter());
cmpImageFiles = targetDir.listFiles(new CmpPngFileFilter());
boolean bUnexpectedNumberOfPages = false;
if (imageFiles.length != cmpImageFiles.length) {
bUnexpectedNumberOfPages = true;
}
int cnt = Math.min(imageFiles.length, cmpImageFiles.length);
if (cnt < 1) {
return "No files for comparing!!!\nThe result or sample pdf file is not processed by GhostScript.";
}
Arrays.sort(imageFiles, new ImageNameComparator());
Arrays.sort(cmpImageFiles, new ImageNameComparator());
String differentPagesFail = null;
for (int i = 0; i < cnt; i++) {
System.out.print("Comparing page " + Integer.toString(i + 1) + " (" + imageFiles[i].getAbsolutePath() + ")...");
FileInputStream is1 = new FileInputStream(imageFiles[i]);
FileInputStream is2 = new FileInputStream(cmpImageFiles[i]);
boolean cmpResult = compareStreams(is1, is2);
is1.close();
is2.close();
if (!cmpResult) {
if (compareExec != null && compareExec.length() > 0) {
String compareParams = this.compareParams.replace("<image1>", imageFiles[i].getAbsolutePath()).replace("<image2>", cmpImageFiles[i].getAbsolutePath()).replace("<difference>", differenceImage + Integer.toString(i + 1) + ".png");
p = Runtime.getRuntime().exec(compareExec + compareParams);
bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = bre.readLine()) != null) {
System.out.println(line);
}
bre.close();
int cmpExitValue = p.waitFor();
if (cmpExitValue == 0) {
if (differentPagesFail == null) {
differentPagesFail = differentPages.replace("<filename>", outPdf).replace("<pagenumber>", Integer.toString(i + 1));
differentPagesFail += "\nPlease, examine " + differenceImage + Integer.toString(i + 1) + ".png for more details.";
} else {
differentPagesFail =
"File " + outPdf + " differs.\nPlease, examine difference images for more details.";
}
} else {
differentPagesFail = differentPages.replace("<filename>", outPdf).replace("<pagenumber>", Integer.toString(i + 1));
}
} else {
differentPagesFail = differentPages.replace("<filename>", outPdf).replace("<pagenumber>", Integer.toString(i + 1));
differentPagesFail += "\nYou can optionally specify path to ImageMagick compare tool (e.g. -DcompareExec=\"C:/Program Files/ImageMagick-6.5.4-2/compare.exe\") to visualize differences.";
break;
}
System.out.println(differentPagesFail);
} else {
System.out.println("done.");
}
}
if (differentPagesFail != null) {
return differentPagesFail;
} else {
if (bUnexpectedNumberOfPages)
return unexpectedNumberOfPages.replace("<filename>", outPdf) + "\n" + differentPagesFail;
}
} else {
return gsFailed.replace("<filename>", outPdf);
}
} else {
return gsFailed.replace("<filename>", cmpPdf);
}
} else {
return cannotOpenTargetDirectory.replace("<filename>", outPdf);
}
return null;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CompareTool.java
public String compare(String outPdf, String cmpPdf, String outPath, String differenceImage) throws IOException, InterruptedException {
init(outPdf, cmpPdf);
return compare(outPath, differenceImage);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CompareTool.java
private boolean compareStreams(InputStream is1, InputStream is2) throws IOException {
byte[] buffer1 = new byte[64 * 1024];
byte[] buffer2 = new byte[64 * 1024];
int len1 = 0;
int len2 = 0;
for (; ;) {
len1 = is1.read(buffer1);
len2 = is2.read(buffer2);
if (len1 != len2)
return false;
if (!Arrays.equals(buffer1, buffer2))
return false;
if (len1 == -1 || len2 == -1)
break;
}
return true;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
private void restoreColor(BaseColor color, boolean fill) throws IOException {
if (isTagged()) {
if (color instanceof UncoloredPattern) {
UncoloredPattern c = (UncoloredPattern)color;
if (fill)
setPatternFill(c.getPainter(), c.color, c.tint);
else
setPatternStroke(c.getPainter(), c.color, c.tint);
} else {
if (fill)
setColorFill(color);
else
setColorStroke(color);
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
private void restoreColor() throws IOException {
if (isTagged()) {
if (inText) {
if (!state.textColorFill.equals(state.graphicsColorFill)) {
restoreColor(state.textColorFill, true);
}
if (!state.textColorStroke.equals(state.graphicsColorStroke)) {
restoreColor(state.textColorStroke, false);
}
} else {
if (!state.textColorFill.equals(state.graphicsColorFill)) {
restoreColor(state.graphicsColorFill, true);
}
if (!state.textColorStroke.equals(state.graphicsColorStroke)) {
restoreColor(state.graphicsColorStroke, false);
}
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
public void setXmpMetadata(final byte[] xmpMetadata) throws IOException {
PdfStream xmp = new PdfStream(xmpMetadata);
xmp.put(PdfName.TYPE, PdfName.METADATA);
xmp.put(PdfName.SUBTYPE, PdfName.XML);
PdfEncryption crypto = writer.getEncryption();
if (crypto != null && !crypto.isMetadataEncrypted()) {
PdfArray ar = new PdfArray();
ar.add(PdfName.CRYPT);
xmp.put(PdfName.FILTER, ar);
}
writer.addPageDictEntry(PdfName.METADATA, writer.addToBody(xmp).getIndirectReference());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void writeOutlines() throws IOException {
if (rootOutline.getKids().size() == 0)
return;
outlineTree(rootOutline);
writer.addToBody(rootOutline, rootOutline.indirectReference());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void outlineTree(final PdfOutline outline) throws IOException {
outline.setIndirectReference(writer.getPdfIndirectReference());
if (outline.parent() != null)
outline.put(PdfName.PARENT, outline.parent().indirectReference());
ArrayList<PdfOutline> kids = outline.getKids();
int size = kids.size();
for (int k = 0; k < size; ++k)
outlineTree(kids.get(k));
for (int k = 0; k < size; ++k) {
if (k > 0)
kids.get(k).put(PdfName.PREV, kids.get(k - 1).indirectReference());
if (k < size - 1)
kids.get(k).put(PdfName.NEXT, kids.get(k + 1).indirectReference());
}
if (size > 0) {
outline.put(PdfName.FIRST, kids.get(0).indirectReference());
outline.put(PdfName.LAST, kids.get(size - 1).indirectReference());
}
for (int k = 0; k < size; ++k) {
PdfOutline kid = kids.get(k);
writer.addToBody(kid, kid.indirectReference());
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addFileAttachment(String description, final PdfFileSpecification fs) throws IOException {
if (description == null) {
PdfString desc = (PdfString)fs.get(PdfName.DESC);
if (desc == null) {
description = "";
}
else {
description = PdfEncodings.convertToString(desc.getBytes(), null);
}
}
fs.addDescription(description, true);
if (description.length() == 0)
description = "Unnamed";
String fn = PdfEncodings.convertToString(new PdfString(description, PdfObject.TEXT_UNICODE).getBytes(), null);
int k = 0;
while (documentFileAttachment.containsKey(fn)) {
++k;
fn = PdfEncodings.convertToString(new PdfString(description + " " + k, PdfObject.TEXT_UNICODE).getBytes(), null);
}
documentFileAttachment.put(fn, fs.getReference());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEFStream.java
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {
if (inputStream != null && compressed)
put(PdfName.FILTER, PdfName.FLATEDECODE);
PdfEncryption crypto = null;
if (writer != null)
crypto = writer.getEncryption();
if (crypto != null) {
PdfObject filter = get(PdfName.FILTER);
if (filter != null) {
if (PdfName.CRYPT.equals(filter))
crypto = null;
else if (filter.isArray()) {
PdfArray a = (PdfArray)filter;
if (!a.isEmpty() && PdfName.CRYPT.equals(a.getPdfObject(0)))
crypto = null;
}
}
}
if (crypto != null && crypto.isEmbeddedFilesOnly()) {
PdfArray filter = new PdfArray();
PdfArray decodeparms = new PdfArray();
PdfDictionary crypt = new PdfDictionary();
crypt.put(PdfName.NAME, PdfName.STDCF);
filter.add(PdfName.CRYPT);
decodeparms.add(crypt);
if (compressed) {
filter.add(PdfName.FLATEDECODE);
decodeparms.add(new PdfNull());
}
put(PdfName.FILTER, filter);
put(PdfName.DECODEPARMS, decodeparms);
}
PdfObject nn = get(PdfName.LENGTH);
if (crypto != null && nn != null && nn.isNumber()) {
int sz = ((PdfNumber)nn).intValue();
put(PdfName.LENGTH, new PdfNumber(crypto.calculateStreamSize(sz)));
superToPdf(writer, os);
put(PdfName.LENGTH, nn);
}
else
superToPdf(writer, os);
os.write(STARTSTREAM);
if (inputStream != null) {
rawLength = 0;
DeflaterOutputStream def = null;
OutputStreamCounter osc = new OutputStreamCounter(os);
OutputStreamEncryption ose = null;
OutputStream fout = osc;
if (crypto != null)
fout = ose = crypto.getEncryptionStream(fout);
Deflater deflater = null;
if (compressed) {
deflater = new Deflater(compressionLevel);
fout = def = new DeflaterOutputStream(fout, deflater, 0x8000);
}
byte buf[] = new byte[4192];
while (true) {
int n = inputStream.read(buf);
if (n <= 0)
break;
fout.write(buf, 0, n);
rawLength += n;
}
if (def != null) {
def.finish();
deflater.end();
}
if (ose != null)
ose.finish();
inputStreamLength = (int)osc.getCounter();
}
else {
if (crypto == null) {
if (streamBytes != null)
streamBytes.writeTo(os);
else
os.write(bytes);
}
else {
byte b[];
if (streamBytes != null) {
b = crypto.encryptByteArray(streamBytes.toByteArray());
}
else {
b = crypto.encryptByteArray(bytes);
}
os.write(b);
}
}
os.write(ENDSTREAM);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentParser.java
public ArrayList<PdfObject> parse(ArrayList<PdfObject> ls) throws IOException {
if (ls == null)
ls = new ArrayList<PdfObject>();
else
ls.clear();
PdfObject ob = null;
while ((ob = readPRObject()) != null) {
ls.add(ob);
if (ob.type() == COMMAND_TYPE)
break;
}
return ls;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentParser.java
public PdfDictionary readDictionary() throws IOException {
PdfDictionary dic = new PdfDictionary();
while (true) {
if (!nextValidToken())
throw new IOException(MessageLocalization.getComposedMessage("unexpected.end.of.file"));
if (tokeniser.getTokenType() == TokenType.END_DIC)
break;
if (tokeniser.getTokenType() == TokenType.OTHER && "def".equals(tokeniser.getStringValue()))
continue;
if (tokeniser.getTokenType() != TokenType.NAME)
throw new IOException(MessageLocalization.getComposedMessage("dictionary.key.is.not.a.name"));
PdfName name = new PdfName(tokeniser.getStringValue(), false);
PdfObject obj = readPRObject();
int type = obj.type();
if (-type == TokenType.END_DIC.ordinal())
throw new IOException(MessageLocalization.getComposedMessage("unexpected.gt.gt"));
if (-type == TokenType.END_ARRAY.ordinal())
throw new IOException(MessageLocalization.getComposedMessage("unexpected.close.bracket"));
dic.put(name, obj);
}
return dic;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentParser.java
public PdfArray readArray() throws IOException {
PdfArray array = new PdfArray();
while (true) {
PdfObject obj = readPRObject();
int type = obj.type();
if (-type == TokenType.END_ARRAY.ordinal())
break;
if (-type == TokenType.END_DIC.ordinal())
throw new IOException(MessageLocalization.getComposedMessage("unexpected.gt.gt"));
array.add(obj);
}
return array;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentParser.java
public PdfObject readPRObject() throws IOException {
if (!nextValidToken())
return null;
TokenType type = tokeniser.getTokenType();
switch (type) {
case START_DIC: {
PdfDictionary dic = readDictionary();
return dic;
}
case START_ARRAY:
return readArray();
case STRING:
PdfString str = new PdfString(tokeniser.getStringValue(), null).setHexWriting(tokeniser.isHexString());
return str;
case NAME:
return new PdfName(tokeniser.getStringValue(), false);
case NUMBER:
return new PdfNumber(tokeniser.getStringValue());
case OTHER:
return new PdfLiteral(COMMAND_TYPE, tokeniser.getStringValue());
default:
return new PdfLiteral(-type.ordinal(), tokeniser.getStringValue());
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentParser.java
public boolean nextValidToken() throws IOException {
while (tokeniser.nextToken()) {
if (tokeniser.getTokenType() == TokenType.COMMENT)
continue;
return true;
}
return false;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
protected PdfIndirectReference copyIndirect(PRIndirectReference in, boolean keepStructure, boolean directRootKids) throws IOException, BadPdfFormatException {
PdfIndirectReference theRef;
RefKey key = new RefKey(in);
IndirectReferences iRef = indirects.get(key);
PdfObject obj = PdfReader.getPdfObjectRelease(in);
if ((keepStructure) && (directRootKids))
if (obj instanceof PdfDictionary) {
PdfDictionary dict = (PdfDictionary) obj;
if (dict.contains(PdfName.PG))
return null;
}
if (iRef != null) {
theRef = iRef.getRef();
if (iRef.getCopied()) {
return theRef;
}
}
else {
theRef = body.getPdfIndirectReference();
iRef = new IndirectReferences(theRef);
indirects.put(key, iRef);
}
if (obj != null && obj.isDictionary()) {
PdfObject type = PdfReader.getPdfObjectRelease(((PdfDictionary)obj).get(PdfName.TYPE));
if (type != null && PdfName.PAGE.equals(type)) {
return theRef;
}
}
iRef.setCopied();
parentObjects.put(obj, in);
PdfObject res = copyObject(obj, keepStructure, directRootKids);
if (disableIndirects.contains(obj))
iRef.setNotCopied();
if ((res != null) && !(res instanceof PdfNull))
{
addToBody(res, theRef);
return theRef;
}
else {
indirects.remove(key);
return null;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
protected PdfIndirectReference copyIndirect(PRIndirectReference in) throws IOException, BadPdfFormatException {
return copyIndirect(in, false, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
protected PdfDictionary copyDictionary(PdfDictionary in, boolean keepStruct, boolean directRootKids)
throws IOException, BadPdfFormatException {
PdfDictionary out = new PdfDictionary();
PdfObject type = PdfReader.getPdfObjectRelease(in.get(PdfName.TYPE));
if (keepStruct)
{
if ((directRootKids) && (in.contains(PdfName.PG)))
{
PdfObject curr = in;
disableIndirects.add(curr);
while (parentObjects.containsKey(curr) && !(disableIndirects.contains(curr))) {
curr = parentObjects.get(curr);
disableIndirects.add(curr);
}
return null;
}
PdfName structType = in.getAsName(PdfName.S);
structTreeController.addRole(structType);
structTreeController.addClass(in);
}
for (Object element : in.getKeys()) {
PdfName key = (PdfName)element;
PdfObject value = in.get(key);
if (structTreeController != null && structTreeController.reader != null && key.equals(PdfName.STRUCTPARENTS)) {
out.put(key, new PdfNumber(currentStructArrayNumber));
structTreeController.copyStructTreeForPage((PdfNumber)value, currentStructArrayNumber++);
continue;
}
if (type != null && PdfName.PAGE.equals(type)) {
if (!key.equals(PdfName.B) && !key.equals(PdfName.PARENT)) {
parentObjects.put(value, in);
PdfObject res = copyObject(value, keepStruct, directRootKids);
if ((res != null) && !(res instanceof PdfNull))
out.put(key, res);
}
}
else {
PdfObject res;
if (tagged && value.isIndirect() && isStructTreeRootReference((PRIndirectReference)value)) {
res = structureTreeRoot.getReference();
} else {
res = copyObject(value, keepStruct, directRootKids);
}
if ((res != null) && !(res instanceof PdfNull))
out.put(key, res);
}
}
return out;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
protected PdfDictionary copyDictionary(PdfDictionary in)
throws IOException, BadPdfFormatException {
return copyDictionary(in, false, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
protected PdfStream copyStream(PRStream in) throws IOException, BadPdfFormatException {
PRStream out = new PRStream(in, null);
for (Object element : in.getKeys()) {
PdfName key = (PdfName) element;
PdfObject value = in.get(key);
parentObjects.put(value, in);
PdfObject res = copyObject(value);
if ((res != null) && !(res instanceof PdfNull))
out.put(key, res);
}
return out;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
protected PdfArray copyArray(PdfArray in, boolean keepStruct, boolean directRootKids) throws IOException, BadPdfFormatException {
PdfArray out = new PdfArray();
for (Iterator<PdfObject> i = in.listIterator(); i.hasNext();) {
PdfObject value = i.next();
parentObjects.put(value, in);
PdfObject res = copyObject(value, keepStruct, directRootKids);
if ((res != null) && !(res instanceof PdfNull))
out.add(res);
}
return out;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
protected PdfArray copyArray(PdfArray in) throws IOException, BadPdfFormatException {
return copyArray(in, false, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
protected PdfObject copyObject(PdfObject in, boolean keepStruct, boolean directRootKids) throws IOException,BadPdfFormatException {
if (in == null)
return PdfNull.PDFNULL;
switch (in.type) {
case PdfObject.DICTIONARY:
return copyDictionary((PdfDictionary)in, keepStruct, directRootKids);
case PdfObject.INDIRECT:
if (!keepStruct && !directRootKids)
// fix for PdfSmartCopy
return copyIndirect((PRIndirectReference)in);
else
return copyIndirect((PRIndirectReference)in, keepStruct, directRootKids);
case PdfObject.ARRAY:
return copyArray((PdfArray)in, keepStruct, directRootKids);
case PdfObject.NUMBER:
case PdfObject.NAME:
case PdfObject.STRING:
case PdfObject.NULL:
case PdfObject.BOOLEAN:
case 0://PdfIndirectReference
return in;
case PdfObject.STREAM:
return copyStream((PRStream)in);
// return in;
default:
if (in.type < 0) {
String lit = ((PdfLiteral)in).toString();
if (lit.equals("true") || lit.equals("false")) {
return new PdfBoolean(lit);
}
return new PdfLiteral(lit);
}
System.out.println("CANNOT COPY type " + in.type);
return null;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
protected PdfObject copyObject(PdfObject in) throws IOException,BadPdfFormatException {
return copyObject(in, false, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
public void addPage(PdfImportedPage iPage) throws IOException, BadPdfFormatException {
int pageNum = setFromIPage(iPage);
PdfDictionary thePage = reader.getPageN(pageNum);
PRIndirectReference origRef = reader.getPageOrigRef(pageNum);
reader.releasePage(pageNum);
RefKey key = new RefKey(origRef);
PdfIndirectReference pageRef;
IndirectReferences iRef = indirects.get(key);
if (iRef != null && !iRef.getCopied()) {
pageReferences.add(iRef.getRef());
iRef.setCopied();
}
pageRef = getCurrentPage();
if (iRef == null) {
iRef = new IndirectReferences(pageRef);
indirects.put(key, iRef);
}
iRef.setCopied();
if (tagged)
structTreeRootReference = (PRIndirectReference)reader.getCatalog().get(PdfName.STRUCTTREEROOT);
PdfDictionary newPage = copyDictionary(thePage);
root.addPage(newPage);
iPage.setCopied();
++currentPageNumber;
structTreeRootReference = null;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
Override
public PdfIndirectObject addToBody(final PdfObject object, final PdfIndirectReference ref) throws IOException {
if (tagged && indirectObjects != null && (object.isArray() || object.isDictionary())) {
RefKey key = new RefKey(ref);
PdfIndirectObject obj = indirectObjects.get(key);
if (obj == null) {
obj = new PdfIndirectObject(ref, object, this);
indirectObjects.put(key, obj);
}
return obj;
} else {
if (tagged && object.isStream()) streams.add(new RefKey(ref));
return super.addToBody(object, ref);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
Override
public PdfIndirectObject addToBody(final PdfObject object) throws IOException {
PdfIndirectObject iobj = super.addToBody(object);
if (tagged && indirectObjects != null) {
savedObjects.add(iobj);
RefKey key = new RefKey(iobj.number, iobj.generation);
if (!indirectObjects.containsKey(key)) indirectObjects.put(key, iobj);
}
return iobj;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
Override
protected void flushTaggedObjects() throws IOException {
try {
fixTaggedStructure();
} catch (ClassCastException ex) {
} finally {flushIndirectObjects();}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
protected void fixTaggedStructure() throws IOException {
HashMap<Integer, PdfIndirectReference> numTree = structureTreeRoot.getNumTree();
HashSet<PdfCopy.RefKey> activeKeys = new HashSet<PdfCopy.RefKey>();
ArrayList<PdfIndirectReference> actives = new ArrayList<PdfIndirectReference>();
if (pageReferences.size() == numTree.size()) {
//from end, because some objects can appear on several pages because of MCR (out16.pdf)
for (int i = numTree.size() - 1; i >= 0; --i) {
PdfIndirectReference currNum = numTree.get(i);
PdfCopy.RefKey numKey = new PdfCopy.RefKey(currNum);
activeKeys.add(numKey);
actives.add(currNum);
PdfObject obj = indirectObjects.get(numKey).object;
PdfArray currNums = (PdfArray)obj;
PdfIndirectReference currPage = pageReferences.get(i);
actives.add(currPage);
activeKeys.add(new RefKey(currPage));
PdfIndirectReference prevKid = null;
for (int j = 0; j < currNums.size(); j++) {
PdfIndirectReference currKid = (PdfIndirectReference)currNums.getDirectObject(j);
if (currKid.equals(prevKid)) continue;
PdfCopy.RefKey kidKey = new PdfCopy.RefKey(currKid);
activeKeys.add(kidKey);
actives.add(currKid);
PdfIndirectObject iobj = indirectObjects.get(kidKey);
if (iobj.object.isDictionary()) {
PdfDictionary dict = (PdfDictionary)iobj.object;
PdfIndirectReference pg = (PdfIndirectReference)dict.get(PdfName.PG);
//if pg is real page - do nothing, else set correct pg and remove first MCID if exists
if (!pageReferences.contains(pg) && !pg.equals(currPage)){
dict.put(PdfName.PG, currPage);
PdfArray kids = dict.getAsArray(PdfName.K);
if (kids != null) {
PdfObject firstKid = kids.getDirectObject(0);
if (firstKid.isNumber()) kids.remove(0);
}
}
}
prevKid = currKid;
}
}
} else return;//invalid tagged document -> flush all objects
HashSet<PdfName> activeClassMaps = new HashSet<PdfName>();
//collect all active objects from current active set (include kids, classmap, attributes)
findActives(actives, activeKeys, activeClassMaps);
//find parents of active objects
ArrayList<PdfIndirectReference> newRefs = findActiveParents(activeKeys);
//find new objects with incorrect Pg; if find, set Pg from first correct kid. This correct kid must be.
fixPgKey(newRefs, activeKeys);
//remove unused kids of StructTreeRoot and remove unused objects from class map
fixStructureTreeRoot(activeKeys, activeClassMaps);
for(Map.Entry<PdfCopy.RefKey, PdfIndirectObject> entry: indirectObjects.entrySet()) {
if (!activeKeys.contains(entry.getKey())) {
entry.setValue(null);
}
else {
if (entry.getValue().object.isArray()) {
removeInactiveReferences((PdfArray)entry.getValue().object, activeKeys);
} else if (entry.getValue().object.isDictionary()) {
PdfObject kids = ((PdfDictionary)entry.getValue().object).get(PdfName.K);
if (kids != null && kids.isArray())
removeInactiveReferences((PdfArray)kids, activeKeys);
}
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
protected void flushIndirectObjects() throws IOException {
for (PdfIndirectObject iobj: savedObjects)
indirectObjects.remove(new PdfCopy.RefKey(iobj.number, iobj.generation));
HashSet<RefKey> inactives = new HashSet<RefKey>();
for(Map.Entry<RefKey, PdfIndirectObject> entry: indirectObjects.entrySet()) {
if (entry.getValue() != null) body.write(entry.getValue(), entry.getValue().number);
else inactives.add(entry.getKey());
}
ArrayList<PdfBody.PdfCrossReference> pdfCrossReferences = new ArrayList<PdfBody.PdfCrossReference>(body.xrefs);
for (PdfBody.PdfCrossReference cr : pdfCrossReferences) {
RefKey key = new RefKey(cr.getRefnum(), 0);
if (inactives.contains(key)) body.xrefs.remove(cr);
}
indirectObjects = null;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
public void copyAcroForm(PdfReader reader) throws IOException, BadPdfFormatException {
setFromReader(reader);
PdfDictionary catalog = reader.getCatalog();
PRIndirectReference hisRef = null;
PdfObject o = catalog.get(PdfName.ACROFORM);
if (o != null && o.type() == PdfObject.INDIRECT)
hisRef = (PRIndirectReference)o;
if (hisRef == null) return; // bugfix by John Englar
RefKey key = new RefKey(hisRef);
PdfIndirectReference myRef;
IndirectReferences iRef = indirects.get(key);
if (iRef != null) {
acroForm = myRef = iRef.getRef();
}
else {
acroForm = myRef = body.getPdfIndirectReference();
iRef = new IndirectReferences(myRef);
indirects.put(key, iRef);
}
if (! iRef.getCopied()) {
iRef.setCopied();
PdfDictionary theForm = copyDictionary((PdfDictionary)PdfReader.getPdfObject(hisRef));
addToBody(theForm, myRef);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
private void addFieldResources(PdfDictionary catalog) throws IOException {
if (fieldArray == null)
return;
PdfDictionary acroForm = new PdfDictionary();
catalog.put(PdfName.ACROFORM, acroForm);
acroForm.put(PdfName.FIELDS, fieldArray);
acroForm.put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g "));
if (fieldTemplates.isEmpty())
return;
PdfDictionary dr = new PdfDictionary();
acroForm.put(PdfName.DR, dr);
for (PdfTemplate template: fieldTemplates) {
PdfFormField.mergeResources(dr, (PdfDictionary)template.getResources());
}
// if (dr.get(PdfName.ENCODING) == null) dr.put(PdfName.ENCODING, PdfName.WIN_ANSI_ENCODING);
PdfDictionary fonts = dr.getAsDict(PdfName.FONT);
if (fonts == null) {
fonts = new PdfDictionary();
dr.put(PdfName.FONT, fonts);
}
if (!fonts.contains(PdfName.HELV)) {
PdfDictionary dic = new PdfDictionary(PdfName.FONT);
dic.put(PdfName.BASEFONT, PdfName.HELVETICA);
dic.put(PdfName.ENCODING, PdfName.WIN_ANSI_ENCODING);
dic.put(PdfName.NAME, PdfName.HELV);
dic.put(PdfName.SUBTYPE, PdfName.TYPE1);
fonts.put(PdfName.HELV, addToBody(dic).getIndirectReference());
}
if (!fonts.contains(PdfName.ZADB)) {
PdfDictionary dic = new PdfDictionary(PdfName.FONT);
dic.put(PdfName.BASEFONT, PdfName.ZAPFDINGBATS);
dic.put(PdfName.NAME, PdfName.ZADB);
dic.put(PdfName.SUBTYPE, PdfName.TYPE1);
fonts.put(PdfName.ZADB, addToBody(dic).getIndirectReference());
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
Override
public void freeReader(PdfReader reader) throws IOException {
indirectMap.remove(reader);
// TODO: Removed - the user should be responsible for closing all PdfReaders. But, this could cause a lot of memory leaks in code out there that hasn't been properly closing things - maybe add a finalizer to PdfReader that calls PdfReader#close() ??
// if (currentPdfReaderInstance != null) {
// if (currentPdfReaderInstance.getReader() == reader) {
// try {
// currentPdfReaderInstance.getReader().close();
// currentPdfReaderInstance.getReaderFile().close();
// }
// catch (IOException ioe) {
// // empty on purpose
// }
currentPdfReaderInstance = null;
// }
// }
super.freeReader(reader);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
public void alterContents() throws IOException {
if (over == null && under == null)
return;
PdfArray ar = null;
PdfObject content = PdfReader.getPdfObject(pageN.get(PdfName.CONTENTS), pageN);
if (content == null) {
ar = new PdfArray();
pageN.put(PdfName.CONTENTS, ar);
} else if (content.isArray()) {
ar = (PdfArray)content;
} else if (content.isStream()) {
ar = new PdfArray();
ar.add(pageN.get(PdfName.CONTENTS));
pageN.put(PdfName.CONTENTS, ar);
} else {
ar = new PdfArray();
pageN.put(PdfName.CONTENTS, ar);
}
ByteBuffer out = new ByteBuffer();
if (under != null) {
out.append(PdfContents.SAVESTATE);
applyRotation(pageN, out);
out.append(under.getInternalBuffer());
out.append(PdfContents.RESTORESTATE);
}
if (over != null)
out.append(PdfContents.SAVESTATE);
PdfStream stream = new PdfStream(out.toByteArray());
stream.flateCompress(cstp.getCompressionLevel());
PdfIndirectReference ref1 = cstp.addToBody(stream).getIndirectReference();
ar.addFirst(ref1);
out.reset();
if (over != null) {
out.append(' ');
out.append(PdfContents.RESTORESTATE);
out.append(PdfContents.SAVESTATE);
applyRotation(pageN, out);
out.append(over.getInternalBuffer());
out.append(PdfContents.RESTORESTATE);
stream = new PdfStream(out.toByteArray());
stream.flateCompress(cstp.getCompressionLevel());
ar.add(cstp.addToBody(stream).getIndirectReference());
}
pageN.put(PdfName.RESOURCES, pageResources.getResources());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfConcatenate.java
public int addPages(PdfReader reader) throws DocumentException, IOException {
open();
int n = reader. getNumberOfPages();
for (int i = 1; i <= n; i++) {
copy.addPage(copy.getImportedPage(reader, i));
}
copy.freeReader(reader);
reader.close();
return n;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFileSpecification.java
public static PdfFileSpecification fileEmbedded(PdfWriter writer, String filePath, String fileDisplay, byte fileStore[]) throws IOException {
return fileEmbedded(writer, filePath, fileDisplay, fileStore, PdfStream.BEST_COMPRESSION);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFileSpecification.java
public static PdfFileSpecification fileEmbedded(PdfWriter writer, String filePath, String fileDisplay, byte fileStore[], int compressionLevel) throws IOException {
return fileEmbedded(writer, filePath, fileDisplay, fileStore, null, null, compressionLevel);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFileSpecification.java
public static PdfFileSpecification fileEmbedded(PdfWriter writer, String filePath, String fileDisplay, byte fileStore[], boolean compress) throws IOException {
return fileEmbedded(writer, filePath, fileDisplay, fileStore, null, null, compress ? PdfStream.BEST_COMPRESSION : PdfStream.NO_COMPRESSION);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFileSpecification.java
public static PdfFileSpecification fileEmbedded(PdfWriter writer, String filePath, String fileDisplay, byte fileStore[], boolean compress, String mimeType, PdfDictionary fileParameter) throws IOException {
return fileEmbedded(writer, filePath, fileDisplay, fileStore, mimeType, fileParameter, compress ? PdfStream.BEST_COMPRESSION : PdfStream.NO_COMPRESSION);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFileSpecification.java
public static PdfFileSpecification fileEmbedded(PdfWriter writer, String filePath, String fileDisplay, byte fileStore[], String mimeType, PdfDictionary fileParameter, int compressionLevel) throws IOException {
PdfFileSpecification fs = new PdfFileSpecification();
fs.writer = writer;
fs.put(PdfName.F, new PdfString(fileDisplay));
fs.setUnicodeFileName(fileDisplay, false);
PdfEFStream stream;
InputStream in = null;
PdfIndirectReference ref;
PdfIndirectReference refFileLength = null;
try {
if (fileStore == null) {
refFileLength = writer.getPdfIndirectReference();
File file = new File(filePath);
if (file.canRead()) {
in = new FileInputStream(filePath);
}
else {
if (filePath.startsWith("file:/") || filePath.startsWith("http://") || filePath.startsWith("https://") || filePath.startsWith("jar:")) {
in = new URL(filePath).openStream();
}
else {
in = BaseFont.getResourceStream(filePath);
if (in == null)
throw new IOException(MessageLocalization.getComposedMessage("1.not.found.as.file.or.resource", filePath));
}
}
stream = new PdfEFStream(in, writer);
}
else {
stream = new PdfEFStream(fileStore);
}
stream.put(PdfName.TYPE, PdfName.EMBEDDEDFILE);
stream.flateCompress(compressionLevel);
PdfDictionary param = new PdfDictionary();
if (fileParameter != null) {
param.merge(fileParameter);
}
if (fileStore != null) {
param.put(PdfName.SIZE, new PdfNumber(stream.getRawLength()));
stream.put(PdfName.PARAMS, param);
}
else
stream.put(PdfName.PARAMS, refFileLength);
if (mimeType != null)
stream.put(PdfName.SUBTYPE, new PdfName(mimeType));
ref = writer.addToBody(stream).getIndirectReference();
if (fileStore == null) {
stream.writeLength();
param.put(PdfName.SIZE, new PdfNumber(stream.getRawLength()));
writer.addToBody(param, refFileLength);
}
}
finally {
if (in != null)
try{in.close();}catch(Exception e){}
}
PdfDictionary f = new PdfDictionary();
f.put(PdfName.F, ref);
f.put(PdfName.UF, ref);
fs.put(PdfName.EF, f);
return fs;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFileSpecification.java
public PdfIndirectReference getReference() throws IOException {
if (ref != null)
return ref;
ref = writer.addToBody(this).getIndirectReference();
return ref;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfIndirectObject.java
protected void writeTo(OutputStream os) throws IOException
{
os.write(DocWriter.getISOBytes(String.valueOf(number)));
os.write(' ');
os.write(DocWriter.getISOBytes(String.valueOf(generation)));
os.write(STARTOBJ);
object.toPdf(writer, os);
os.write(ENDOBJ);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Pfm2afm.java
public static void convert(RandomAccessFileOrArray in, OutputStream out) throws IOException {
Pfm2afm p = new Pfm2afm(in, out);
p.openpfm();
p.putheader();
p.putchartab();
p.putkerntab();
p.puttrailer();
p.out.flush();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Pfm2afm.java
private String readString(int n) throws IOException {
byte b[] = new byte[n];
in.readFully(b);
int k;
for (k = 0; k < b.length; ++k) {
if (b[k] == 0)
break;
}
return new String(b, 0, k, "ISO-8859-1");
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Pfm2afm.java
private String readString() throws IOException {
StringBuffer buf = new StringBuffer();
while (true) {
int c = in.read();
if (c <= 0)
break;
buf.append((char)c);
}
return buf.toString();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Pfm2afm.java
private void openpfm() throws IOException {
in.seek(0);
vers = in.readShortLE();
h_len = in.readIntLE();
copyright = readString(60);
type = in.readShortLE();
points = in.readShortLE();
verres = in.readShortLE();
horres = in.readShortLE();
ascent = in.readShortLE();
intleading = in.readShortLE();
extleading = in.readShortLE();
italic = (byte)in.read();
uline = (byte)in.read();
overs = (byte)in.read();
weight = in.readShortLE();
charset = (byte)in.read();
pixwidth = in.readShortLE();
pixheight = in.readShortLE();
kind = (byte)in.read();
avgwidth = in.readShortLE();
maxwidth = in.readShortLE();
firstchar = in.read();
lastchar = in.read();
defchar = (byte)in.read();
brkchar = (byte)in.read();
widthby = in.readShortLE();
device = in.readIntLE();
face = in.readIntLE();
bits = in.readIntLE();
bitoff = in.readIntLE();
extlen = in.readShortLE();
psext = in.readIntLE();
chartab = in.readIntLE();
res1 = in.readIntLE();
kernpairs = in.readIntLE();
res2 = in.readIntLE();
fontname = in.readIntLE();
if (h_len != in.length() || extlen != 30 || fontname < 75 || fontname > 512)
throw new IOException(MessageLocalization.getComposedMessage("not.a.valid.pfm.file"));
in.seek(psext + 14);
capheight = in.readShortLE();
xheight = in.readShortLE();
ascender = in.readShortLE();
descender = in.readShortLE();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Pfm2afm.java
private void putheader() throws IOException {
out.print("StartFontMetrics 2.0\n");
if (copyright.length() > 0)
out.print("Comment " + copyright + '\n');
out.print("FontName ");
in.seek(fontname);
String fname = readString();
out.print(fname);
out.print("\nEncodingScheme ");
if (charset != 0)
out.print("FontSpecific\n");
else
out.print("AdobeStandardEncoding\n");
/*
* The .pfm is missing full name, so construct from font name by
* changing the hyphen to a space. This actually works in a lot
* of cases.
*/
out.print("FullName " + fname.replace('-', ' '));
if (face != 0) {
in.seek(face);
out.print("\nFamilyName " + readString());
}
out.print("\nWeight ");
if (weight > 475 || fname.toLowerCase().indexOf("bold") >= 0)
out.print("Bold");
else if ((weight < 325 && weight != 0) || fname.toLowerCase().indexOf("light") >= 0)
out.print("Light");
else if (fname.toLowerCase().indexOf("black") >= 0)
out.print("Black");
else
out.print("Medium");
out.print("\nItalicAngle ");
if (italic != 0 || fname.toLowerCase().indexOf("italic") >= 0)
out.print("-12.00");
/* this is a typical value; something else may work better for a
specific font */
else
out.print("0");
/*
* The mono flag in the pfm actually indicates whether there is a
* table of font widths, not if they are all the same.
*/
out.print("\nIsFixedPitch ");
if ((kind & 1) == 0 || /* Flag for mono */
avgwidth == maxwidth ) { /* Avg width = max width */
out.print("true");
isMono = true;
}
else {
out.print("false");
isMono = false;
}
/*
* The font bounding box is lost, but try to reconstruct it.
* Much of this is just guess work. The bounding box is required in
* the .afm, but is not used by the PM font installer.
*/
out.print("\nFontBBox");
if (isMono)
outval(-20); /* Just guess at left bounds */
else
outval(-100);
outval(-(descender+5)); /* Descender is given as positive value */
outval(maxwidth+10);
outval(ascent+5);
/*
* Give other metrics that were kept
*/
out.print("\nCapHeight");
outval(capheight);
out.print("\nXHeight");
outval(xheight);
out.print("\nDescender");
outval(-descender);
out.print("\nAscender");
outval(ascender);
out.print('\n');
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Pfm2afm.java
private void putchartab() throws IOException {
int count = lastchar - firstchar + 1;
int ctabs[] = new int[count];
in.seek(chartab);
for (int k = 0; k < count; ++k)
ctabs[k] = in.readUnsignedShortLE();
int back[] = new int[256];
if (charset == 0) {
for (int i = firstchar; i <= lastchar; ++i) {
if (Win2PSStd[i] != 0)
back[Win2PSStd[i]] = i;
}
}
/* Put out the header */
out.print("StartCharMetrics");
outval(count);
out.print('\n');
/* Put out all encoded chars */
if (charset != 0) {
/*
* If the charset is not the Windows standard, just put out
* unnamed entries.
*/
for (int i = firstchar; i <= lastchar; i++) {
if (ctabs[i - firstchar] != 0) {
outchar(i, ctabs[i - firstchar], null);
}
}
}
else {
for (int i = 0; i < 256; i++) {
int j = back[i];
if (j != 0) {
outchar(i, ctabs[j - firstchar], WinChars[j]);
ctabs[j - firstchar] = 0;
}
}
/* Put out all non-encoded chars */
for (int i = firstchar; i <= lastchar; i++) {
if (ctabs[i - firstchar] != 0) {
outchar(-1, ctabs[i - firstchar], WinChars[i]);
}
}
}
/* Put out the trailer */
out.print("EndCharMetrics\n");
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Pfm2afm.java
private void putkerntab() throws IOException {
if (kernpairs == 0)
return;
in.seek(kernpairs);
int count = in.readUnsignedShortLE();
int nzero = 0;
int kerns[] = new int[count * 3];
for (int k = 0; k < kerns.length;) {
kerns[k++] = in.read();
kerns[k++] = in.read();
if ((kerns[k++] = in.readShortLE()) != 0)
++nzero;
}
if (nzero == 0)
return;
out.print("StartKernData\nStartKernPairs");
outval(nzero);
out.print('\n');
for (int k = 0; k < kerns.length; k += 3) {
if (kerns[k + 2] != 0) {
out.print("KPX ");
out.print(WinChars[kerns[k]]);
out.print(' ');
out.print(WinChars[kerns[k + 1]]);
outval(kerns[k + 2]);
out.print('\n');
}
}
/* Put out trailer */
out.print("EndKernPairs\nEndKernData\n");
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/EnumerateTTC.java
void findNames() throws DocumentException, IOException {
tables = new HashMap<String, int[]>();
try {
String mainTag = readStandardString(4);
if (!mainTag.equals("ttcf"))
throw new DocumentException(MessageLocalization.getComposedMessage("1.is.not.a.valid.ttc.file", fileName));
rf.skipBytes(4);
int dirCount = rf.readInt();
names = new String[dirCount];
int dirPos = (int)rf.getFilePointer();
for (int dirIdx = 0; dirIdx < dirCount; ++dirIdx) {
tables.clear();
rf.seek(dirPos);
rf.skipBytes(dirIdx * 4);
directoryOffset = rf.readInt();
rf.seek(directoryOffset);
if (rf.readInt() != 0x00010000)
throw new DocumentException(MessageLocalization.getComposedMessage("1.is.not.a.valid.ttf.file", fileName));
int num_tables = rf.readUnsignedShort();
rf.skipBytes(6);
for (int k = 0; k < num_tables; ++k) {
String tag = readStandardString(4);
rf.skipBytes(4);
int table_location[] = new int[2];
table_location[0] = rf.readInt();
table_location[1] = rf.readInt();
tables.put(tag, table_location);
}
names[dirIdx] = getBaseFont();
}
}
finally {
if (rf != null)
rf.close();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPSXObject.java
public PdfStream getFormXObject(int compressionLevel) throws IOException {
PdfStream s = new PdfStream(content.toByteArray());
s.put(PdfName.TYPE, PdfName.XOBJECT);
s.put(PdfName.SUBTYPE, PdfName.PS);
s.flateCompress(compressionLevel);
return s;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type3Font.java
Override
void writeFont(PdfWriter writer, PdfIndirectReference ref, Object[] params) throws com.itextpdf.text.DocumentException, java.io.IOException {
if (this.writer != writer)
throw new IllegalArgumentException(MessageLocalization.getComposedMessage("type3.font.used.with.the.wrong.pdfwriter"));
// Get first & lastchar ...
int firstChar = 0;
while( firstChar < usedSlot.length && !usedSlot[firstChar] ) firstChar++;
if ( firstChar == usedSlot.length ) {
throw new DocumentException(MessageLocalization.getComposedMessage("no.glyphs.defined.for.type3.font"));
}
int lastChar = usedSlot.length - 1;
while( lastChar >= firstChar && !usedSlot[lastChar] ) lastChar--;
int[] widths = new int[lastChar - firstChar + 1];
int[] invOrd = new int[lastChar - firstChar + 1];
int invOrdIndx = 0, w = 0;
for( int u = firstChar; u<=lastChar; u++, w++ ) {
if ( usedSlot[u] ) {
invOrd[invOrdIndx++] = u;
widths[w] = widths3.get(u);
}
}
PdfArray diffs = new PdfArray();
PdfDictionary charprocs = new PdfDictionary();
int last = -1;
for (int k = 0; k < invOrdIndx; ++k) {
int c = invOrd[k];
if (c > last) {
last = c;
diffs.add(new PdfNumber(last));
}
++last;
int c2 = invOrd[k];
String s = GlyphList.unicodeToName(c2);
if (s == null)
s = "a" + c2;
PdfName n = new PdfName(s);
diffs.add(n);
Type3Glyph glyph = char2glyph.get(Integer.valueOf(c2));
PdfStream stream = new PdfStream(glyph.toPdf(null));
stream.flateCompress(compressionLevel);
PdfIndirectReference refp = writer.addToBody(stream).getIndirectReference();
charprocs.put(n, refp);
}
PdfDictionary font = new PdfDictionary(PdfName.FONT);
font.put(PdfName.SUBTYPE, PdfName.TYPE3);
if (colorized)
font.put(PdfName.FONTBBOX, new PdfRectangle(0, 0, 0, 0));
else
font.put(PdfName.FONTBBOX, new PdfRectangle(llx, lly, urx, ury));
font.put(PdfName.FONTMATRIX, new PdfArray(new float[]{0.001f, 0, 0, 0.001f, 0, 0}));
font.put(PdfName.CHARPROCS, writer.addToBody(charprocs).getIndirectReference());
PdfDictionary encoding = new PdfDictionary();
encoding.put(PdfName.DIFFERENCES, diffs);
font.put(PdfName.ENCODING, writer.addToBody(encoding).getIndirectReference());
font.put(PdfName.FIRSTCHAR, new PdfNumber(firstChar));
font.put(PdfName.LASTCHAR, new PdfNumber(lastChar));
font.put(PdfName.WIDTHS, writer.addToBody(new PdfArray(widths)).getIndirectReference());
if (pageResources.hasResources())
font.put(PdfName.RESOURCES, writer.addToBody(pageResources.getResources()).getIndirectReference());
writer.addToBody(font, ref);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReaderInstance.java
PdfStream getFormXObject(int pageNumber, int compressionLevel) throws IOException {
PdfDictionary page = reader.getPageNRelease(pageNumber);
PdfObject contents = PdfReader.getPdfObjectRelease(page.get(PdfName.CONTENTS));
PdfDictionary dic = new PdfDictionary();
byte bout[] = null;
if (contents != null) {
if (contents.isStream())
dic.putAll((PRStream)contents);
else
bout = reader.getPageContent(pageNumber, file);
}
else
bout = new byte[0];
dic.put(PdfName.RESOURCES, PdfReader.getPdfObjectRelease(page.get(PdfName.RESOURCES)));
dic.put(PdfName.TYPE, PdfName.XOBJECT);
dic.put(PdfName.SUBTYPE, PdfName.FORM);
PdfImportedPage impPage = importedPages.get(Integer.valueOf(pageNumber));
dic.put(PdfName.BBOX, new PdfRectangle(impPage.getBoundingBox()));
PdfArray matrix = impPage.getMatrix();
if (matrix == null)
dic.put(PdfName.MATRIX, IDENTITYMATRIX);
else
dic.put(PdfName.MATRIX, matrix);
dic.put(PdfName.FORMTYPE, ONE);
PRStream stream;
if (bout == null) {
stream = new PRStream((PRStream)contents, dic);
}
else {
stream = new PRStream(reader, bout, compressionLevel);
stream.putAll(dic);
}
return stream;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReaderInstance.java
void writeAllVisited() throws IOException {
while (!nextRound.isEmpty()) {
ArrayList<Integer> vec = nextRound;
nextRound = new ArrayList<Integer>();
for (int k = 0; k < vec.size(); ++k) {
Integer i = vec.get(k);
if (!visited.contains(i)) {
visited.add(i);
int n = i.intValue();
writer.addToBody(reader.getPdfObjectRelease(n), myXref[n]);
}
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReaderInstance.java
public void writeAllPages() throws IOException {
try {
file.reOpen();
for (Object element : importedPages.values()) {
PdfImportedPage ip = (PdfImportedPage)element;
if (ip.isToCopy()) {
writer.addToBody(ip.getFormXObject(writer.getCompressionLevel()), ip.getIndirectReference());
ip.setCopied();
}
}
writeAllVisited();
}
finally {
try {
// TODO: Removed - the user should be responsible for closing all PdfReaders. But, this could cause a lot of memory leaks in code out there that hasn't been properly closing things - maybe add a finalizer to PdfReader that calls PdfReader#close() ??
// reader.close();
file.close();
}
catch (Exception e) {
//Empty on purpose
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfObject.java
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {
if (bytes != null)
os.write(bytes);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
public void toPdf(PdfWriter writer, OutputStream os) throws IOException {
byte[] b = PdfReader.getStreamBytesRaw(this);
PdfEncryption crypto = null;
if (writer != null)
crypto = writer.getEncryption();
PdfObject objLen = get(PdfName.LENGTH);
int nn = b.length;
if (crypto != null)
nn = crypto.calculateStreamSize(nn);
put(PdfName.LENGTH, new PdfNumber(nn));
superToPdf(writer, os);
put(PdfName.LENGTH, objLen);
os.write(STARTSTREAM);
if (length > 0) {
if (crypto != null && !crypto.isEmbeddedFilesOnly())
b = crypto.encryptByteArray(b);
os.write(b);
}
os.write(ENDSTREAM);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfNumberTree.java
public static <O extends PdfObject> PdfDictionary writeTree(HashMap<Integer, O> items, PdfWriter writer) throws IOException {
if (items.isEmpty())
return null;
Integer numbers[] = new Integer[items.size()];
numbers = items.keySet().toArray(numbers);
Arrays.sort(numbers);
if (numbers.length <= leafSize) {
PdfDictionary dic = new PdfDictionary();
PdfArray ar = new PdfArray();
for (int k = 0; k < numbers.length; ++k) {
ar.add(new PdfNumber(numbers[k].intValue()));
ar.add(items.get(numbers[k]));
}
dic.put(PdfName.NUMS, ar);
return dic;
}
int skip = leafSize;
PdfIndirectReference kids[] = new PdfIndirectReference[(numbers.length + leafSize - 1) / leafSize];
for (int k = 0; k < kids.length; ++k) {
int offset = k * leafSize;
int end = Math.min(offset + leafSize, numbers.length);
PdfDictionary dic = new PdfDictionary();
PdfArray arr = new PdfArray();
arr.add(new PdfNumber(numbers[offset].intValue()));
arr.add(new PdfNumber(numbers[end - 1].intValue()));
dic.put(PdfName.LIMITS, arr);
arr = new PdfArray();
for (; offset < end; ++offset) {
arr.add(new PdfNumber(numbers[offset].intValue()));
arr.add(items.get(numbers[offset]));
}
dic.put(PdfName.NUMS, arr);
kids[k] = writer.addToBody(dic).getIndirectReference();
}
int top = kids.length;
while (true) {
if (top <= leafSize) {
PdfArray arr = new PdfArray();
for (int k = 0; k < top; ++k)
arr.add(kids[k]);
PdfDictionary dic = new PdfDictionary();
dic.put(PdfName.KIDS, arr);
return dic;
}
skip *= leafSize;
int tt = (numbers.length + skip - 1 )/ skip;
for (int k = 0; k < tt; ++k) {
int offset = k * leafSize;
int end = Math.min(offset + leafSize, top);
PdfDictionary dic = new PdfDictionary();
PdfArray arr = new PdfArray();
arr.add(new PdfNumber(numbers[k * skip].intValue()));
arr.add(new PdfNumber(numbers[Math.min((k + 1) * skip, numbers.length) - 1].intValue()));
dic.put(PdfName.LIMITS, arr);
arr = new PdfArray();
for (; offset < end; ++offset) {
arr.add(kids[offset]);
}
dic.put(PdfName.KIDS, arr);
kids[k] = writer.addToBody(dic).getIndirectReference();
}
top = tt;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfReaderContentParser.java
public <E extends RenderListener> E processContent(int pageNumber, E renderListener) throws IOException{
PdfDictionary pageDic = reader.getPageN(pageNumber);
PdfDictionary resourcesDic = pageDic.getAsDict(PdfName.RESOURCES);
PdfContentStreamProcessor processor = new PdfContentStreamProcessor(renderListener);
processor.processContent(ContentByteUtils.getContentBytesForPage(reader, pageNumber), resourcesDic);
return renderListener;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
private void displayXObject(PdfName xobjectName) throws IOException {
PdfDictionary xobjects = resources.getAsDict(PdfName.XOBJECT);
PdfObject xobject = xobjects.getDirectObject(xobjectName);
PdfStream xobjectStream = (PdfStream)xobject;
PdfName subType = xobjectStream.getAsName(PdfName.SUBTYPE);
if (xobject.isStream()){
XObjectDoHandler handler = xobjectDoHandlers.get(subType);
if (handler == null)
handler = xobjectDoHandlers.get(PdfName.DEFAULT);
handler.handleXObject(this, xobjectStream, xobjects.getAsIndirectObject(xobjectName));
} else {
throw new IllegalStateException(MessageLocalization.getComposedMessage("XObject.1.is.not.a.stream", xobjectName));
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
public void invoke(PdfContentStreamProcessor processor, PdfLiteral operator, ArrayList<PdfObject> operands) throws IOException {
PdfName xobjectName = (PdfName)operands.get(0);
processor.displayXObject(xobjectName);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/ContentByteUtils.java
public static byte[] getContentBytesFromContentObject(final PdfObject contentObject) throws IOException {
final byte[] result;
switch (contentObject.type())
{
case PdfObject.INDIRECT:
final PRIndirectReference ref = (PRIndirectReference) contentObject;
final PdfObject directObject = PdfReader.getPdfObject(ref);
result = getContentBytesFromContentObject(directObject);
break;
case PdfObject.STREAM:
final PRStream stream = (PRStream) PdfReader.getPdfObject(contentObject);
result = PdfReader.getStreamBytes(stream);
break;
case PdfObject.ARRAY:
// Stitch together all content before calling processContent(), because
// processContent() resets state.
final ByteArrayOutputStream allBytes = new ByteArrayOutputStream();
final PdfArray contentArray = (PdfArray) contentObject;
final ListIterator<PdfObject> iter = contentArray.listIterator();
while (iter.hasNext())
{
final PdfObject element = iter.next();
allBytes.write(getContentBytesFromContentObject(element));
allBytes.write((byte)' ');
}
result = allBytes.toByteArray();
break;
default:
final String msg = "Unable to handle Content of type " + contentObject.getClass();
throw new IllegalStateException(msg);
}
return result;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/ContentByteUtils.java
public static byte[] getContentBytesForPage(PdfReader reader, int pageNum) throws IOException {
final PdfDictionary pageDictionary = reader.getPageN(pageNum);
final PdfObject contentObject = pageDictionary.get(PdfName.CONTENTS);
if (contentObject == null)
return new byte[0];
final byte[] contentBytes = ContentByteUtils.getContentBytesFromContentObject(contentObject);
return contentBytes;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentReaderTool.java
static public String getXObjectDetail(PdfDictionary resourceDic) throws IOException {
StringBuilder sb = new StringBuilder();
PdfDictionary xobjects = resourceDic.getAsDict(PdfName.XOBJECT);
if (xobjects == null)
return "No XObjects";
for (PdfName entryName : xobjects.getKeys()) {
PdfStream xobjectStream = xobjects.getAsStream(entryName);
sb.append("------ " + entryName + " - subtype = " + xobjectStream.get(PdfName.SUBTYPE) + " = " + xobjectStream.getAsNumber(PdfName.LENGTH) + " bytes ------\n");
if (!xobjectStream.get(PdfName.SUBTYPE).equals(PdfName.IMAGE)){
byte[] contentBytes = ContentByteUtils.getContentBytesFromContentObject(xobjectStream);
InputStream is = new ByteArrayInputStream(contentBytes);
int ch;
while ((ch = is.read()) != -1){
sb.append((char)ch);
}
sb.append("------ " + entryName + " - subtype = " + xobjectStream.get(PdfName.SUBTYPE) + "End of Content" + "------\n");
}
}
return sb.toString();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentReaderTool.java
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("- - - - - XObject Summary - - - - - -");
out.println(getXObjectDetail(pageDictionary.getAsDict(PdfName.RESOURCES)));
out.println("- - - - - Content Stream - - - - - -");
RandomAccessFileOrArray f = reader.getSafeFile();
byte[] contentBytes = reader.getPageContent(pageNum, f);
f.close();
out.flush();
InputStream is = new ByteArrayInputStream(contentBytes);
int ch;
while ((ch = is.read()) != -1){
out.print((char)ch);
}
out.flush();
out.println("- - - - - Text Extraction - - - - - -");
String extractedText = PdfTextExtractor.getTextFromPage(reader, pageNum, new LocationTextExtractionStrategy());
if (extractedText.length() != 0)
out.println(extractedText);
else
out.println("No text found on page " + pageNum);
out.println();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentReaderTool.java
static public void listContentStream(File pdfFile, PrintWriter out) throws IOException {
PdfReader reader = new PdfReader(pdfFile.getCanonicalPath());
int maxPageNum = reader.getNumberOfPages();
for (int pageNum = 1; pageNum <= maxPageNum; pageNum++){
listContentStreamForPage(reader, pageNum, out);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentReaderTool.java
static public void listContentStream(File pdfFile, int pageNum, PrintWriter out) throws IOException {
PdfReader reader = new PdfReader(pdfFile.getCanonicalPath());
listContentStreamForPage(reader, pageNum, out);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/TaggedPdfReaderTool.java
public void convertToXml(PdfReader reader, OutputStream os, String charset)
throws IOException {
this.reader = reader;
OutputStreamWriter outs = new OutputStreamWriter(os, charset);
out = new PrintWriter(outs);
// get the StructTreeRoot from the root object
PdfDictionary catalog = reader.getCatalog();
PdfDictionary struct = catalog.getAsDict(PdfName.STRUCTTREEROOT);
if (struct == null)
throw new IOException(MessageLocalization.getComposedMessage("no.structtreeroot.found"));
// Inspect the child or children of the StructTreeRoot
inspectChild(struct.getDirectObject(PdfName.K));
out.flush();
out.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/TaggedPdfReaderTool.java
public void convertToXml(PdfReader reader, OutputStream os)
throws IOException {
convertToXml(reader, os, Charset.defaultCharset().name());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/TaggedPdfReaderTool.java
public void inspectChild(PdfObject k) throws IOException {
if (k == null)
return;
if (k instanceof PdfArray)
inspectChildArray((PdfArray) k);
else if (k instanceof PdfDictionary)
inspectChildDictionary((PdfDictionary) k);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/TaggedPdfReaderTool.java
public void inspectChildArray(PdfArray k) throws IOException {
if (k == null)
return;
for (int i = 0; i < k.size(); i++) {
inspectChild(k.getDirectObject(i));
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/TaggedPdfReaderTool.java
public void inspectChildDictionary(PdfDictionary k) throws IOException {
inspectChildDictionary(k, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/TaggedPdfReaderTool.java
public void inspectChildDictionary(PdfDictionary k, boolean inspectAttributes) throws IOException {
if (k == null)
return;
PdfName s = k.getAsName(PdfName.S);
if (s != null) {
String tagN = PdfName.decodeName(s.toString());
String tag = fixTagName(tagN);
out.print("<");
out.print(tag);
if (inspectAttributes) {
PdfDictionary a = k.getAsDict(PdfName.A);
if (a != null) {
Set<PdfName> keys = a.getKeys();
for (PdfName key : keys) {
out.print(' ');
PdfObject value = a.get(key);
value = PdfReader.getPdfObject(value);
out.print(xmlName(key));
out.print("=\"");
out.print(value.toString());
out.print("\"");
}
}
}
out.print(">");
PdfDictionary dict = k.getAsDict(PdfName.PG);
if (dict != null)
parseTag(tagN, k.getDirectObject(PdfName.K), dict);
inspectChild(k.getDirectObject(PdfName.K));
out.print("</");
out.print(tag);
out.println(">");
} else
inspectChild(k.getDirectObject(PdfName.K));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/TaggedPdfReaderTool.java
public void parseTag(String tag, PdfObject object, PdfDictionary page)
throws IOException {
// if the identifier is a number, we can extract the content right away
if (object instanceof PdfNumber) {
PdfNumber mcid = (PdfNumber) object;
RenderFilter filter = new MarkedContentRenderFilter(mcid.intValue());
TextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
FilteredTextRenderListener listener = new FilteredTextRenderListener(
strategy, filter);
PdfContentStreamProcessor processor = new PdfContentStreamProcessor(
listener);
processor.processContent(PdfReader.getPageContent(page), page
.getAsDict(PdfName.RESOURCES));
out.print(XMLUtil.escapeXML(listener.getResultantText(), true));
}
// if the identifier is an array, we call the parseTag method
// recursively
else if (object instanceof PdfArray) {
PdfArray arr = (PdfArray) object;
int n = arr.size();
for (int i = 0; i < n; i++) {
parseTag(tag, arr.getPdfObject(i), page);
if (i < n - 1)
out.println();
}
}
// if the identifier is a dictionary, we get the resources from the
// dictionary
else if (object instanceof PdfDictionary) {
PdfDictionary mcr = (PdfDictionary) object;
parseTag(tag, mcr.getDirectObject(PdfName.MCID), mcr
.getAsDict(PdfName.PG));
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/ImageRenderInfo.java
public PdfImageObject getImage() throws IOException {
prepareImageObject();
return imageObject;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/ImageRenderInfo.java
private void prepareImageObject() throws IOException{
if (imageObject != null)
return;
if (ref != null){
PRStream stream = (PRStream)PdfReader.getPdfObject(ref);
imageObject = new PdfImageObject(stream, colorSpaceDictionary);
} else if (inlineImageInfo != null){
imageObject = new PdfImageObject(inlineImageInfo.getImageDictionary(), inlineImageInfo.getSamples(), colorSpaceDictionary);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfTextExtractor.java
public static String getTextFromPage(PdfReader reader, int pageNumber, TextExtractionStrategy strategy) throws IOException{
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
return parser.processContent(pageNumber, strategy).getResultantText();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfTextExtractor.java
public static String getTextFromPage(PdfReader reader, int pageNumber) throws IOException{
return getTextFromPage(reader, pageNumber, new LocationTextExtractionStrategy());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/InlineImageUtils.java
public static InlineImageInfo parseInlineImage(PdfContentParser ps, PdfDictionary colorSpaceDic) throws IOException{
PdfDictionary inlineImageDictionary = parseInlineImageDictionary(ps);
byte[] samples = parseInlineImageSamples(inlineImageDictionary, colorSpaceDic, ps);
return new InlineImageInfo(samples, inlineImageDictionary);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/InlineImageUtils.java
private static PdfDictionary parseInlineImageDictionary(PdfContentParser ps) throws IOException{
// by the time we get to here, we have already parsed the BI operator
PdfDictionary dictionary = new PdfDictionary();
for(PdfObject key = ps.readPRObject(); key != null && !"ID".equals(key.toString()); key = ps.readPRObject()){
PdfObject value = ps.readPRObject();
PdfName resolvedKey = inlineImageEntryAbbreviationMap.get(key);
if (resolvedKey == null)
resolvedKey = (PdfName)key;
dictionary.put(resolvedKey, getAlternateValue(resolvedKey, value));
}
int ch = ps.getTokeniser().read();
if (!PRTokeniser.isWhitespace(ch))
throw new IOException("Unexpected character " + ch + " found after ID in inline image");
return dictionary;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/InlineImageUtils.java
private static byte[] parseUnfilteredSamples(PdfDictionary imageDictionary, PdfDictionary colorSpaceDic, PdfContentParser ps) throws IOException{
// special case: when no filter is specified, we just read the number of bits
// per component, multiplied by the width and height.
if (imageDictionary.contains(PdfName.FILTER))
throw new IllegalArgumentException("Dictionary contains filters");
PdfNumber h = imageDictionary.getAsNumber(PdfName.HEIGHT);
int bytesToRead = computeBytesPerRow(imageDictionary, colorSpaceDic) * h.intValue();
byte[] bytes = new byte[bytesToRead];
PRTokeniser tokeniser = ps.getTokeniser();
int shouldBeWhiteSpace = tokeniser.read(); // skip next character (which better be a whitespace character - I suppose we could check for this)
// from the PDF spec: Unless the image uses ASCIIHexDecode or ASCII85Decode as one of its filters, the ID operator shall be followed by a single white-space character, and the next character shall be interpreted as the first byte of image data.
// unfortunately, we've seen some PDFs where there is no space following the ID, so we have to capture this case and handle it
int startIndex = 0;
if (!PRTokeniser.isWhitespace(shouldBeWhiteSpace) || shouldBeWhiteSpace == 0){ // tokeniser treats 0 as whitespace, but for our purposes, we shouldn't
bytes[0] = (byte)shouldBeWhiteSpace;
startIndex++;
}
for(int i = startIndex; i < bytesToRead; i++){
int ch = tokeniser.read();
if (ch == -1)
throw new InlineImageParseException("End of content stream reached before end of image data");
bytes[i] = (byte)ch;
}
PdfObject ei = ps.readPRObject();
if (!ei.toString().equals("EI"))
throw new InlineImageParseException("EI not found after end of image data");
return bytes;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/InlineImageUtils.java
private static byte[] parseInlineImageSamples(PdfDictionary imageDictionary, PdfDictionary colorSpaceDic, PdfContentParser ps) throws IOException{
// by the time we get to here, we have already parsed the ID operator
if (!imageDictionary.contains(PdfName.FILTER)){
return parseUnfilteredSamples(imageDictionary, colorSpaceDic, ps);
}
// read all content until we reach an EI operator surrounded by whitespace.
// The following algorithm has two potential issues: what if the image stream
// contains <ws>EI<ws> ?
// Plus, there are some streams that don't have the <ws> before the EI operator
// it sounds like we would have to actually decode the content stream, which
// I'd rather avoid right now.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayOutputStream accumulated = new ByteArrayOutputStream();
int ch;
int found = 0;
PRTokeniser tokeniser = ps.getTokeniser();
while ((ch = tokeniser.read()) != -1){
if (found == 0 && PRTokeniser.isWhitespace(ch)){
found++;
accumulated.write(ch);
} else if (found == 1 && ch == 'E'){
found++;
accumulated.write(ch);
} else if (found == 1 && PRTokeniser.isWhitespace(ch)){
// this clause is needed if we have a white space character that is part of the image data
// followed by a whitespace character that precedes the EI operator. In this case, we need
// to flush the first whitespace, then treat the current whitespace as the first potential
// character for the end of stream check. Note that we don't increment 'found' here.
baos.write(accumulated.toByteArray());
accumulated.reset();
accumulated.write(ch);
} else if (found == 2 && ch == 'I'){
found++;
accumulated.write(ch);
} else if (found == 3 && PRTokeniser.isWhitespace(ch)){
return baos.toByteArray();
} else {
baos.write(accumulated.toByteArray());
accumulated.reset();
baos.write(ch);
found = 0;
}
}
throw new InlineImageParseException("Could not find image data or EI");
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfImageObject.java
public byte[] decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary) throws IOException {
lastFilterName = filterName;
return b;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfImageObject.java
private void findColorspace(PdfObject colorspace, boolean allowIndexed) throws IOException {
if (colorspace == null && bpc == 1){ // handle imagemasks
stride = (width*bpc + 7) / 8;
pngColorType = 0;
}
else if (PdfName.DEVICEGRAY.equals(colorspace)) {
stride = (width * bpc + 7) / 8;
pngColorType = 0;
}
else if (PdfName.DEVICERGB.equals(colorspace)) {
if (bpc == 8 || bpc == 16) {
stride = (width * bpc * 3 + 7) / 8;
pngColorType = 2;
}
}
else if (colorspace instanceof PdfArray) {
PdfArray ca = (PdfArray)colorspace;
PdfObject tyca = ca.getDirectObject(0);
if (PdfName.CALGRAY.equals(tyca)) {
stride = (width * bpc + 7) / 8;
pngColorType = 0;
}
else if (PdfName.CALRGB.equals(tyca)) {
if (bpc == 8 || bpc == 16) {
stride = (width * bpc * 3 + 7) / 8;
pngColorType = 2;
}
}
else if (PdfName.ICCBASED.equals(tyca)) {
PRStream pr = (PRStream)ca.getDirectObject(1);
int n = pr.getAsNumber(PdfName.N).intValue();
if (n == 1) {
stride = (width * bpc + 7) / 8;
pngColorType = 0;
icc = PdfReader.getStreamBytes(pr);
}
else if (n == 3) {
stride = (width * bpc * 3 + 7) / 8;
pngColorType = 2;
icc = PdfReader.getStreamBytes(pr);
}
}
else if (allowIndexed && PdfName.INDEXED.equals(tyca)) {
findColorspace(ca.getDirectObject(1), false);
if (pngColorType == 2) {
PdfObject id2 = ca.getDirectObject(3);
if (id2 instanceof PdfString) {
palette = ((PdfString)id2).getBytes();
}
else if (id2 instanceof PRStream) {
palette = PdfReader.getStreamBytes(((PRStream)id2));
}
stride = (width * bpc + 7) / 8;
pngColorType = 3;
}
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfImageObject.java
private void decodeImageBytes() throws IOException{
if (streamContentType != null)
throw new IllegalStateException(MessageLocalization.getComposedMessage("Decoding.can't.happen.on.this.type.of.stream.(.1.)", streamContentType));
pngColorType = -1;
PdfArray decode = dictionary.getAsArray(PdfName.DECODE);
width = dictionary.getAsNumber(PdfName.WIDTH).intValue();
height = dictionary.getAsNumber(PdfName.HEIGHT).intValue();
bpc = dictionary.getAsNumber(PdfName.BITSPERCOMPONENT).intValue();
pngBitDepth = bpc;
PdfObject colorspace = dictionary.getDirectObject(PdfName.COLORSPACE);
if (colorspace instanceof PdfName && colorSpaceDic != null){
PdfObject csLookup = colorSpaceDic.getDirectObject((PdfName)colorspace);
if (csLookup != null)
colorspace = csLookup;
}
palette = null;
icc = null;
stride = 0;
findColorspace(colorspace, true);
ByteArrayOutputStream ms = new ByteArrayOutputStream();
if (pngColorType < 0) {
if (bpc != 8)
throw new UnsupportedPdfException(MessageLocalization.getComposedMessage("the.color.depth.1.is.not.supported", bpc));
if (PdfName.DEVICECMYK.equals(colorspace)) {
}
else if (colorspace instanceof PdfArray) {
PdfArray ca = (PdfArray)colorspace;
PdfObject tyca = ca.getDirectObject(0);
if (!PdfName.ICCBASED.equals(tyca))
throw new UnsupportedPdfException(MessageLocalization.getComposedMessage("the.color.space.1.is.not.supported", colorspace));
PRStream pr = (PRStream)ca.getDirectObject(1);
int n = pr.getAsNumber(PdfName.N).intValue();
if (n != 4) {
throw new UnsupportedPdfException(MessageLocalization.getComposedMessage("N.value.1.is.not.supported", n));
}
icc = PdfReader.getStreamBytes(pr);
}
else
throw new UnsupportedPdfException(MessageLocalization.getComposedMessage("the.color.space.1.is.not.supported", colorspace));
stride = 4 * width;
TiffWriter wr = new TiffWriter();
wr.addField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL, 4));
wr.addField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_BITSPERSAMPLE, new int[]{8,8,8,8}));
wr.addField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PHOTOMETRIC, TIFFConstants.PHOTOMETRIC_SEPARATED));
wr.addField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGEWIDTH, width));
wr.addField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_IMAGELENGTH, height));
wr.addField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_COMPRESSION, TIFFConstants.COMPRESSION_LZW));
wr.addField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_PREDICTOR, TIFFConstants.PREDICTOR_HORIZONTAL_DIFFERENCING));
wr.addField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP, height));
wr.addField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_XRESOLUTION, new int[]{300,1}));
wr.addField(new TiffWriter.FieldRational(TIFFConstants.TIFFTAG_YRESOLUTION, new int[]{300,1}));
wr.addField(new TiffWriter.FieldShort(TIFFConstants.TIFFTAG_RESOLUTIONUNIT, TIFFConstants.RESUNIT_INCH));
wr.addField(new TiffWriter.FieldAscii(TIFFConstants.TIFFTAG_SOFTWARE, Version.getInstance().getVersion()));
ByteArrayOutputStream comp = new ByteArrayOutputStream();
TiffWriter.compressLZW(comp, 2, imageBytes, height, 4, stride);
byte[] buf = comp.toByteArray();
wr.addField(new TiffWriter.FieldImage(buf));
wr.addField(new TiffWriter.FieldLong(TIFFConstants.TIFFTAG_STRIPBYTECOUNTS, buf.length));
if (icc != null)
wr.addField(new TiffWriter.FieldUndefined(TIFFConstants.TIFFTAG_ICCPROFILE, icc));
wr.writeFile(ms);
streamContentType = ImageBytesType.CCITT;
imageBytes = ms.toByteArray();
return;
} else {
PngWriter png = new PngWriter(ms);
if (decode != null){
if (pngBitDepth == 1){
// if the decode array is 1,0, then we need to invert the image
if(decode.getAsNumber(0).intValue() == 1 && decode.getAsNumber(1).intValue() == 0){
int len = imageBytes.length;
for (int t = 0; t < len; ++t) {
imageBytes[t] ^= 0xff;
}
} else {
// if the decode array is 0,1, do nothing. It's possible that the array could be 0,0 or 1,1 - but that would be silly, so we'll just ignore that case
}
} else {
// todo: add decode transformation for other depths
}
}
png.writeHeader(width, height, pngBitDepth, pngColorType);
if (icc != null)
png.writeIccProfile(icc);
if (palette != null)
png.writePalette(palette);
png.writeData(imageBytes, stride);
png.writeEnd();
streamContentType = ImageBytesType.PNG;
imageBytes = ms.toByteArray();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfImageObject.java
public java.awt.image.BufferedImage getBufferedImage() throws IOException {
byte[] img = getImageAsBytes();
if (img == null)
return null;
return ImageIO.read(new ByteArrayInputStream(img));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontUnicode.java
Override
void process(byte ttfAfm[], boolean preload) throws DocumentException, IOException {
super.process(ttfAfm, preload);
//readGsubTable();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontUnicode.java
Override
void writeFont(PdfWriter writer, PdfIndirectReference ref, Object params[]) throws DocumentException, IOException {
writer.getTtfUnicodeWriter().writeFont(this, ref, params, rotbits);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontUnicode.java
Override
public PdfStream getFullFontStream() throws IOException, DocumentException {
if (cff) {
return new StreamFont(readCffFont(), "CIDFontType0C", compressionLevel);
}
return super.getFullFontStream();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontUnicode.java
private void readGsubTable() throws IOException {
if (tables.get("GSUB") != null) {
Map<Integer, Character> glyphToCharacterMap = new HashMap<Integer, Character>(cmap31.size());
for (Integer charCode : cmap31.keySet()) {
char c = (char) charCode.intValue();
int glyphCode = cmap31.get(charCode)[0];
glyphToCharacterMap.put(glyphCode, c);
}
GlyphSubstitutionTableReader gsubReader = new GlyphSubstitutionTableReader(
fileName, tables.get("GSUB")[0], glyphToCharacterMap, glyphWidthsByIndex);
try {
gsubReader.read();
supportedLanguage = gsubReader.getSupportedLanguage();
if (SUPPORTED_LANGUAGES_FOR_OTF.contains(supportedLanguage)) {
glyphSubstitutionMap = gsubReader.getGlyphSubstitutionMap();
/*if (false) {
StringBuilder sb = new StringBuilder(50);
for (int glyphCode : glyphToCharacterMap.keySet()) {
sb.append(glyphCode).append("=>").append(glyphToCharacterMap.get(glyphCode)).append("\n");
}
System.out.println("GlyphToCharacterMap:\n" + sb.toString());
}
if (false) {
StringBuilder sb = new StringBuilder(50);
int count = 1;
for (String chars : glyphSubstitutionMap.keySet()) {
int glyphId = glyphSubstitutionMap.get(chars).code;
sb.append(count++).append(".>");
sb.append(chars).append(" => ").append(glyphId).append("\n");
}
System.out.println("GlyphSubstitutionMap:\n" + sb.toString());
}*/
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfTemplate.java
public PdfStream getFormXObject(int compressionLevel) throws IOException {
return new PdfFormXObject(this, compressionLevel);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
public static PdfAnnotation createScreen(PdfWriter writer, Rectangle rect, String clipTitle, PdfFileSpecification fs,
String mimeType, boolean playOnDisplay) throws IOException {
PdfAnnotation ann = new PdfAnnotation(writer, rect);
ann.put(PdfName.SUBTYPE, PdfName.SCREEN);
ann.put (PdfName.F, new PdfNumber(FLAGS_PRINT));
ann.put(PdfName.TYPE, PdfName.ANNOT);
ann.setPage();
PdfIndirectReference ref = ann.getIndirectReference();
PdfAction action = PdfAction.rendition(clipTitle,fs,mimeType, ref);
PdfIndirectReference actionRef = writer.addToBody(action).getIndirectReference();
// for play on display add trigger event
if (playOnDisplay)
{
PdfDictionary aa = new PdfDictionary();
aa.put(new PdfName("PV"), actionRef);
ann.put(PdfName.AA, aa);
}
ann.put(PdfName.A, actionRef);
return ann;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
public static PdfAnnotation createFileAttachment(PdfWriter writer, Rectangle rect, String contents, byte fileStore[], String file, String fileDisplay) throws IOException {
return createFileAttachment(writer, rect, contents, PdfFileSpecification.fileEmbedded(writer, file, fileDisplay, fileStore));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
public static PdfAnnotation createFileAttachment(PdfWriter writer, Rectangle rect, String contents, PdfFileSpecification fs) throws IOException {
PdfAnnotation annot = new PdfAnnotation(writer, rect);
annot.put(PdfName.SUBTYPE, PdfName.FILEATTACHMENT);
if (contents != null)
annot.put(PdfName.CONTENTS, new PdfString(contents, PdfObject.TEXT_UNICODE));
annot.put(PdfName.FS, fs.getReference());
return annot;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
Override
protected PdfIndirectReference copyIndirect(PRIndirectReference in) throws IOException, BadPdfFormatException {
PdfObject srcObj = PdfReader.getPdfObjectRelease(in);
ByteStore streamKey = null;
boolean validStream = false;
if (srcObj.isStream()) {
streamKey = new ByteStore((PRStream)srcObj);
validStream = true;
PdfIndirectReference streamRef = streamMap.get(streamKey);
if (streamRef != null) {
return streamRef;
}
}
else if (srcObj.isDictionary()) {
streamKey = new ByteStore((PdfDictionary)srcObj);
validStream = true;
PdfIndirectReference streamRef = streamMap.get(streamKey);
if (streamRef != null) {
return streamRef;
}
}
PdfIndirectReference theRef;
RefKey key = new RefKey(in);
IndirectReferences iRef = indirects.get(key);
if (iRef != null) {
theRef = iRef.getRef();
if (iRef.getCopied()) {
return theRef;
}
} else {
theRef = body.getPdfIndirectReference();
iRef = new IndirectReferences(theRef);
indirects.put(key, iRef);
}
if (srcObj.isDictionary()) {
PdfObject type = PdfReader.getPdfObjectRelease(((PdfDictionary)srcObj).get(PdfName.TYPE));
if (type != null && PdfName.PAGE.equals(type)) {
return theRef;
}
}
iRef.setCopied();
if (validStream) {
streamMap.put(streamKey, theRef);
}
PdfObject obj = copyObject(srcObj);
addToBody(obj, theRef);
return theRef;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
private void serObject(PdfObject obj, int level, ByteBuffer bb) throws IOException {
if (level <= 0)
return;
if (obj == null) {
bb.append("$Lnull");
return;
}
if (obj.isIndirect()) {
if (serialized.contains(obj))
return;
else
serialized.add(obj);
}
obj = PdfReader.getPdfObject(obj);
if (obj.isStream()) {
bb.append("$B");
serDic((PdfDictionary)obj, level - 1, bb);
if (level > 0) {
md5.reset();
bb.append(md5.digest(PdfReader.getStreamBytesRaw((PRStream)obj)));
}
}
else if (obj.isDictionary()) {
serDic((PdfDictionary)obj, level - 1, bb);
}
else if (obj.isArray()) {
serArray((PdfArray)obj, level - 1, bb);
}
else if (obj.isString()) {
bb.append("$S").append(obj.toString());
}
else if (obj.isName()) {
bb.append("$N").append(obj.toString());
}
else
bb.append("$L").append(obj.toString());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
private void serDic(PdfDictionary dic, int level, ByteBuffer bb) throws IOException {
bb.append("$D");
if (level <= 0)
return;
Object[] keys = dic.getKeys().toArray();
Arrays.sort(keys);
for (int k = 0; k < keys.length; ++k) {
serObject((PdfObject)keys[k], level, bb);
serObject(dic.get((PdfName)keys[k]), level, bb);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
private void serArray(PdfArray array, int level, ByteBuffer bb) throws IOException {
bb.append("$A");
if (level <= 0)
return;
for (int k = 0; k < array.size(); ++k) {
serObject(array.getPdfObject(k), level, bb);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FilterHandlers.java
public byte[] decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary) throws IOException {
b = PdfReader.FlateDecode(b);
b = PdfReader.decodePredictor(b, decodeParams);
return b;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FilterHandlers.java
public byte[] decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary) throws IOException {
b = PdfReader.ASCIIHexDecode(b);
return b;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FilterHandlers.java
public byte[] decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary) throws IOException {
b = PdfReader.ASCII85Decode(b);
return b;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FilterHandlers.java
public byte[] decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary) throws IOException {
b = PdfReader.LZWDecode(b);
b = PdfReader.decodePredictor(b, decodeParams);
return b;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FilterHandlers.java
public byte[] decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary) throws IOException {
PdfNumber wn = (PdfNumber)PdfReader.getPdfObjectRelease(streamDictionary.get(PdfName.WIDTH));
PdfNumber hn = (PdfNumber)PdfReader.getPdfObjectRelease(streamDictionary.get(PdfName.HEIGHT));
if (wn == null || hn == null)
throw new UnsupportedPdfException(MessageLocalization.getComposedMessage("filter.ccittfaxdecode.is.only.supported.for.images"));
int width = wn.intValue();
int height = hn.intValue();
PdfDictionary param = decodeParams instanceof PdfDictionary ? (PdfDictionary)decodeParams : null;
int k = 0;
boolean blackIs1 = false;
boolean byteAlign = false;
if (param != null) {
PdfNumber kn = param.getAsNumber(PdfName.K);
if (kn != null)
k = kn.intValue();
PdfBoolean bo = param.getAsBoolean(PdfName.BLACKIS1);
if (bo != null)
blackIs1 = bo.booleanValue();
bo = param.getAsBoolean(PdfName.ENCODEDBYTEALIGN);
if (bo != null)
byteAlign = bo.booleanValue();
}
byte[] outBuf = new byte[(width + 7) / 8 * height];
TIFFFaxDecompressor decoder = new TIFFFaxDecompressor();
if (k == 0 || k > 0) {
int tiffT4Options = k > 0 ? TIFFConstants.GROUP3OPT_2DENCODING : 0;
tiffT4Options |= byteAlign ? TIFFConstants.GROUP3OPT_FILLBITS : 0;
decoder.SetOptions(1, TIFFConstants.COMPRESSION_CCITTFAX3, tiffT4Options, 0);
decoder.decodeRaw(outBuf, b, width, height);
if (decoder.fails > 0) {
byte[] outBuf2 = new byte[(width + 7) / 8 * height];
int oldFails = decoder.fails;
decoder.SetOptions(1, TIFFConstants.COMPRESSION_CCITTRLE, tiffT4Options, 0);
decoder.decodeRaw(outBuf2, b, width, height);
if (decoder.fails < oldFails) {
outBuf = outBuf2;
}
}
}
else {
TIFFFaxDecoder deca = new TIFFFaxDecoder(1, width, height);
deca.decodeT6(outBuf, b, 0, height, 0);
}
if (!blackIs1) {
int len = outBuf.length;
for (int t = 0; t < len; ++t) {
outBuf[t] ^= 0xff;
}
}
b = outBuf;
return b;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FilterHandlers.java
public byte[] decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary) throws IOException {
return b;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FilterHandlers.java
public byte[] decode(byte[] b, PdfName filterName, PdfObject decodeParams, PdfDictionary streamDictionary) throws IOException {
// allocate the output buffer
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte dupCount = -1;
for(int i = 0; i < b.length; i++){
dupCount = b[i];
if (dupCount == -128) break; // this is implicit end of data
if (dupCount >= 0 && dupCount <= 127){
int bytesToCopy = dupCount+1;
baos.write(b, i, bytesToCopy);
i+=bytesToCopy;
} else {
// make dupcount copies of the next byte
i++;
for(int j = 0; j < 1-(int)(dupCount);j++){
baos.write(b[i]);
}
}
}
return baos.toByteArray();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfNameTree.java
public static PdfDictionary writeTree(HashMap<String, ? extends PdfObject> items, PdfWriter writer) throws IOException {
if (items.isEmpty())
return null;
String names[] = new String[items.size()];
names = items.keySet().toArray(names);
Arrays.sort(names);
if (names.length <= leafSize) {
PdfDictionary dic = new PdfDictionary();
PdfArray ar = new PdfArray();
for (int k = 0; k < names.length; ++k) {
ar.add(new PdfString(names[k], null));
ar.add(items.get(names[k]));
}
dic.put(PdfName.NAMES, ar);
return dic;
}
int skip = leafSize;
PdfIndirectReference kids[] = new PdfIndirectReference[(names.length + leafSize - 1) / leafSize];
for (int k = 0; k < kids.length; ++k) {
int offset = k * leafSize;
int end = Math.min(offset + leafSize, names.length);
PdfDictionary dic = new PdfDictionary();
PdfArray arr = new PdfArray();
arr.add(new PdfString(names[offset], null));
arr.add(new PdfString(names[end - 1], null));
dic.put(PdfName.LIMITS, arr);
arr = new PdfArray();
for (; offset < end; ++offset) {
arr.add(new PdfString(names[offset], null));
arr.add(items.get(names[offset]));
}
dic.put(PdfName.NAMES, arr);
kids[k] = writer.addToBody(dic).getIndirectReference();
}
int top = kids.length;
while (true) {
if (top <= leafSize) {
PdfArray arr = new PdfArray();
for (int k = 0; k < top; ++k)
arr.add(kids[k]);
PdfDictionary dic = new PdfDictionary();
dic.put(PdfName.KIDS, arr);
return dic;
}
skip *= leafSize;
int tt = (names.length + skip - 1 )/ skip;
for (int k = 0; k < tt; ++k) {
int offset = k * leafSize;
int end = Math.min(offset + leafSize, top);
PdfDictionary dic = new PdfDictionary();
PdfArray arr = new PdfArray();
arr.add(new PdfString(names[k * skip], null));
arr.add(new PdfString(names[Math.min((k + 1) * skip, names.length) - 1], null));
dic.put(PdfName.LIMITS, arr);
arr = new PdfArray();
for (; offset < end; ++offset) {
arr.add(kids[offset]);
}
dic.put(PdfName.KIDS, arr);
kids[k] = writer.addToBody(dic).getIndirectReference();
}
top = tt;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
private void readLookupListTable(int lookupListTableLocation)
throws IOException {
rf.seek(lookupListTableLocation);
int lookupCount = rf.readShort();
List<Integer> lookupTableOffsets = new ArrayList<Integer>();
for (int i = 0; i < lookupCount; i++) {
int lookupTableOffset = rf.readShort();
lookupTableOffsets.add(lookupTableOffset);
}
// read LookUp tables
for (int i = 0; i < lookupCount; i++) {
// LOG.debug("#############lookupIndex=" + i);
int lookupTableOffset = lookupTableOffsets.get(i);
readLookupTable(lookupListTableLocation + lookupTableOffset);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
private void readLookupTable(int lookupTableLocation) throws IOException {
rf.seek(lookupTableLocation);
int lookupType = rf.readShort();
// LOG.debug("lookupType=" + lookupType);
// skip 2 bytes for the field `lookupFlag`
rf.skipBytes(2);
int subTableCount = rf.readShort();
// LOG.debug("subTableCount=" + subTableCount);
List<Integer> subTableOffsets = new ArrayList<Integer>();
for (int i = 0; i < subTableCount; i++) {
int subTableOffset = rf.readShort();
subTableOffsets.add(subTableOffset);
}
for (int subTableOffset : subTableOffsets) {
// LOG.debug("subTableOffset=" + subTableOffset);
readSubTable(lookupType, lookupTableLocation + subTableOffset);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
protected final List<Integer> readCoverageFormat(int coverageLocation)
throws IOException {
rf.seek(coverageLocation);
int coverageFormat = rf.readShort();
List<Integer> glyphIds;
if (coverageFormat == 1) {
int glyphCount = rf.readShort();
glyphIds = new ArrayList<Integer>(glyphCount);
for (int i = 0; i < glyphCount; i++) {
int coverageGlyphId = rf.readShort();
glyphIds.add(coverageGlyphId);
}
} else if (coverageFormat == 2) {
int rangeCount = rf.readShort();
glyphIds = new ArrayList<Integer>();
for (int i = 0; i < rangeCount; i++) {
readRangeRecord(glyphIds);
}
} else {
throw new UnsupportedOperationException("Invalid coverage format: "
+ coverageFormat);
}
return Collections.unmodifiableList(glyphIds);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
private void readRangeRecord(List<Integer> glyphIds) throws IOException {
int startGlyphId = rf.readShort();
int endGlyphId = rf.readShort();
int startCoverageIndex = rf.readShort();
for (int glyphId = startGlyphId; glyphId <= endGlyphId; glyphId++) {
glyphIds.add(glyphId);
}
// LOG.debug("^^^^^^^^^Coverage Format 2.... "
// + "startGlyphId=" + startGlyphId
// + ", endGlyphId=" + endGlyphId
// + ", startCoverageIndex=" + startCoverageIndex
// + "\n, glyphIds" + glyphIds);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
private void readScriptListTable(int scriptListTableLocationOffset)
throws IOException {
rf.seek(scriptListTableLocationOffset);
// Number of ScriptRecords
int scriptCount = rf.readShort();
Map<String, Integer> scriptRecords = new HashMap<String, Integer>(
scriptCount);
for (int i = 0; i < scriptCount; i++) {
readScriptRecord(scriptListTableLocationOffset, scriptRecords);
}
List<String> supportedLanguages = new ArrayList<String>(scriptCount);
for (String scriptName : scriptRecords.keySet()) {
readScriptTable(scriptRecords.get(scriptName));
supportedLanguages.add(scriptName);
}
this.supportedLanguages = Collections.unmodifiableList(supportedLanguages);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
private void readScriptRecord(final int scriptListTableLocationOffset,
Map<String, Integer> scriptRecords) throws IOException {
String scriptTag = rf.readString(4, "utf-8");
int scriptOffset = rf.readShort();
scriptRecords.put(scriptTag, scriptListTableLocationOffset
+ scriptOffset);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
private void readScriptTable(final int scriptTableLocationOffset)
throws IOException {
rf.seek(scriptTableLocationOffset);
int defaultLangSys = rf.readShort();
int langSysCount = rf.readShort();
if (langSysCount > 0) {
Map<String, Integer> langSysRecords = new LinkedHashMap<String, Integer>(
langSysCount);
for (int i = 0; i < langSysCount; i++) {
readLangSysRecord(langSysRecords);
}
// read LangSys tables
for (String langSysTag : langSysRecords.keySet()) {
readLangSysTable(scriptTableLocationOffset
+ langSysRecords.get(langSysTag));
}
}
// read default LangSys table
readLangSysTable(scriptTableLocationOffset + defaultLangSys);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
private void readLangSysRecord(Map<String, Integer> langSysRecords)
throws IOException {
String langSysTag = rf.readString(4, "utf-8");
int langSys = rf.readShort();
langSysRecords.put(langSysTag, langSys);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
private void readLangSysTable(final int langSysTableLocationOffset)
throws IOException {
rf.seek(langSysTableLocationOffset);
int lookupOrderOffset = rf.readShort();
LOG.debug("lookupOrderOffset=" + lookupOrderOffset);
int reqFeatureIndex = rf.readShort();
LOG.debug("reqFeatureIndex=" + reqFeatureIndex);
int featureCount = rf.readShort();
List<Short> featureListIndices = new ArrayList<Short>(featureCount);
for (int i = 0; i < featureCount; i++) {
featureListIndices.add(rf.readShort());
}
LOG.debug("featureListIndices=" + featureListIndices);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
private void readFeatureListTable(final int featureListTableLocationOffset)
throws IOException {
rf.seek(featureListTableLocationOffset);
int featureCount = rf.readShort();
LOG.debug("featureCount=" + featureCount);
Map<String, Short> featureRecords = new LinkedHashMap<String, Short>(
featureCount);
for (int i = 0; i < featureCount; i++) {
featureRecords.put(rf.readString(4, "utf-8"), rf.readShort());
}
for (String featureName : featureRecords.keySet()) {
LOG.debug("*************featureName=" + featureName);
readFeatureTable(featureListTableLocationOffset
+ featureRecords.get(featureName));
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
private void readFeatureTable(final int featureTableLocationOffset)
throws IOException {
rf.seek(featureTableLocationOffset);
int featureParamsOffset = rf.readShort();
LOG.debug("featureParamsOffset=" + featureParamsOffset);
int lookupCount = rf.readShort();
LOG.debug("lookupCount=" + lookupCount);
List<Short> lookupListIndices = new ArrayList<Short>(lookupCount);
for (int i = 0; i < lookupCount; i++) {
lookupListIndices.add(rf.readShort());
}
// LOG.debug("lookupListIndices=" + lookupListIndices);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
private TableHeader readHeader() throws IOException {
rf.seek(tableLocation);
// 32 bit signed
int version = rf.readInt();
// 16 bit unsigned
int scriptListOffset = rf.readUnsignedShort();
int featureListOffset = rf.readUnsignedShort();
int lookupListOffset = rf.readUnsignedShort();
// LOG.debug("version=" + version);
// LOG.debug("scriptListOffset=" + scriptListOffset);
// LOG.debug("featureListOffset=" + featureListOffset);
// LOG.debug("lookupListOffset=" + lookupListOffset);
TableHeader header = new TableHeader(version, scriptListOffset,
featureListOffset, lookupListOffset);
return header;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
Override
protected void readSubTable(int lookupType, int subTableLocation) throws IOException {
if (lookupType == 1) {
readSingleSubstitutionSubtable(subTableLocation);
} else if (lookupType == 4) {
readLigatureSubstitutionSubtable(subTableLocation);
} else {
System.err.println("LookupType " + lookupType + " is not yet handled for " + GlyphSubstitutionTableReader.class.getSimpleName());
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
private void readSingleSubstitutionSubtable(int subTableLocation) throws IOException {
rf.seek(subTableLocation);
int substFormat = rf.readShort();
LOG.debug("substFormat=" + substFormat);
if (substFormat == 1) {
int coverage = rf.readShort();
LOG.debug("coverage=" + coverage);
int deltaGlyphID = rf.readShort();
LOG.debug("deltaGlyphID=" + deltaGlyphID);
List<Integer> coverageGlyphIds = readCoverageFormat(subTableLocation + coverage);
for (int coverageGlyphId : coverageGlyphIds) {
int substituteGlyphId = coverageGlyphId + deltaGlyphID;
rawLigatureSubstitutionMap.put(substituteGlyphId, Arrays.asList(coverageGlyphId));
}
} else if (substFormat == 2) {
System.err.println("LookupType 1 :: substFormat 2 is not yet handled by " + GlyphSubstitutionTableReader.class.getSimpleName());
} else {
throw new IllegalArgumentException("Bad substFormat: " + substFormat);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
private void readLigatureSubstitutionSubtable(int ligatureSubstitutionSubtableLocation) throws IOException {
rf.seek(ligatureSubstitutionSubtableLocation);
int substFormat = rf.readShort();
LOG.debug("substFormat=" + substFormat);
if (substFormat != 1) {
throw new IllegalArgumentException("The expected SubstFormat is 1");
}
int coverage = rf.readShort();
LOG.debug("coverage=" + coverage);
int ligSetCount = rf.readShort();
List<Integer> ligatureOffsets = new ArrayList<Integer>(ligSetCount);
for (int i = 0; i < ligSetCount; i++) {
int ligatureOffset = rf.readShort();
ligatureOffsets.add(ligatureOffset);
}
List<Integer> coverageGlyphIds = readCoverageFormat(ligatureSubstitutionSubtableLocation + coverage);
if (ligSetCount != coverageGlyphIds.size()) {
throw new IllegalArgumentException("According to the OpenTypeFont specifications, the coverage count should be equal to the no. of LigatureSetTables");
}
for (int i = 0; i < ligSetCount; i++) {
int coverageGlyphId = coverageGlyphIds.get(i);
int ligatureOffset = ligatureOffsets.get(i);
LOG.debug("ligatureOffset=" + ligatureOffset);
readLigatureSetTable(ligatureSubstitutionSubtableLocation + ligatureOffset, coverageGlyphId);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
private void readLigatureSetTable(int ligatureSetTableLocation, int coverageGlyphId) throws IOException {
rf.seek(ligatureSetTableLocation);
int ligatureCount = rf.readShort();
LOG.debug("ligatureCount=" + ligatureCount);
List<Integer> ligatureOffsets = new ArrayList<Integer>(ligatureCount);
for (int i = 0; i < ligatureCount; i++) {
int ligatureOffset = rf.readShort();
ligatureOffsets.add(ligatureOffset);
}
for (int ligatureOffset : ligatureOffsets) {
readLigatureTable(ligatureSetTableLocation + ligatureOffset, coverageGlyphId);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
private void readLigatureTable(int ligatureTableLocation, int coverageGlyphId) throws IOException {
rf.seek(ligatureTableLocation);
int ligGlyph = rf.readShort();
LOG.debug("ligGlyph=" + ligGlyph);
int compCount = rf.readShort();
List<Integer> glyphIdList = new ArrayList<Integer>();
glyphIdList.add(coverageGlyphId);
for (int i = 0; i < compCount - 1; i++) {
int glyphId = rf.readShort();
glyphIdList.add(glyphId);
}
LOG.debug("glyphIdList=" + glyphIdList);
List<Integer> previousValue = rawLigatureSubstitutionMap.put(ligGlyph, glyphIdList);
if (previousValue != null) {
LOG.warn("!!!!!!!!!!glyphId=" + ligGlyph
+ ",\npreviousValue=" + previousValue
+ ",\ncurrentVal=" + glyphIdList);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphPositioningTableReader.java
Override
protected void readSubTable(int lookupType, int subTableLocation) throws IOException {
if (lookupType == 1) {
readLookUpType_1(subTableLocation);
} else if (lookupType == 4) {
readLookUpType_4(subTableLocation);
} else if (lookupType == 8) {
readLookUpType_8(subTableLocation);
} else {
System.err.println("The lookupType " + lookupType + " is not yet supported by " + GlyphPositioningTableReader.class.getSimpleName());
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphPositioningTableReader.java
private void readLookUpType_1(int lookupTableLocation) throws IOException {
rf.seek(lookupTableLocation);
int posFormat = rf.readShort();
if (posFormat == 1) {
LOG.debug("Reading `Look Up Type 1, Format 1` ....");
int coverageOffset = rf.readShort();
int valueFormat = rf.readShort();
// LOG.debug("valueFormat=" + valueFormat);
//check if XPlacement should be read
if ((valueFormat & 1) == 1) {
int xPlacement = rf.readShort();
LOG.debug("xPlacement=" + xPlacement);
}
//check if YPlacement should be read
if ((valueFormat & 2) ==2) {
int yPlacement = rf.readShort();
LOG.debug("yPlacement=" + yPlacement);
}
List<Integer> glyphCodes = readCoverageFormat(lookupTableLocation + coverageOffset);
LOG.debug("glyphCodes=" + glyphCodes);
} else {
System.err.println("The PosFormat " + posFormat + " for `LookupType 1` is not yet supported by " + GlyphPositioningTableReader.class.getSimpleName());
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphPositioningTableReader.java
private void readLookUpType_4(int lookupTableLocation) throws IOException {
rf.seek(lookupTableLocation);
int posFormat = rf.readShort();
if (posFormat == 1) {
LOG.debug("Reading `Look Up Type 4, Format 1` ....");
int markCoverageOffset = rf.readShort();
int baseCoverageOffset = rf.readShort();
int classCount = rf.readShort();
int markArrayOffset = rf.readShort();
int baseArrayOffset = rf.readShort();
List<Integer> markCoverages = readCoverageFormat(lookupTableLocation + markCoverageOffset);
LOG.debug("markCoverages=" + markCoverages);
List<Integer> baseCoverages = readCoverageFormat(lookupTableLocation + baseCoverageOffset);
LOG.debug("baseCoverages=" + baseCoverages);
readMarkArrayTable(lookupTableLocation + markArrayOffset);
readBaseArrayTable(lookupTableLocation + baseArrayOffset, classCount);
} else {
System.err.println("The posFormat " + posFormat + " is not supported by " + GlyphPositioningTableReader.class.getSimpleName());
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphPositioningTableReader.java
private void readLookUpType_8(int lookupTableLocation) throws IOException {
rf.seek(lookupTableLocation);
int posFormat = rf.readShort();
if (posFormat == 3) {
LOG.debug("Reading `Look Up Type 8, Format 3` ....");
readChainingContextPositioningFormat_3(lookupTableLocation);
} else {
System.err.println("The posFormat " + posFormat + " for `Look Up Type 8` is not supported by " + GlyphPositioningTableReader.class.getSimpleName());
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphPositioningTableReader.java
private void readChainingContextPositioningFormat_3(int lookupTableLocation) throws IOException {
int backtrackGlyphCount = rf.readShort();
LOG.debug("backtrackGlyphCount=" + backtrackGlyphCount);
List<Integer> backtrackGlyphOffsets = new ArrayList<Integer>(backtrackGlyphCount);
for (int i = 0; i < backtrackGlyphCount; i++) {
int backtrackGlyphOffset = rf.readShort();
backtrackGlyphOffsets.add(backtrackGlyphOffset);
}
int inputGlyphCount = rf.readShort();
LOG.debug("inputGlyphCount=" + inputGlyphCount);
List<Integer>inputGlyphOffsets = new ArrayList<Integer>(inputGlyphCount);
for (int i = 0; i < inputGlyphCount; i++) {
int inputGlyphOffset = rf.readShort();
inputGlyphOffsets.add(inputGlyphOffset);
}
int lookaheadGlyphCount = rf.readShort();
LOG.debug("lookaheadGlyphCount=" + lookaheadGlyphCount);
List<Integer>lookaheadGlyphOffsets = new ArrayList<Integer>(lookaheadGlyphCount);
for (int i = 0; i < lookaheadGlyphCount; i++) {
int lookaheadGlyphOffset = rf.readShort();
lookaheadGlyphOffsets.add(lookaheadGlyphOffset);
}
int posCount = rf.readShort();
LOG.debug("posCount=" + posCount);
List<PosLookupRecord> posLookupRecords = new ArrayList<PosLookupRecord>(posCount);
for (int i = 0; i < posCount; i++) {
int sequenceIndex = rf.readShort();
int lookupListIndex = rf.readShort();
LOG.debug("sequenceIndex=" + sequenceIndex + ", lookupListIndex=" + lookupListIndex);
posLookupRecords.add(new PosLookupRecord(sequenceIndex, lookupListIndex));
}
for (int backtrackGlyphOffset : backtrackGlyphOffsets) {
List<Integer> backtrackGlyphs = readCoverageFormat(lookupTableLocation + backtrackGlyphOffset);
LOG.debug("backtrackGlyphs=" + backtrackGlyphs);
}
for (int inputGlyphOffset : inputGlyphOffsets) {
List<Integer> inputGlyphs = readCoverageFormat(lookupTableLocation + inputGlyphOffset);
LOG.debug("inputGlyphs=" + inputGlyphs);
}
for (int lookaheadGlyphOffset : lookaheadGlyphOffsets) {
List<Integer> lookaheadGlyphs = readCoverageFormat(lookupTableLocation + lookaheadGlyphOffset);
LOG.debug("lookaheadGlyphs=" + lookaheadGlyphs);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphPositioningTableReader.java
private void readMarkArrayTable(int markArrayLocation) throws IOException {
rf.seek(markArrayLocation);
int markCount = rf.readShort();
List<MarkRecord> markRecords = new ArrayList<GlyphPositioningTableReader.MarkRecord>();
for (int i = 0; i < markCount; i++) {
markRecords.add(readMarkRecord());
}
for (MarkRecord markRecord : markRecords) {
readAnchorTable(markArrayLocation + markRecord.markAnchorOffset);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphPositioningTableReader.java
private MarkRecord readMarkRecord() throws IOException {
int markClass = rf.readShort();
int markAnchorOffset = rf.readShort();
return new MarkRecord(markClass, markAnchorOffset);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphPositioningTableReader.java
private void readAnchorTable(int anchorTableLocation) throws IOException {
rf.seek(anchorTableLocation);
int anchorFormat = rf.readShort();
if (anchorFormat != 1) {
System.err.println("The extra features of the AnchorFormat " + anchorFormat + " will not be used");
}
int x = rf.readShort();
int y = rf.readShort();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphPositioningTableReader.java
private void readBaseArrayTable(int baseArrayTableLocation, int classCount) throws IOException {
rf.seek(baseArrayTableLocation);
int baseCount = rf.readShort();
Set<Integer> baseAnchors = new HashSet<Integer>();
for (int i = 0; i < baseCount; i++) {
//read BaseRecord
for (int k = 0; k < classCount; k++) {
int baseAnchor = rf.readShort();
baseAnchors.add(baseAnchor);
}
}
// LOG.debug(baseAnchors.size());
for (int baseAnchor : baseAnchors) {
readAnchorTable(baseArrayTableLocation + baseAnchor);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CidLocationFromByte.java
public PRTokeniser getLocation(String location) throws IOException {
return new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(data)));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
public Map<Integer, Integer> createReverseMapping() throws IOException {
Map<Integer, Integer> result = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, String> entry : singleByteMappings.entrySet()) {
result.put(convertToInt(entry.getValue()), entry.getKey());
}
for (Map.Entry<Integer, String> entry : doubleByteMappings.entrySet()) {
result.put(convertToInt(entry.getValue()), entry.getKey());
}
return result;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
public Map<Integer, Integer> createDirectMapping() throws IOException {
Map<Integer, Integer> result = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, String> entry : singleByteMappings.entrySet()) {
result.put(entry.getKey(), convertToInt(entry.getValue()));
}
for (Map.Entry<Integer, String> entry : doubleByteMappings.entrySet()) {
result.put(entry.getKey(), convertToInt(entry.getValue()));
}
return result;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
private int convertToInt(String s) throws IOException {
byte[] b = s.getBytes("UTF-16BE");
int value = 0;
for (int i = 0; i < b.length - 1; i++) {
value += b[i] & 0xff;
value <<= 8;
}
value += b[b.length - 1] & 0xff;
return value;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
private String createStringFromBytes(byte[] bytes) throws IOException {
String retval = null;
if (bytes.length == 1) {
retval = new String(bytes);
} else {
retval = new String(bytes, "UTF-16BE");
}
return retval;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CidResource.java
public PRTokeniser getLocation(String location) throws IOException {
String fullName = BaseFont.RESOURCE_PATH + "cmaps/" + location;
InputStream inp = BaseFont.getResourceStream(fullName);
if (inp == null)
throw new IOException(MessageLocalization.getComposedMessage("the.cmap.1.was.not.found", fullName));
return new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(inp)));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapParserEx.java
public static void parseCid(String cmapName, AbstractCMap cmap, CidLocation location) throws IOException {
parseCid(cmapName, cmap, location, 0);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapParserEx.java
private static void parseCid(String cmapName, AbstractCMap cmap, CidLocation location, int level) throws IOException {
if (level >= MAXLEVEL)
return;
PRTokeniser inp = location.getLocation(cmapName);
try {
ArrayList<PdfObject> list = new ArrayList<PdfObject>();
PdfContentParser cp = new PdfContentParser(inp);
int maxExc = 50;
while (true) {
try {
cp.parse(list);
}
catch (Exception ex) {
if (--maxExc < 0)
break;
continue;
}
if (list.isEmpty())
break;
String last = list.get(list.size() - 1).toString();
if (level == 0 && list.size() == 3 && last.equals(DEF)) {
PdfObject key = list.get(0);
if (PdfName.REGISTRY.equals(key))
cmap.setRegistry(list.get(1).toString());
else if (PdfName.ORDERING.equals(key))
cmap.setOrdering(list.get(1).toString());
else if (CMAPNAME.equals(key))
cmap.setName(list.get(1).toString());
else if (PdfName.SUPPLEMENT.equals(key)) {
try {
cmap.setSupplement(((PdfNumber)list.get(1)).intValue());
}
catch (Exception ex) {}
}
}
else if ((last.equals(ENDCIDCHAR) || last.equals(ENDBFCHAR)) && list.size() >= 3) {
int lmax = list.size() - 2;
for (int k = 0; k < lmax; k += 2) {
if (list.get(k) instanceof PdfString) {
cmap.addChar((PdfString)list.get(k), list.get(k + 1));
}
}
}
else if ((last.equals(ENDCIDRANGE) || last.equals(ENDBFRANGE)) && list.size() >= 4) {
int lmax = list.size() - 3;
for (int k = 0; k < lmax; k += 3) {
if (list.get(k) instanceof PdfString && list.get(k + 1) instanceof PdfString) {
cmap.addRange((PdfString)list.get(k), (PdfString)list.get(k + 1), list.get(k + 2));
}
}
}
else if (last.equals(USECMAP) && list.size() == 2 && list.get(0) instanceof PdfName) {
parseCid(PdfName.decodeName(list.get(0).toString()), cmap, location, level + 1);
}
}
}
finally {
inp.close();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapCache.java
public static CMapUniCid getCachedCMapUniCid(String name) throws IOException {
CMapUniCid cmap = null;
synchronized (cacheUniCid) {
cmap = cacheUniCid.get(name);
}
if (cmap == null) {
cmap = new CMapUniCid();
CMapParserEx.parseCid(name, cmap, new CidResource());
synchronized (cacheUniCid) {
cacheUniCid.put(name, cmap);
}
}
return cmap;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapCache.java
public static CMapCidUni getCachedCMapCidUni(String name) throws IOException {
CMapCidUni cmap = null;
synchronized (cacheCidUni) {
cmap = cacheCidUni.get(name);
}
if (cmap == null) {
cmap = new CMapCidUni();
CMapParserEx.parseCid(name, cmap, new CidResource());
synchronized (cacheCidUni) {
cacheCidUni.put(name, cmap);
}
}
return cmap;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapCache.java
public static CMapCidByte getCachedCMapCidByte(String name) throws IOException {
CMapCidByte cmap = null;
synchronized (cacheCidByte) {
cmap = cacheCidByte.get(name);
}
if (cmap == null) {
cmap = new CMapCidByte();
CMapParserEx.parseCid(name, cmap, new CidResource());
synchronized (cacheCidByte) {
cacheCidByte.put(name, cmap);
}
}
return cmap;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapCache.java
public static CMapByteCid getCachedCMapByteCid(String name) throws IOException {
CMapByteCid cmap = null;
synchronized (cacheByteCid) {
cmap = cacheByteCid.get(name);
}
if (cmap == null) {
cmap = new CMapByteCid();
CMapParserEx.parseCid(name, cmap, new CidResource());
synchronized (cacheByteCid) {
cacheByteCid.put(name, cmap);
}
}
return cmap;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TextField.java
public PdfAppearance getAppearance() throws IOException, DocumentException {
PdfAppearance app = getBorderAppearance();
app.beginVariableText();
if (text == null || text.length() == 0) {
app.endVariableText();
return app;
}
boolean borderExtra = borderStyle == PdfBorderDictionary.STYLE_BEVELED || borderStyle == PdfBorderDictionary.STYLE_INSET;
float h = box.getHeight() - borderWidth * 2 - extraMarginTop;
float bw2 = borderWidth;
if (borderExtra) {
h -= borderWidth * 2;
bw2 *= 2;
}
float offsetX = Math.max(bw2, 1);
float offX = Math.min(bw2, offsetX);
app.saveState();
app.rectangle(offX, offX, box.getWidth() - 2 * offX, box.getHeight() - 2 * offX);
app.clip();
app.newPath();
String ptext;
if ((options & PASSWORD) != 0)
ptext = obfuscatePassword(text);
else if ((options & MULTILINE) == 0)
ptext = removeCRLF(text);
else
ptext = text; //fixed by Kazuya Ujihara (ujihara.jp)
BaseFont ufont = getRealFont();
BaseColor fcolor = textColor == null ? GrayColor.GRAYBLACK : textColor;
int rtl = checkRTL(ptext) ? PdfWriter.RUN_DIRECTION_LTR : PdfWriter.RUN_DIRECTION_NO_BIDI;
float usize = fontSize;
Phrase phrase = composePhrase(ptext, ufont, fcolor, usize);
if ((options & MULTILINE) != 0) {
float width = box.getWidth() - 4 * offsetX - extraMarginLeft;
float factor = ufont.getFontDescriptor(BaseFont.BBOXURY, 1) - ufont.getFontDescriptor(BaseFont.BBOXLLY, 1);
ColumnText ct = new ColumnText(null);
if (usize == 0) {
usize = h / factor;
if (usize > 4) {
if (usize > 12)
usize = 12;
float step = Math.max((usize - 4) / 10, 0.2f);
ct.setSimpleColumn(0, -h, width, 0);
ct.setAlignment(alignment);
ct.setRunDirection(rtl);
for (; usize > 4; usize -= step) {
ct.setYLine(0);
changeFontSize(phrase, usize);
ct.setText(phrase);
ct.setLeading(factor * usize);
int status = ct.go(true);
if ((status & ColumnText.NO_MORE_COLUMN) == 0)
break;
}
}
if (usize < 4)
usize = 4;
}
changeFontSize(phrase, usize);
ct.setCanvas(app);
float leading = usize * factor;
float offsetY = offsetX + h - ufont.getFontDescriptor(BaseFont.BBOXURY, usize);
ct.setSimpleColumn(extraMarginLeft + 2 * offsetX, -20000, box.getWidth() - 2 * offsetX, offsetY + leading);
ct.setLeading(leading);
ct.setAlignment(alignment);
ct.setRunDirection(rtl);
ct.setText(phrase);
ct.go();
}
else {
if (usize == 0) {
float maxCalculatedSize = h / (ufont.getFontDescriptor(BaseFont.BBOXURX, 1) - ufont.getFontDescriptor(BaseFont.BBOXLLY, 1));
changeFontSize(phrase, 1);
float wd = ColumnText.getWidth(phrase, rtl, 0);
if (wd == 0)
usize = maxCalculatedSize;
else
usize = Math.min(maxCalculatedSize, (box.getWidth() - extraMarginLeft - 4 * offsetX) / wd);
if (usize < 4)
usize = 4;
}
changeFontSize(phrase, usize);
float offsetY = offX + (box.getHeight() - 2*offX - ufont.getFontDescriptor(BaseFont.ASCENT, usize)) / 2;
if (offsetY < offX)
offsetY = offX;
if (offsetY - offX < -ufont.getFontDescriptor(BaseFont.DESCENT, usize)) {
float ny = -ufont.getFontDescriptor(BaseFont.DESCENT, usize) + offX;
float dy = box.getHeight() - offX - ufont.getFontDescriptor(BaseFont.ASCENT, usize);
offsetY = Math.min(ny, Math.max(offsetY, dy));
}
if ((options & COMB) != 0 && maxCharacterLength > 0) {
int textLen = Math.min(maxCharacterLength, ptext.length());
int position = 0;
if (alignment == Element.ALIGN_RIGHT)
position = maxCharacterLength - textLen;
else if (alignment == Element.ALIGN_CENTER)
position = (maxCharacterLength - textLen) / 2;
float step = (box.getWidth() - extraMarginLeft) / maxCharacterLength;
float start = step / 2 + position * step;
if (textColor == null)
app.setGrayFill(0);
else
app.setColorFill(textColor);
app.beginText();
for (int k = 0; k < phrase.size(); ++k) {
Chunk ck = (Chunk)phrase.get(k);
BaseFont bf = ck.getFont().getBaseFont();
app.setFontAndSize(bf, usize);
StringBuffer sb = ck.append("");
for (int j = 0; j < sb.length(); ++j) {
String c = sb.substring(j, j + 1);
float wd = bf.getWidthPoint(c, usize);
app.setTextMatrix(extraMarginLeft + start - wd / 2, offsetY - extraMarginTop);
app.showText(c);
start += step;
}
}
app.endText();
}
else {
float x;
switch (alignment) {
case Element.ALIGN_RIGHT:
x = extraMarginLeft + box.getWidth() - 2 * offsetX;
break;
case Element.ALIGN_CENTER:
x = extraMarginLeft + box.getWidth() / 2;
break;
default:
x = extraMarginLeft + 2 * offsetX;
}
ColumnText.showTextAligned(app, alignment, phrase, x, offsetY - extraMarginTop, 0, rtl, 0);
}
}
app.restoreState();
app.endVariableText();
return app;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TextField.java
PdfAppearance getListAppearance() throws IOException, DocumentException {
PdfAppearance app = getBorderAppearance();
if (choices == null || choices.length == 0) {
return app;
}
app.beginVariableText();
int topChoice = getTopChoice();
BaseFont ufont = getRealFont();
float usize = fontSize;
if (usize == 0)
usize = 12;
boolean borderExtra = borderStyle == PdfBorderDictionary.STYLE_BEVELED || borderStyle == PdfBorderDictionary.STYLE_INSET;
float h = box.getHeight() - borderWidth * 2;
float offsetX = borderWidth;
if (borderExtra) {
h -= borderWidth * 2;
offsetX *= 2;
}
float leading = ufont.getFontDescriptor(BaseFont.BBOXURY, usize) - ufont.getFontDescriptor(BaseFont.BBOXLLY, usize);
int maxFit = (int)(h / leading) + 1;
int first = 0;
int last = 0;
first = topChoice;
last = first + maxFit;
if (last > choices.length)
last = choices.length;
topFirst = first;
app.saveState();
app.rectangle(offsetX, offsetX, box.getWidth() - 2 * offsetX, box.getHeight() - 2 * offsetX);
app.clip();
app.newPath();
BaseColor fcolor = textColor == null ? GrayColor.GRAYBLACK : textColor;
// background boxes for selected value[s]
app.setColorFill(new BaseColor(10, 36, 106));
for (int curVal = 0; curVal < choiceSelections.size(); ++curVal) {
int curChoice = (choiceSelections.get( curVal )).intValue();
// only draw selections within our display range... not strictly necessary with
// that clipping rect from above, but it certainly doesn't hurt either
if (curChoice >= first && curChoice <= last) {
app.rectangle(offsetX, offsetX + h - (curChoice - first + 1) * leading, box.getWidth() - 2 * offsetX, leading);
app.fill();
}
}
float xp = offsetX * 2;
float yp = offsetX + h - ufont.getFontDescriptor(BaseFont.BBOXURY, usize);
for (int idx = first; idx < last; ++idx, yp -= leading) {
String ptext = choices[idx];
int rtl = checkRTL(ptext) ? PdfWriter.RUN_DIRECTION_LTR : PdfWriter.RUN_DIRECTION_NO_BIDI;
ptext = removeCRLF(ptext);
// highlight selected values against their (presumably) darker background
BaseColor textCol = choiceSelections.contains( Integer.valueOf( idx )) ? GrayColor.GRAYWHITE : fcolor;
Phrase phrase = composePhrase(ptext, ufont, textCol, usize);
ColumnText.showTextAligned(app, Element.ALIGN_LEFT, phrase, xp, yp, 0, rtl, 0);
}
app.restoreState();
app.endVariableText();
return app;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TextField.java
public PdfFormField getTextField() throws IOException, DocumentException {
if (maxCharacterLength <= 0)
options &= ~COMB;
if ((options & COMB) != 0)
options &= ~MULTILINE;
PdfFormField field = PdfFormField.createTextField(writer, false, false, maxCharacterLength);
field.setWidget(box, PdfAnnotation.HIGHLIGHT_INVERT);
switch (alignment) {
case Element.ALIGN_CENTER:
field.setQuadding(PdfFormField.Q_CENTER);
break;
case Element.ALIGN_RIGHT:
field.setQuadding(PdfFormField.Q_RIGHT);
break;
}
if (rotation != 0)
field.setMKRotation(rotation);
if (fieldName != null) {
field.setFieldName(fieldName);
if (!"".equals(text))
field.setValueAsString(text);
if (defaultText != null)
field.setDefaultValueAsString(defaultText);
if ((options & READ_ONLY) != 0)
field.setFieldFlags(PdfFormField.FF_READ_ONLY);
if ((options & REQUIRED) != 0)
field.setFieldFlags(PdfFormField.FF_REQUIRED);
if ((options & MULTILINE) != 0)
field.setFieldFlags(PdfFormField.FF_MULTILINE);
if ((options & DO_NOT_SCROLL) != 0)
field.setFieldFlags(PdfFormField.FF_DONOTSCROLL);
if ((options & PASSWORD) != 0)
field.setFieldFlags(PdfFormField.FF_PASSWORD);
if ((options & FILE_SELECTION) != 0)
field.setFieldFlags(PdfFormField.FF_FILESELECT);
if ((options & DO_NOT_SPELL_CHECK) != 0)
field.setFieldFlags(PdfFormField.FF_DONOTSPELLCHECK);
if ((options & COMB) != 0)
field.setFieldFlags(PdfFormField.FF_COMB);
}
field.setBorderStyle(new PdfBorderDictionary(borderWidth, borderStyle, new PdfDashPattern(3)));
PdfAppearance tp = getAppearance();
field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
PdfAppearance da = (PdfAppearance)tp.getDuplicate();
da.setFontAndSize(getRealFont(), fontSize);
if (textColor == null)
da.setGrayFill(0);
else
da.setColorFill(textColor);
field.setDefaultAppearanceString(da);
if (borderColor != null)
field.setMKBorderColor(borderColor);
if (backgroundColor != null)
field.setMKBackgroundColor(backgroundColor);
switch (visibility) {
case HIDDEN:
field.setFlags(PdfAnnotation.FLAGS_PRINT | PdfAnnotation.FLAGS_HIDDEN);
break;
case VISIBLE_BUT_DOES_NOT_PRINT:
break;
case HIDDEN_BUT_PRINTABLE:
field.setFlags(PdfAnnotation.FLAGS_PRINT | PdfAnnotation.FLAGS_NOVIEW);
break;
default:
field.setFlags(PdfAnnotation.FLAGS_PRINT);
break;
}
return field;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TextField.java
public PdfFormField getComboField() throws IOException, DocumentException {
return getChoiceField(false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TextField.java
public PdfFormField getListField() throws IOException, DocumentException {
return getChoiceField(true);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TextField.java
protected PdfFormField getChoiceField(boolean isList) throws IOException, DocumentException {
options &= ~MULTILINE & ~COMB;
String uchoices[] = choices;
if (uchoices == null)
uchoices = new String[0];
int topChoice = getTopChoice();
if (uchoices.length > 0 && topChoice >= 0)
text = uchoices[topChoice];
if (text == null)
text = "";
PdfFormField field = null;
String mix[][] = null;
if (choiceExports == null) {
if (isList)
field = PdfFormField.createList(writer, uchoices, topChoice);
else
field = PdfFormField.createCombo(writer, (options & EDIT) != 0, uchoices, topChoice);
}
else {
mix = new String[uchoices.length][2];
for (int k = 0; k < mix.length; ++k)
mix[k][0] = mix[k][1] = uchoices[k];
int top = Math.min(uchoices.length, choiceExports.length);
for (int k = 0; k < top; ++k) {
if (choiceExports[k] != null)
mix[k][0] = choiceExports[k];
}
if (isList)
field = PdfFormField.createList(writer, mix, topChoice);
else
field = PdfFormField.createCombo(writer, (options & EDIT) != 0, mix, topChoice);
}
field.setWidget(box, PdfAnnotation.HIGHLIGHT_INVERT);
if (rotation != 0)
field.setMKRotation(rotation);
if (fieldName != null) {
field.setFieldName(fieldName);
if (uchoices.length > 0) {
if (mix != null) {
if (choiceSelections.size() < 2) {
field.setValueAsString(mix[topChoice][0]);
field.setDefaultValueAsString(mix[topChoice][0]);
} else {
writeMultipleValues( field, mix);
}
} else {
if (choiceSelections.size() < 2) {
field.setValueAsString(text);
field.setDefaultValueAsString(text);
} else {
writeMultipleValues( field, null );
}
}
}
if ((options & READ_ONLY) != 0)
field.setFieldFlags(PdfFormField.FF_READ_ONLY);
if ((options & REQUIRED) != 0)
field.setFieldFlags(PdfFormField.FF_REQUIRED);
if ((options & DO_NOT_SPELL_CHECK) != 0)
field.setFieldFlags(PdfFormField.FF_DONOTSPELLCHECK);
if ((options & MULTISELECT) != 0) {
field.setFieldFlags( PdfFormField.FF_MULTISELECT );
}
}
field.setBorderStyle(new PdfBorderDictionary(borderWidth, borderStyle, new PdfDashPattern(3)));
PdfAppearance tp;
if (isList) {
tp = getListAppearance();
if (topFirst > 0)
field.put(PdfName.TI, new PdfNumber(topFirst));
}
else
tp = getAppearance();
field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
PdfAppearance da = (PdfAppearance)tp.getDuplicate();
da.setFontAndSize(getRealFont(), fontSize);
if (textColor == null)
da.setGrayFill(0);
else
da.setColorFill(textColor);
field.setDefaultAppearanceString(da);
if (borderColor != null)
field.setMKBorderColor(borderColor);
if (backgroundColor != null)
field.setMKBackgroundColor(backgroundColor);
switch (visibility) {
case HIDDEN:
field.setFlags(PdfAnnotation.FLAGS_PRINT | PdfAnnotation.FLAGS_HIDDEN);
break;
case VISIBLE_BUT_DOES_NOT_PRINT:
break;
case HIDDEN_BUT_PRINTABLE:
field.setFlags(PdfAnnotation.FLAGS_PRINT | PdfAnnotation.FLAGS_NOVIEW);
break;
default:
field.setFlags(PdfAnnotation.FLAGS_PRINT);
break;
}
return field;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
byte[] process() throws IOException, DocumentException {
try {
rf.reOpen();
createTableDirectory();
readLoca();
flatGlyphs();
createNewGlyphTables();
locaTobytes();
assembleFont();
return outFont;
}
finally {
try {
rf.close();
}
catch (Exception e) {
// empty on purpose
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
protected void assembleFont() throws IOException {
int tableLocation[];
int fullFontSize = 0;
String tableNames[];
if (includeExtras)
tableNames = tableNamesExtra;
else {
if (includeCmap)
tableNames = tableNamesCmap;
else
tableNames = tableNamesSimple;
}
int tablesUsed = 2;
int len = 0;
for (int k = 0; k < tableNames.length; ++k) {
String name = tableNames[k];
if (name.equals("glyf") || name.equals("loca"))
continue;
tableLocation = tableDirectory.get(name);
if (tableLocation == null)
continue;
++tablesUsed;
fullFontSize += tableLocation[TABLE_LENGTH] + 3 & ~3;
}
fullFontSize += newLocaTableOut.length;
fullFontSize += newGlyfTable.length;
int ref = 16 * tablesUsed + 12;
fullFontSize += ref;
outFont = new byte[fullFontSize];
fontPtr = 0;
writeFontInt(0x00010000);
writeFontShort(tablesUsed);
int selector = entrySelectors[tablesUsed];
writeFontShort((1 << selector) * 16);
writeFontShort(selector);
writeFontShort((tablesUsed - (1 << selector)) * 16);
for (int k = 0; k < tableNames.length; ++k) {
String name = tableNames[k];
tableLocation = tableDirectory.get(name);
if (tableLocation == null)
continue;
writeFontString(name);
if (name.equals("glyf")) {
writeFontInt(calculateChecksum(newGlyfTable));
len = glyfTableRealSize;
}
else if (name.equals("loca")) {
writeFontInt(calculateChecksum(newLocaTableOut));
len = locaTableRealSize;
}
else {
writeFontInt(tableLocation[TABLE_CHECKSUM]);
len = tableLocation[TABLE_LENGTH];
}
writeFontInt(ref);
writeFontInt(len);
ref += len + 3 & ~3;
}
for (int k = 0; k < tableNames.length; ++k) {
String name = tableNames[k];
tableLocation = tableDirectory.get(name);
if (tableLocation == null)
continue;
if (name.equals("glyf")) {
System.arraycopy(newGlyfTable, 0, outFont, fontPtr, newGlyfTable.length);
fontPtr += newGlyfTable.length;
newGlyfTable = null;
}
else if (name.equals("loca")) {
System.arraycopy(newLocaTableOut, 0, outFont, fontPtr, newLocaTableOut.length);
fontPtr += newLocaTableOut.length;
newLocaTableOut = null;
}
else {
rf.seek(tableLocation[TABLE_OFFSET]);
rf.readFully(outFont, fontPtr, tableLocation[TABLE_LENGTH]);
fontPtr += tableLocation[TABLE_LENGTH] + 3 & ~3;
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
protected void createTableDirectory() throws IOException, DocumentException {
tableDirectory = new HashMap<String, int[]>();
rf.seek(directoryOffset);
int id = rf.readInt();
if (id != 0x00010000)
throw new DocumentException(MessageLocalization.getComposedMessage("1.is.not.a.true.type.file", fileName));
int num_tables = rf.readUnsignedShort();
rf.skipBytes(6);
for (int k = 0; k < num_tables; ++k) {
String tag = readStandardString(4);
int tableLocation[] = new int[3];
tableLocation[TABLE_CHECKSUM] = rf.readInt();
tableLocation[TABLE_OFFSET] = rf.readInt();
tableLocation[TABLE_LENGTH] = rf.readInt();
tableDirectory.put(tag, tableLocation);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
protected void readLoca() throws IOException, DocumentException {
int tableLocation[];
tableLocation = tableDirectory.get("head");
if (tableLocation == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "head", fileName));
rf.seek(tableLocation[TABLE_OFFSET] + HEAD_LOCA_FORMAT_OFFSET);
locaShortTable = rf.readUnsignedShort() == 0;
tableLocation = tableDirectory.get("loca");
if (tableLocation == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "loca", fileName));
rf.seek(tableLocation[TABLE_OFFSET]);
if (locaShortTable) {
int entries = tableLocation[TABLE_LENGTH] / 2;
locaTable = new int[entries];
for (int k = 0; k < entries; ++k)
locaTable[k] = rf.readUnsignedShort() * 2;
}
else {
int entries = tableLocation[TABLE_LENGTH] / 4;
locaTable = new int[entries];
for (int k = 0; k < entries; ++k)
locaTable[k] = rf.readInt();
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
protected void createNewGlyphTables() throws IOException {
newLocaTable = new int[locaTable.length];
int activeGlyphs[] = new int[glyphsInList.size()];
for (int k = 0; k < activeGlyphs.length; ++k)
activeGlyphs[k] = glyphsInList.get(k).intValue();
Arrays.sort(activeGlyphs);
int glyfSize = 0;
for (int k = 0; k < activeGlyphs.length; ++k) {
int glyph = activeGlyphs[k];
glyfSize += locaTable[glyph + 1] - locaTable[glyph];
}
glyfTableRealSize = glyfSize;
glyfSize = glyfSize + 3 & ~3;
newGlyfTable = new byte[glyfSize];
int glyfPtr = 0;
int listGlyf = 0;
for (int k = 0; k < newLocaTable.length; ++k) {
newLocaTable[k] = glyfPtr;
if (listGlyf < activeGlyphs.length && activeGlyphs[listGlyf] == k) {
++listGlyf;
newLocaTable[k] = glyfPtr;
int start = locaTable[k];
int len = locaTable[k + 1] - start;
if (len > 0) {
rf.seek(tableGlyphOffset + start);
rf.readFully(newGlyfTable, glyfPtr, len);
glyfPtr += len;
}
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
protected void flatGlyphs() throws IOException, DocumentException {
int tableLocation[];
tableLocation = tableDirectory.get("glyf");
if (tableLocation == null)
throw new DocumentException(MessageLocalization.getComposedMessage("table.1.does.not.exist.in.2", "glyf", fileName));
Integer glyph0 = Integer.valueOf(0);
if (!glyphsUsed.contains(glyph0)) {
glyphsUsed.add(glyph0);
glyphsInList.add(glyph0);
}
tableGlyphOffset = tableLocation[TABLE_OFFSET];
for (int k = 0; k < glyphsInList.size(); ++k) {
int glyph = glyphsInList.get(k).intValue();
checkGlyphComposite(glyph);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
protected void checkGlyphComposite(int glyph) throws IOException {
int start = locaTable[glyph];
if (start == locaTable[glyph + 1]) // no contour
return;
rf.seek(tableGlyphOffset + start);
int numContours = rf.readShort();
if (numContours >= 0)
return;
rf.skipBytes(8);
for(;;) {
int flags = rf.readUnsignedShort();
Integer cGlyph = Integer.valueOf(rf.readUnsignedShort());
if (!glyphsUsed.contains(cGlyph)) {
glyphsUsed.add(cGlyph);
glyphsInList.add(cGlyph);
}
if ((flags & MORE_COMPONENTS) == 0)
return;
int skip;
if ((flags & ARG_1_AND_2_ARE_WORDS) != 0)
skip = 4;
else
skip = 2;
if ((flags & WE_HAVE_A_SCALE) != 0)
skip += 2;
else if ((flags & WE_HAVE_AN_X_AND_Y_SCALE) != 0)
skip += 4;
if ((flags & WE_HAVE_A_TWO_BY_TWO) != 0)
skip += 8;
rf.skipBytes(skip);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
protected String readStandardString(int length) throws IOException {
byte buf[] = new byte[length];
rf.readFully(buf);
try {
return new String(buf, BaseFont.WINANSI);
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RadioCheckField.java
public PdfAppearance getAppearance(boolean isRadio, boolean on) throws IOException, DocumentException {
if (isRadio && checkType == TYPE_CIRCLE)
return getAppearanceRadioCircle(on);
PdfAppearance app = getBorderAppearance();
if (!on)
return app;
BaseFont ufont = getRealFont();
boolean borderExtra = borderStyle == PdfBorderDictionary.STYLE_BEVELED || borderStyle == PdfBorderDictionary.STYLE_INSET;
float h = box.getHeight() - borderWidth * 2;
float bw2 = borderWidth;
if (borderExtra) {
h -= borderWidth * 2;
bw2 *= 2;
}
float offsetX = (borderExtra ? 2 * borderWidth : borderWidth);
offsetX = Math.max(offsetX, 1);
float offX = Math.min(bw2, offsetX);
float wt = box.getWidth() - 2 * offX;
float ht = box.getHeight() - 2 * offX;
float fsize = fontSize;
if (fsize == 0) {
float bw = ufont.getWidthPoint(text, 1);
if (bw == 0)
fsize = 12;
else
fsize = wt / bw;
float nfsize = h / (ufont.getFontDescriptor(BaseFont.ASCENT, 1));
fsize = Math.min(fsize, nfsize);
}
app.saveState();
app.rectangle(offX, offX, wt, ht);
app.clip();
app.newPath();
if (textColor == null)
app.resetGrayFill();
else
app.setColorFill(textColor);
app.beginText();
app.setFontAndSize(ufont, fsize);
app.setTextMatrix((box.getWidth() - ufont.getWidthPoint(text, fsize)) / 2,
(box.getHeight() - ufont.getAscentPoint(text, fsize)) / 2);
app.showText(text);
app.endText();
app.restoreState();
return app;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RadioCheckField.java
public PdfFormField getRadioField() throws IOException, DocumentException {
return getField(true);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RadioCheckField.java
public PdfFormField getCheckField() throws IOException, DocumentException {
return getField(false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RadioCheckField.java
protected PdfFormField getField(boolean isRadio) throws IOException, DocumentException {
PdfFormField field = null;
if (isRadio)
field = PdfFormField.createEmpty(writer);
else
field = PdfFormField.createCheckBox(writer);
field.setWidget(box, PdfAnnotation.HIGHLIGHT_INVERT);
if (!isRadio) {
field.setFieldName(fieldName);
if ((options & READ_ONLY) != 0)
field.setFieldFlags(PdfFormField.FF_READ_ONLY);
if ((options & REQUIRED) != 0)
field.setFieldFlags(PdfFormField.FF_REQUIRED);
field.setValueAsName(checked ? onValue : "Off");
setCheckType(TYPE_CHECK);
}
if (text != null)
field.setMKNormalCaption(text);
if (rotation != 0)
field.setMKRotation(rotation);
field.setBorderStyle(new PdfBorderDictionary(borderWidth, borderStyle, new PdfDashPattern(3)));
PdfAppearance tpon = getAppearance(isRadio, true);
PdfAppearance tpoff = getAppearance(isRadio, false);
field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, onValue, tpon);
field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", tpoff);
field.setAppearanceState(checked ? onValue : "Off");
PdfAppearance da = (PdfAppearance)tpon.getDuplicate();
da.setFontAndSize(getRealFont(), fontSize);
if (textColor == null)
da.setGrayFill(0);
else
da.setColorFill(textColor);
field.setDefaultAppearanceString(da);
if (borderColor != null)
field.setMKBorderColor(borderColor);
if (backgroundColor != null)
field.setMKBackgroundColor(backgroundColor);
switch (visibility) {
case HIDDEN:
field.setFlags(PdfAnnotation.FLAGS_PRINT | PdfAnnotation.FLAGS_HIDDEN);
break;
case VISIBLE_BUT_DOES_NOT_PRINT:
break;
case HIDDEN_BUT_PRINTABLE:
field.setFlags(PdfAnnotation.FLAGS_PRINT | PdfAnnotation.FLAGS_NOVIEW);
break;
default:
field.setFlags(PdfAnnotation.FLAGS_PRINT);
break;
}
return field;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
private static void loadRegistry() throws IOException {
InputStream is = getResourceStream(RESOURCE_PATH_CMAP + "cjk_registry.properties");
Properties p = new Properties();
p.load(is);
is.close();
for (Object key : p.keySet()) {
String value = p.getProperty((String)key);
String[] sp = value.split(" ");
Set<String> hs = new HashSet<String>();
for (String s : sp) {
if (s.length() > 0)
hs.add(s);
}
registryNames.put((String)key, hs);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
Override
void writeFont(PdfWriter writer, PdfIndirectReference ref, Object params[]) throws DocumentException, IOException {
IntHashtable cjkTag = (IntHashtable)params[0];
PdfIndirectReference ind_font = null;
PdfObject pobj = null;
PdfIndirectObject obj = null;
pobj = getFontDescriptor();
if (pobj != null){
obj = writer.addToBody(pobj);
ind_font = obj.getIndirectReference();
}
pobj = getCIDFont(ind_font, cjkTag);
if (pobj != null){
obj = writer.addToBody(pobj);
ind_font = obj.getIndirectReference();
}
pobj = getFontBaseType(ind_font);
writer.addToBody(pobj, ref);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
private static HashMap<String, Object> readFontProperties(String name) throws IOException {
name += ".properties";
InputStream is = getResourceStream(RESOURCE_PATH_CMAP + name);
Properties p = new Properties();
p.load(is);
is.close();
IntHashtable W = createMetric(p.getProperty("W"));
p.remove("W");
IntHashtable W2 = createMetric(p.getProperty("W2"));
p.remove("W2");
HashMap<String, Object> map = new HashMap<String, Object>();
for (Enumeration<Object> e = p.keys(); e.hasMoreElements();) {
Object obj = e.nextElement();
map.put((String)obj, p.getProperty((String)obj));
}
map.put("W", W);
map.put("W2", W2);
return map;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PushbuttonField.java
private float calculateFontSize(float w, float h) throws IOException, DocumentException {
BaseFont ufont = getRealFont();
float fsize = fontSize;
if (fsize == 0) {
float bw = ufont.getWidthPoint(text, 1);
if (bw == 0)
fsize = 12;
else
fsize = w / bw;
float nfsize = h / (1 - ufont.getFontDescriptor(BaseFont.DESCENT, 1));
fsize = Math.min(fsize, nfsize);
if (fsize < 4)
fsize = 4;
}
return fsize;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PushbuttonField.java
public PdfAppearance getAppearance() throws IOException, DocumentException {
PdfAppearance app = getBorderAppearance();
Rectangle box = new Rectangle(app.getBoundingBox());
if ((text == null || text.length() == 0) && (layout == LAYOUT_LABEL_ONLY || (image == null && template == null && iconReference == null))) {
return app;
}
if (layout == LAYOUT_ICON_ONLY && image == null && template == null && iconReference == null)
return app;
BaseFont ufont = getRealFont();
boolean borderExtra = borderStyle == PdfBorderDictionary.STYLE_BEVELED || borderStyle == PdfBorderDictionary.STYLE_INSET;
float h = box.getHeight() - borderWidth * 2;
float bw2 = borderWidth;
if (borderExtra) {
h -= borderWidth * 2;
bw2 *= 2;
}
float offsetX = (borderExtra ? 2 * borderWidth : borderWidth);
offsetX = Math.max(offsetX, 1);
float offX = Math.min(bw2, offsetX);
tp = null;
float textX = Float.NaN;
float textY = 0;
float fsize = fontSize;
float wt = box.getWidth() - 2 * offX - 2;
float ht = box.getHeight() - 2 * offX;
float adj = (iconFitToBounds ? 0 : offX + 1);
int nlayout = layout;
if (image == null && template == null && iconReference == null)
nlayout = LAYOUT_LABEL_ONLY;
Rectangle iconBox = null;
while (true) {
switch (nlayout) {
case LAYOUT_LABEL_ONLY:
case LAYOUT_LABEL_OVER_ICON:
if (text != null && text.length() > 0 && wt > 0 && ht > 0) {
fsize = calculateFontSize(wt, ht);
textX = (box.getWidth() - ufont.getWidthPoint(text, fsize)) / 2;
textY = (box.getHeight() - ufont.getFontDescriptor(BaseFont.ASCENT, fsize)) / 2;
}
case LAYOUT_ICON_ONLY:
if (nlayout == LAYOUT_LABEL_OVER_ICON || nlayout == LAYOUT_ICON_ONLY)
iconBox = new Rectangle(box.getLeft() + adj, box.getBottom() + adj, box.getRight() - adj, box.getTop() - adj);
break;
case LAYOUT_ICON_TOP_LABEL_BOTTOM:
if (text == null || text.length() == 0 || wt <= 0 || ht <= 0) {
nlayout = LAYOUT_ICON_ONLY;
continue;
}
float nht = box.getHeight() * 0.35f - offX;
if (nht > 0)
fsize = calculateFontSize(wt, nht);
else
fsize = 4;
textX = (box.getWidth() - ufont.getWidthPoint(text, fsize)) / 2;
textY = offX - ufont.getFontDescriptor(BaseFont.DESCENT, fsize);
iconBox = new Rectangle(box.getLeft() + adj, textY + fsize, box.getRight() - adj, box.getTop() - adj);
break;
case LAYOUT_LABEL_TOP_ICON_BOTTOM:
if (text == null || text.length() == 0 || wt <= 0 || ht <= 0) {
nlayout = LAYOUT_ICON_ONLY;
continue;
}
nht = box.getHeight() * 0.35f - offX;
if (nht > 0)
fsize = calculateFontSize(wt, nht);
else
fsize = 4;
textX = (box.getWidth() - ufont.getWidthPoint(text, fsize)) / 2;
textY = box.getHeight() - offX - fsize;
if (textY < offX)
textY = offX;
iconBox = new Rectangle(box.getLeft() + adj, box.getBottom() + adj, box.getRight() - adj, textY + ufont.getFontDescriptor(BaseFont.DESCENT, fsize));
break;
case LAYOUT_LABEL_LEFT_ICON_RIGHT:
if (text == null || text.length() == 0 || wt <= 0 || ht <= 0) {
nlayout = LAYOUT_ICON_ONLY;
continue;
}
float nw = box.getWidth() * 0.35f - offX;
if (nw > 0)
fsize = calculateFontSize(wt, nw);
else
fsize = 4;
if (ufont.getWidthPoint(text, fsize) >= wt) {
nlayout = LAYOUT_LABEL_ONLY;
fsize = fontSize;
continue;
}
textX = offX + 1;
textY = (box.getHeight() - ufont.getFontDescriptor(BaseFont.ASCENT, fsize)) / 2;
iconBox = new Rectangle(textX + ufont.getWidthPoint(text, fsize), box.getBottom() + adj, box.getRight() - adj, box.getTop() - adj);
break;
case LAYOUT_ICON_LEFT_LABEL_RIGHT:
if (text == null || text.length() == 0 || wt <= 0 || ht <= 0) {
nlayout = LAYOUT_ICON_ONLY;
continue;
}
nw = box.getWidth() * 0.35f - offX;
if (nw > 0)
fsize = calculateFontSize(wt, nw);
else
fsize = 4;
if (ufont.getWidthPoint(text, fsize) >= wt) {
nlayout = LAYOUT_LABEL_ONLY;
fsize = fontSize;
continue;
}
textX = box.getWidth() - ufont.getWidthPoint(text, fsize) - offX - 1;
textY = (box.getHeight() - ufont.getFontDescriptor(BaseFont.ASCENT, fsize)) / 2;
iconBox = new Rectangle(box.getLeft() + adj, box.getBottom() + adj, textX - 1, box.getTop() - adj);
break;
}
break;
}
if (textY < box.getBottom() + offX)
textY = box.getBottom() + offX;
if (iconBox != null && (iconBox.getWidth() <= 0 || iconBox.getHeight() <= 0))
iconBox = null;
boolean haveIcon = false;
float boundingBoxWidth = 0;
float boundingBoxHeight = 0;
PdfArray matrix = null;
if (iconBox != null) {
if (image != null) {
tp = new PdfTemplate(writer);
tp.setBoundingBox(new Rectangle(image));
writer.addDirectTemplateSimple(tp, PdfName.FRM);
tp.addImage(image, image.getWidth(), 0, 0, image.getHeight(), 0, 0);
haveIcon = true;
boundingBoxWidth = tp.getBoundingBox().getWidth();
boundingBoxHeight = tp.getBoundingBox().getHeight();
}
else if (template != null) {
tp = new PdfTemplate(writer);
tp.setBoundingBox(new Rectangle(template.getWidth(), template.getHeight()));
writer.addDirectTemplateSimple(tp, PdfName.FRM);
tp.addTemplate(template, template.getBoundingBox().getLeft(), template.getBoundingBox().getBottom());
haveIcon = true;
boundingBoxWidth = tp.getBoundingBox().getWidth();
boundingBoxHeight = tp.getBoundingBox().getHeight();
}
else if (iconReference != null) {
PdfDictionary dic = (PdfDictionary)PdfReader.getPdfObject(iconReference);
if (dic != null) {
Rectangle r2 = PdfReader.getNormalizedRectangle(dic.getAsArray(PdfName.BBOX));
matrix = dic.getAsArray(PdfName.MATRIX);
haveIcon = true;
boundingBoxWidth = r2.getWidth();
boundingBoxHeight = r2.getHeight();
}
}
}
if (haveIcon) {
float icx = iconBox.getWidth() / boundingBoxWidth;
float icy = iconBox.getHeight() / boundingBoxHeight;
if (proportionalIcon) {
switch (scaleIcon) {
case SCALE_ICON_IS_TOO_BIG:
icx = Math.min(icx, icy);
icx = Math.min(icx, 1);
break;
case SCALE_ICON_IS_TOO_SMALL:
icx = Math.min(icx, icy);
icx = Math.max(icx, 1);
break;
case SCALE_ICON_NEVER:
icx = 1;
break;
default:
icx = Math.min(icx, icy);
break;
}
icy = icx;
}
else {
switch (scaleIcon) {
case SCALE_ICON_IS_TOO_BIG:
icx = Math.min(icx, 1);
icy = Math.min(icy, 1);
break;
case SCALE_ICON_IS_TOO_SMALL:
icx = Math.max(icx, 1);
icy = Math.max(icy, 1);
break;
case SCALE_ICON_NEVER:
icx = icy = 1;
break;
default:
break;
}
}
float xpos = iconBox.getLeft() + (iconBox.getWidth() - (boundingBoxWidth * icx)) * iconHorizontalAdjustment;
float ypos = iconBox.getBottom() + (iconBox.getHeight() - (boundingBoxHeight * icy)) * iconVerticalAdjustment;
app.saveState();
app.rectangle(iconBox.getLeft(), iconBox.getBottom(), iconBox.getWidth(), iconBox.getHeight());
app.clip();
app.newPath();
if (tp != null)
app.addTemplate(tp, icx, 0, 0, icy, xpos, ypos);
else {
float cox = 0;
float coy = 0;
if (matrix != null && matrix.size() == 6) {
PdfNumber nm = matrix.getAsNumber(4);
if (nm != null)
cox = nm.floatValue();
nm = matrix.getAsNumber(5);
if (nm != null)
coy = nm.floatValue();
}
app.addTemplateReference(iconReference, PdfName.FRM, icx, 0, 0, icy, xpos - cox * icx, ypos - coy * icy);
}
app.restoreState();
}
if (!Float.isNaN(textX)) {
app.saveState();
app.rectangle(offX, offX, box.getWidth() - 2 * offX, box.getHeight() - 2 * offX);
app.clip();
app.newPath();
if (textColor == null)
app.resetGrayFill();
else
app.setColorFill(textColor);
app.beginText();
app.setFontAndSize(ufont, fsize);
app.setTextMatrix(textX, textY);
app.showText(text);
app.endText();
app.restoreState();
}
return app;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PushbuttonField.java
public PdfFormField getField() throws IOException, DocumentException {
PdfFormField field = PdfFormField.createPushButton(writer);
field.setWidget(box, PdfAnnotation.HIGHLIGHT_INVERT);
if (fieldName != null) {
field.setFieldName(fieldName);
if ((options & READ_ONLY) != 0)
field.setFieldFlags(PdfFormField.FF_READ_ONLY);
if ((options & REQUIRED) != 0)
field.setFieldFlags(PdfFormField.FF_REQUIRED);
}
if (text != null)
field.setMKNormalCaption(text);
if (rotation != 0)
field.setMKRotation(rotation);
field.setBorderStyle(new PdfBorderDictionary(borderWidth, borderStyle, new PdfDashPattern(3)));
PdfAppearance tpa = getAppearance();
field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, tpa);
PdfAppearance da = (PdfAppearance)tpa.getDuplicate();
da.setFontAndSize(getRealFont(), fontSize);
if (textColor == null)
da.setGrayFill(0);
else
da.setColorFill(textColor);
field.setDefaultAppearanceString(da);
if (borderColor != null)
field.setMKBorderColor(borderColor);
if (backgroundColor != null)
field.setMKBackgroundColor(backgroundColor);
switch (visibility) {
case HIDDEN:
field.setFlags(PdfAnnotation.FLAGS_PRINT | PdfAnnotation.FLAGS_HIDDEN);
break;
case VISIBLE_BUT_DOES_NOT_PRINT:
break;
case HIDDEN_BUT_PRINTABLE:
field.setFlags(PdfAnnotation.FLAGS_PRINT | PdfAnnotation.FLAGS_NOVIEW);
break;
default:
field.setFlags(PdfAnnotation.FLAGS_PRINT);
break;
}
if (tp != null)
field.setMKNormalIcon(tp);
field.setMKTextPosition(layout - 1);
PdfName scale = PdfName.A;
if (scaleIcon == SCALE_ICON_IS_TOO_BIG)
scale = PdfName.B;
else if (scaleIcon == SCALE_ICON_IS_TOO_SMALL)
scale = PdfName.S;
else if (scaleIcon == SCALE_ICON_NEVER)
scale = PdfName.N;
field.setMKIconFit(scale, proportionalIcon ? PdfName.P : PdfName.A, iconHorizontalAdjustment,
iconVerticalAdjustment, iconFitToBounds);
return field;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
static void transferBytes(InputStream in, OutputStream out, int len) throws IOException {
byte buffer[] = new byte[TRANSFERSIZE];
if (len < 0)
len = 0x7fff0000;
int size;
while (len != 0) {
size = in.read(buffer, 0, Math.min(len, TRANSFERSIZE));
if (size < 0)
return;
out.write(buffer, 0, size);
len -= size;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfShading.java
public void addToBody() throws IOException {
if (bBox != null)
shading.put(PdfName.BBOX, new PdfArray(bBox));
if (antiAlias)
shading.put(PdfName.ANTIALIAS, PdfBoolean.PDFTRUE);
writer.addToBody(shading, getShadingReference());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ByteBuffer.java
public void writeTo(OutputStream out) throws IOException {
out.write(buf, 0, count);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ByteBuffer.java
public void write(int b) throws IOException {
append((byte)b);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void close() throws DocumentException, IOException {
if (stamper.closed)
return;
if (!hasSignature) {
mergeVerification();
stamper.close(moreInfo);
}
else {
throw new DocumentException("Signature defined. Must be closed in PdfSignatureAppearance.");
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void addComments(final FdfReader fdf) throws IOException {
stamper.addComments(fdf);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void addFileAttachment(final String description, final byte fileStore[], final String file, final String fileDisplay) throws IOException {
addFileAttachment(description, PdfFileSpecification.fileEmbedded(stamper, file, fileDisplay, fileStore));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void addFileAttachment(final String description, final PdfFileSpecification fs) throws IOException {
stamper.addFileAttachment(description, fs);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public static PdfStamper createSignature(final PdfReader reader, final OutputStream os, final char pdfVersion, File tempFile, final boolean append) throws DocumentException, IOException {
PdfStamper stp;
if (tempFile == null) {
ByteBuffer bout = new ByteBuffer();
stp = new PdfStamper(reader, bout, pdfVersion, append);
stp.sigApp = new PdfSignatureAppearance(stp.stamper);
stp.sigApp.setSigout(bout);
}
else {
if (tempFile.isDirectory())
tempFile = File.createTempFile("pdf", null, tempFile);
FileOutputStream fout = new FileOutputStream(tempFile);
stp = new PdfStamper(reader, fout, pdfVersion, append);
stp.sigApp = new PdfSignatureAppearance(stp.stamper);
stp.sigApp.setTempFile(tempFile);
}
stp.sigApp.setOriginalout(os);
stp.sigApp.setStamper(stp);
stp.hasSignature = true;
PdfDictionary catalog = reader.getCatalog();
PdfDictionary acroForm = (PdfDictionary)PdfReader.getPdfObject(catalog.get(PdfName.ACROFORM), catalog);
if (acroForm != null) {
acroForm.remove(PdfName.NEEDAPPEARANCES);
stp.stamper.markUsed(acroForm);
}
return stp;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public static PdfStamper createSignature(final PdfReader reader, final OutputStream os, final char pdfVersion) throws DocumentException, IOException {
return createSignature(reader, os, pdfVersion, null, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public static PdfStamper createSignature(final PdfReader reader, final OutputStream os, final char pdfVersion, final File tempFile) throws DocumentException, IOException
{
return createSignature(reader, os, pdfVersion, tempFile, false);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
void mergeVerification() throws IOException {
if (verification == null)
return;
verification.merge();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
Deprecated
public RandomAccessFileOrArray(String filename) throws IOException {
this(new RandomAccessSourceFactory()
.setForceRead(false)
.setUsePlainRandomAccess(Document.plainRandomAccess)
.createBestSource(filename));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
Deprecated
public RandomAccessFileOrArray(String filename, boolean forceRead, boolean plainRandomAccess) throws IOException {
this(new RandomAccessSourceFactory()
.setForceRead(forceRead)
.setUsePlainRandomAccess(plainRandomAccess)
.createBestSource(filename));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
Deprecated
public RandomAccessFileOrArray(URL url) throws IOException {
this (new RandomAccessSourceFactory().createSource(url));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
Deprecated
public RandomAccessFileOrArray(InputStream is) throws IOException {
this (new RandomAccessSourceFactory().createSource(is));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public int read() throws IOException {
if(isBack) {
isBack = false;
return back & 0xff;
}
return byteSource.get(byteSourcePosition++);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public int read(byte[] b, int off, int len) throws IOException {
if (len == 0)
return 0;
int count = 0;
if (isBack && len > 0) {
isBack = false;
b[off++] = back;
--len;
count++;
}
if (len > 0){
int byteSourceCount = byteSource.get(byteSourcePosition, b, off, len);
if (byteSourceCount > 0) {
count += byteSourceCount;
byteSourcePosition += byteSourceCount;
}
}
if (count == 0)
return -1;
return count;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public void readFully(byte b[]) throws IOException {
readFully(b, 0, b.length);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public void readFully(byte b[], int off, int len) throws IOException {
int n = 0;
do {
int count = read(b, off + n, len - n);
if (count < 0)
throw new EOFException();
n += count;
} while (n < len);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public long skip(long n) throws IOException {
if (n <= 0) {
return 0;
}
int adj = 0;
if (isBack) {
isBack = false;
if (n == 1) {
return 1;
}
else {
--n;
adj = 1;
}
}
long pos;
long len;
long newpos;
pos = getFilePointer();
len = length();
newpos = pos + n;
if (newpos > len) {
newpos = len;
}
seek(newpos);
/* return the actual number of bytes skipped */
return newpos - pos + adj;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public int skipBytes(int n) throws IOException {
return (int)skip(n);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
Deprecated
//TODO: remove all references to this call, then remove this method
public void reOpen() throws IOException {
seek(0);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
Deprecated
//TODO: remove all references to this call, then remove this method
protected void insureOpen() throws IOException {
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public void close() throws IOException {
isBack = false;
byteSource.close();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public long length() throws IOException {
return byteSource.length();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public void seek(long pos) throws IOException {
byteSourcePosition = pos;
isBack = false;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public long getFilePointer() throws IOException {
return byteSourcePosition - (isBack ? 1 : 0);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public boolean readBoolean() throws IOException {
int ch = this.read();
if (ch < 0)
throw new EOFException();
return (ch != 0);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public byte readByte() throws IOException {
int ch = this.read();
if (ch < 0)
throw new EOFException();
return (byte)(ch);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public int readUnsignedByte() throws IOException {
int ch = this.read();
if (ch < 0)
throw new EOFException();
return ch;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public short readShort() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (short)((ch1 << 8) + ch2);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public final short readShortLE() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (short)((ch2 << 8) + (ch1 << 0));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public int readUnsignedShort() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (ch1 << 8) + ch2;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public final int readUnsignedShortLE() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (ch2 << 8) + (ch1 << 0);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public char readChar() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (char)((ch1 << 8) + ch2);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public final char readCharLE() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
if ((ch1 | ch2) < 0)
throw new EOFException();
return (char)((ch2 << 8) + (ch1 << 0));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public int readInt() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
int ch3 = this.read();
int ch4 = this.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public final int readIntLE() throws IOException {
int ch1 = this.read();
int ch2 = this.read();
int ch3 = this.read();
int ch4 = this.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public final long readUnsignedInt() throws IOException {
long ch1 = this.read();
long ch2 = this.read();
long ch3 = this.read();
long ch4 = this.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public final long readUnsignedIntLE() throws IOException {
long ch1 = this.read();
long ch2 = this.read();
long ch3 = this.read();
long ch4 = this.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public long readLong() throws IOException {
return ((long)(readInt()) << 32) + (readInt() & 0xFFFFFFFFL);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public final long readLongLE() throws IOException {
int i1 = readIntLE();
int i2 = readIntLE();
return ((long)i2 << 32) + (i1 & 0xFFFFFFFFL);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public final float readFloatLE() throws IOException {
return Float.intBitsToFloat(readIntLE());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public final double readDoubleLE() throws IOException {
return Double.longBitsToDouble(readLongLE());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public String readLine() throws IOException {
StringBuilder input = new StringBuilder();
int c = -1;
boolean eol = false;
while (!eol) {
switch (c = read()) {
case -1:
case '\n':
eol = true;
break;
case '\r':
eol = true;
long cur = getFilePointer();
if ((read()) != '\n') {
seek(cur);
}
break;
default:
input.append((char)c);
break;
}
}
if ((c == -1) && (input.length() == 0)) {
return null;
}
return input.toString();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public String readUTF() throws IOException {
return DataInputStream.readUTF(this);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
public String readString(int length, String encoding) throws IOException {
byte buf[] = new byte[length];
readFully(buf);
try {
return new String(buf, encoding);
}
catch (Exception e) {
throw new ExceptionConverter(e);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
private void processUni2Byte() throws IOException{
//IntHashtable uni2byte = getUni2Byte();
//int e[] = uni2byte.toOrderedKeys();
//if (e.length == 0)
// return;
IntHashtable byte2uni = getByte2Uni();
int e[] = byte2uni.toOrderedKeys();
if (e.length == 0)
return;
cidbyte2uni = new char[256];
for (int k = 0; k < e.length; ++k) {
int key = e[k];
cidbyte2uni[key] = (char)byte2uni.get(key);
}
if (toUnicodeCmap != null) {
/*
for (int k = 0; k < e.length; ++k) {
// Kevin Day:
// this is messy, messy - an encoding can have multiple unicode values mapping to the same cid - we are going to arbitrarily choose the first one
// what we really need to do is to parse the encoding, and handle the differences info ourselves. This is a huge duplication of code of what is already
// being done in DocumentFont, so I really hate to go down that path without seriously thinking about a change in the organization of the Font class hierarchy
// Bruno Lowagie:
// I wish I could fix this in a better way, for instance by creating a uni2byte intHashtable in DocumentFont.
// However, I chose a quick & dirty solution, allowing intHashtable to store an array of int values.
ArrayList<Integer> nList = uni2byte.getValues(e[k]);
for (int n : nList) {
if (n < 256 && cidbyte2uni[n] == 0)
cidbyte2uni[n] = (char)e[k];
}
}
*/
Map<Integer, Integer> dm = toUnicodeCmap.createDirectMapping();
for (Map.Entry<Integer, Integer> kv : dm.entrySet()) {
if (kv.getKey() < 256) {
cidbyte2uni[kv.getKey().intValue()] = (char)kv.getValue().intValue();
}
}
}
IntHashtable diffmap = getDiffmap();
if (diffmap != null) {
// the difference array overrides the existing encoding
e = diffmap.toOrderedKeys();
for (int k = 0; k < e.length; ++k) {
int n = diffmap.get(e[k]);
if (n < 256)
cidbyte2uni[n] = (char)e[k];
}
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerifier.java
public List<VerificationOK> verify(X509Certificate signCert, X509Certificate issuerCert, Date signDate)
throws GeneralSecurityException, IOException {
// Check if the certificate is valid on the signDate
if (signDate != null)
signCert.checkValidity(signDate);
// Check if the signature is valid
if (issuerCert != null) {
signCert.verify(issuerCert.getPublicKey());
}
// Also in case, the certificate is self-signed
else {
signCert.verify(signCert.getPublicKey());
}
List<VerificationOK> result = new ArrayList<VerificationOK>();
if (verifier != null)
result.addAll(verifier.verify(signCert, issuerCert, signDate));
return result;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/RootStoreVerifier.java
public List<VerificationOK> verify(X509Certificate signCert, X509Certificate issuerCert,
Date signDate) throws GeneralSecurityException, IOException {
LOGGER.info("Root store verification: " + signCert.getSubjectDN().getName());
// verify using the CertificateVerifier if root store is missing
if (rootStore == null)
return super.verify(signCert, issuerCert, signDate);
try {
List<VerificationOK> result = new ArrayList<VerificationOK>();
// loop over the trusted anchors in the root store
for (Enumeration<String> aliases = rootStore.aliases(); aliases.hasMoreElements();) {
String alias = aliases.nextElement();
try {
if (!rootStore.isCertificateEntry(alias))
continue;
X509Certificate anchor = (X509Certificate) rootStore
.getCertificate(alias);
signCert.verify(anchor.getPublicKey());
LOGGER.info("Certificate verified against root store");
result.add(new VerificationOK(signCert, this.getClass(), "Certificate verified against root store."));
result.addAll(super.verify(signCert, issuerCert, signDate));
return result;
} catch (GeneralSecurityException e) {
continue;
}
}
result.addAll(super.verify(signCert, issuerCert, signDate));
return result;
} catch (GeneralSecurityException e) {
return super.verify(signCert, issuerCert, signDate);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateUtil.java
public static CRL getCRL(X509Certificate certificate) throws CertificateException, CRLException, IOException {
return CertificateUtil.getCRL(CertificateUtil.getCRLURL(certificate));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateUtil.java
public static CRL getCRL(String url) throws IOException, CertificateException, CRLException {
if (url == null)
return null;
InputStream is = new URL(url).openStream();
CertificateFactory cf = CertificateFactory.getInstance("X.509");
return (CRL)cf.generateCRL(is);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateUtil.java
private static ASN1Primitive getExtensionValue(X509Certificate certificate, String oid) throws IOException {
byte[] bytes = certificate.getExtensionValue(oid);
if (bytes == null) {
return null;
}
ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
return aIn.readObject();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateUtil.java
private static String getStringFromGeneralName(ASN1Primitive names) throws IOException {
ASN1TaggedObject taggedObject = (ASN1TaggedObject) names ;
return new String(ASN1OctetString.getInstance(taggedObject, false).getOctets(), "ISO-8859-1");
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvTimestamp.java
public static void timestamp(PdfSignatureAppearance sap, TSAClient tsa, String signatureName) throws IOException, DocumentException, GeneralSecurityException {
int contentEstimated = tsa.getTokenSizeEstimate();
sap.setVisibleSignature(new Rectangle(0,0,0,0), 1, signatureName);
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ETSI_RFC3161);
dic.put(PdfName.TYPE, PdfName.DOCTIMESTAMP);
sap.setCryptoDictionary(dic);
HashMap<PdfName,Integer> exc = new HashMap<PdfName,Integer>();
exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
sap.preClose(exc);
InputStream data = sap.getRangeStream();
MessageDigest messageDigest = tsa.getMessageDigest();
byte[] buf = new byte[4096];
int n;
while ((n = data.read(buf)) > 0) {
messageDigest.update(buf, 0, n);
}
byte[] tsImprint = messageDigest.digest();
byte[] tsToken;
try {
tsToken = tsa.getTimeStampToken(tsImprint);
}
catch(Exception e) {
throw new GeneralSecurityException(e);
}
if (contentEstimated + 2 < tsToken.length)
throw new IOException("Not enough space");
byte[] paddedSig = new byte[contentEstimated];
System.arraycopy(tsToken, 0, paddedSig, 0, tsToken.length);
PdfDictionary dic2 = new PdfDictionary();
dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
sap.close(dic2);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/TSAClientBouncyCastle.java
public byte[] getTimeStampToken(byte[] imprint) throws IOException, TSPException {
byte[] respBytes = null;
// Setup the time stamp request
TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
tsqGenerator.setCertReq(true);
// tsqGenerator.setReqPolicy("1.3.6.1.4.1.601.10.3.1");
BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
TimeStampRequest request = tsqGenerator.generate(new ASN1ObjectIdentifier(DigestAlgorithms.getAllowedDigests(digestAlgorithm)), imprint, nonce);
byte[] requestBytes = request.getEncoded();
// Call the communications layer
respBytes = getTSAResponse(requestBytes);
// Handle the TSA response
TimeStampResponse response = new TimeStampResponse(respBytes);
// validate communication level attributes (RFC 3161 PKIStatus)
response.validate(request);
PKIFailureInfo failure = response.getFailInfo();
int value = (failure == null) ? 0 : failure.intValue();
if (value != 0) {
// @todo: Translate value of 15 error codes defined by PKIFailureInfo to string
throw new IOException(MessageLocalization.getComposedMessage("invalid.tsa.1.response.code.2", tsaURL, String.valueOf(value)));
}
// @todo: validate the time stap certificate chain (if we want
// assure we do not sign using an invalid timestamp).
// extract just the time stamp token (removes communication status info)
TimeStampToken tsToken = response.getTimeStampToken();
if (tsToken == null) {
throw new IOException(MessageLocalization.getComposedMessage("tsa.1.failed.to.return.time.stamp.token.2", tsaURL, response.getStatusString()));
}
TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo(); // to view details
byte[] encoded = tsToken.getEncoded();
LOGGER.info("Timestamp generated: " + tsTokenInfo.getGenTime());
if (tsaInfo != null) {
tsaInfo.inspectTimeStampTokenInfo(tsTokenInfo);
}
// Update our token size estimate for the next call (padded to be safe)
this.tokenSizeEstimate = encoded.length + 32;
return encoded;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/TSAClientBouncyCastle.java
protected byte[] getTSAResponse(byte[] requestBytes) throws IOException {
// Setup the TSA connection
URL url = new URL(tsaURL);
URLConnection tsaConnection;
try {
tsaConnection = (URLConnection) url.openConnection();
}
catch (IOException ioe) {
throw new IOException(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL));
}
tsaConnection.setDoInput(true);
tsaConnection.setDoOutput(true);
tsaConnection.setUseCaches(false);
tsaConnection.setRequestProperty("Content-Type", "application/timestamp-query");
//tsaConnection.setRequestProperty("Content-Transfer-Encoding", "base64");
tsaConnection.setRequestProperty("Content-Transfer-Encoding", "binary");
if ((tsaUsername != null) && !tsaUsername.equals("") ) {
String userPassword = tsaUsername + ":" + tsaPassword;
tsaConnection.setRequestProperty("Authorization", "Basic " +
Base64.encodeBytes(userPassword.getBytes()));
}
OutputStream out = tsaConnection.getOutputStream();
out.write(requestBytes);
out.close();
// Get TSA response as a byte array
InputStream inp = tsaConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = inp.read(buffer, 0, buffer.length)) >= 0) {
baos.write(buffer, 0, bytesRead);
}
byte[] respBytes = baos.toByteArray();
String encoding = tsaConnection.getContentEncoding();
if (encoding != null && encoding.equalsIgnoreCase("base64")) {
respBytes = Base64.decode(new String(respBytes));
}
return respBytes;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
public List<VerificationOK> verify(List<VerificationOK> result) throws IOException, GeneralSecurityException {
if (result == null)
result = new ArrayList<VerificationOK>();
while (pkcs7 != null) {
result.addAll(verifySignature());
}
return result;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
public List<VerificationOK> verifySignature() throws GeneralSecurityException, IOException {
LOGGER.info("Verifying signature.");
List<VerificationOK> result = new ArrayList<VerificationOK>();
// Get the certificate chain
Certificate[] chain = pkcs7.getSignCertificateChain();
verifyChain(chain);
// how many certificates in the chain do we need to check?
int total = 1;
if (CertificateOption.WHOLE_CHAIN.equals(option)) {
total = chain.length;
}
// loop over the certificates
X509Certificate signCert;
X509Certificate issuerCert;
for (int i = 0; i < total; ) {
// the certificate to check
signCert = (X509Certificate) chain[i++];
// its issuer
issuerCert = null;
if (i < chain.length)
issuerCert = (X509Certificate) chain[i];
// now lets verify the certificate
LOGGER.info(signCert.getSubjectDN().getName());
List<VerificationOK> list = verify(signCert, issuerCert, signDate);
if (list.size() == 0) {
try {
signCert.verify(signCert.getPublicKey());
if (latestRevision && chain.length > 1) {
list.add(new VerificationOK(signCert, this.getClass(), "Root certificate in final revision"));
}
if (list.size() == 0 && verifyRootCertificate) {
throw new GeneralSecurityException();
}
else if (chain.length > 1)
list.add(new VerificationOK(signCert, this.getClass(), "Root certificate passed without checking"));
}
catch(GeneralSecurityException e) {
throw new VerificationException(signCert, "Couldn't verify with CRL or OCSP or trusted anchor");
}
}
result.addAll(list);
}
// go to the previous revision
switchToPreviousRevision();
return result;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
public List<VerificationOK> verify(X509Certificate signCert, X509Certificate issuerCert, Date signDate) throws GeneralSecurityException, IOException {
// we'll verify agains the rootstore (if present)
RootStoreVerifier rootStoreVerifier = new RootStoreVerifier(verifier);
rootStoreVerifier.setRootStore(rootStore);
// We'll verify against a list of CRLs
CRLVerifier crlVerifier = new CRLVerifier(rootStoreVerifier, getCRLsFromDSS());
crlVerifier.setRootStore(rootStore);
crlVerifier.setOnlineCheckingAllowed(latestRevision || onlineCheckingAllowed);
// We'll verify against a list of OCSPs
OCSPVerifier ocspVerifier = new OCSPVerifier(crlVerifier, getOCSPResponsesFromDSS());
ocspVerifier.setRootStore(rootStore);
ocspVerifier.setOnlineCheckingAllowed(latestRevision || onlineCheckingAllowed);
// We verify the chain
return ocspVerifier.verify(signCert, issuerCert, signDate);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
public void switchToPreviousRevision() throws IOException, GeneralSecurityException {
LOGGER.info("Switching to previous revision.");
latestRevision = false;
dss = reader.getCatalog().getAsDict(PdfName.DSS);
Calendar cal = pkcs7.getTimeStampDate();
if (cal == null)
cal = pkcs7.getSignDate();
// TODO: get date from signature
signDate = cal.getTime();
List<String> names = fields.getSignatureNames();
if (names.size() > 1) {
signatureName = names.get(names.size() - 2);
reader = new PdfReader(fields.extractRevision(signatureName));
this.fields = reader.getAcroFields();
names = fields.getSignatureNames();
signatureName = names.get(names.size() - 1);
pkcs7 = coversWholeDocument();
LOGGER.info(String.format("Checking %ssignature %s", pkcs7.isTsp() ? "document-level timestamp " : "", signatureName));
}
else {
LOGGER.info("No signatures in revision");
pkcs7 = null;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
public List<X509CRL> getCRLsFromDSS() throws GeneralSecurityException, IOException {
List<X509CRL> crls = new ArrayList<X509CRL>();
if (dss == null)
return crls;
PdfArray crlarray = dss.getAsArray(PdfName.CRLS);
if (crlarray == null)
return crls;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
for (int i = 0; i < crlarray.size(); i++) {
PRStream stream = (PRStream) crlarray.getAsStream(i);
X509CRL crl = (X509CRL)cf.generateCRL(new ByteArrayInputStream(PdfReader.getStreamBytes(stream)));
crls.add(crl);
}
return crls;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
public List<BasicOCSPResp> getOCSPResponsesFromDSS() throws IOException, GeneralSecurityException {
List<BasicOCSPResp> ocsps = new ArrayList<BasicOCSPResp>();
if (dss == null)
return ocsps;
PdfArray ocsparray = dss.getAsArray(PdfName.OCSPS);
if (ocsparray == null)
return ocsps;
for (int i = 0; i < ocsparray.size(); i++) {
PRStream stream = (PRStream) ocsparray.getAsStream(i);
OCSPResp ocspResponse = new OCSPResp(PdfReader.getStreamBytes(stream));
if (ocspResponse.getStatus() == 0)
try {
ocsps.add((BasicOCSPResp) ocspResponse.getResponseObject());
} catch (OCSPException e) {
throw new GeneralSecurityException(e);
}
}
return ocsps;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
public List<VerificationOK> verify(X509Certificate signCert, X509Certificate issuerCert, Date signDate)
throws GeneralSecurityException, IOException {
List<VerificationOK> result = new ArrayList<VerificationOK>();
int validCrlsFound = 0;
// first check the list of CRLs that is provided
if (crls != null) {
for (X509CRL crl : crls) {
if (verify(crl, signCert, issuerCert, signDate))
validCrlsFound++;
}
}
// then check online if allowed
boolean online = false;
if (onlineCheckingAllowed && validCrlsFound == 0) {
if (verify(getCRL(signCert, issuerCert), signCert, issuerCert, signDate)) {
validCrlsFound++;
online = true;
}
}
// show how many valid CRLs were found
LOGGER.info("Valid CRLs found: " + validCrlsFound);
if (validCrlsFound > 0) {
result.add(new VerificationOK(signCert, this.getClass(), "Valid CRLs found: " + validCrlsFound + (online ? " (online)" : "")));
}
if (verifier != null)
result.addAll(verifier.verify(signCert, issuerCert, signDate));
// verify using the previous verifier in the chain (if any)
return result;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
private ASN1EncodableVector buildUnauthenticatedAttributes(byte[] timeStampToken) throws IOException {
if (timeStampToken == null)
return null;
// @todo: move this together with the rest of the defintions
String ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; // RFC 3161 id-aa-timeStampToken
ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(timeStampToken));
ASN1EncodableVector unauthAttributes = new ASN1EncodableVector();
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1ObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken
ASN1Sequence seq = (ASN1Sequence) tempstream.readObject();
v.add(new DERSet(seq));
unauthAttributes.add(new DERSequence(v));
return unauthAttributes;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
private void findOcsp(ASN1Sequence seq) throws IOException {
basicResp = null;
boolean ret = false;
while (true) {
if (seq.getObjectAt(0) instanceof ASN1ObjectIdentifier
&& ((ASN1ObjectIdentifier)seq.getObjectAt(0)).getId().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic.getId())) {
break;
}
ret = true;
for (int k = 0; k < seq.size(); ++k) {
if (seq.getObjectAt(k) instanceof ASN1Sequence) {
seq = (ASN1Sequence)seq.getObjectAt(0);
ret = false;
break;
}
if (seq.getObjectAt(k) instanceof ASN1TaggedObject) {
ASN1TaggedObject tag = (ASN1TaggedObject)seq.getObjectAt(k);
if (tag.getObject() instanceof ASN1Sequence) {
seq = (ASN1Sequence)tag.getObject();
ret = false;
break;
}
else
return;
}
}
if (ret)
return;
}
ASN1OctetString os = (ASN1OctetString)seq.getObjectAt(1);
ASN1InputStream inp = new ASN1InputStream(os.getOctets());
BasicOCSPResponse resp = BasicOCSPResponse.getInstance(inp.readObject());
basicResp = new BasicOCSPResp(resp);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerification.java
public boolean addVerification(String signatureName, OcspClient ocsp, CrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude) throws IOException, GeneralSecurityException {
if (used)
throw new IllegalStateException(MessageLocalization.getComposedMessage("verification.already.output"));
PdfPKCS7 pk = acroFields.verifySignature(signatureName);
LOGGER.info("Adding verification for " + signatureName);
Certificate[] xc = pk.getCertificates();
X509Certificate cert;
X509Certificate signingCert = pk.getSigningCertificate();
ValidationData vd = new ValidationData();
for (int k = 0; k < xc.length; ++k) {
cert = (X509Certificate)xc[k];
LOGGER.info("Certificate: " + cert.getSubjectDN());
if (certOption == CertificateOption.SIGNING_CERTIFICATE
&& !cert.equals(signingCert)) {
continue;
}
byte[] ocspEnc = null;
if (ocsp != null && level != Level.CRL) {
ocspEnc = ocsp.getEncoded(cert, getParent(cert, xc), null);
if (ocspEnc != null) {
vd.ocsps.add(buildOCSPResponse(ocspEnc));
LOGGER.info("OCSP added");
}
}
if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null))) {
Collection<byte[]> cims = crl.getEncoded(cert, null);
if (cims != null) {
for (byte[] cim : cims) {
boolean dup = false;
for (byte[] b : vd.crls) {
if (Arrays.equals(b, cim)) {
dup = true;
break;
}
}
if (!dup) {
vd.crls.add(cim);
LOGGER.info("CRL added");
}
}
}
}
if (certInclude == CertificateInclusion.YES) {
vd.certs.add(cert.getEncoded());
}
}
if (vd.crls.isEmpty() && vd.ocsps.isEmpty())
return false;
validated.put(getSignatureHashKey(signatureName), vd);
return true;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerification.java
public boolean addVerification(String signatureName, Collection<byte[]> ocsps, Collection<byte[]> crls, Collection<byte[]> certs) throws IOException, GeneralSecurityException {
if (used)
throw new IllegalStateException(MessageLocalization.getComposedMessage("verification.already.output"));
ValidationData vd = new ValidationData();
if (ocsps != null) {
for (byte[] ocsp : ocsps) {
vd.ocsps.add(buildOCSPResponse(ocsp));
}
}
if (crls != null) {
for (byte[] crl : crls) {
vd.crls.add(crl);
}
}
if (certs != null) {
for (byte[] cert : certs) {
vd.certs.add(cert);
}
}
validated.put(getSignatureHashKey(signatureName), vd);
return true;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerification.java
private static byte[] buildOCSPResponse(byte[] BasicOCSPResponse) throws IOException {
DEROctetString doctet = new DEROctetString(BasicOCSPResponse);
ASN1EncodableVector v2 = new ASN1EncodableVector();
v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
v2.add(doctet);
ASN1Enumerated den = new ASN1Enumerated(0);
ASN1EncodableVector v3 = new ASN1EncodableVector();
v3.add(den);
v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
DERSequence seq = new DERSequence(v3);
return seq.getEncoded();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerification.java
private PdfName getSignatureHashKey(String signatureName) throws NoSuchAlgorithmException, IOException {
PdfDictionary dic = acroFields.getSignatureDictionary(signatureName);
PdfString contents = dic.getAsString(PdfName.CONTENTS);
byte[] bc = contents.getOriginalBytes();
byte[] bt = null;
if (PdfName.ETSI_RFC3161.equals(PdfReader.getPdfObject(dic.get(PdfName.SUBFILTER)))) {
ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(bc));
ASN1Primitive pkcs = din.readObject();
bc = pkcs.getEncoded();
}
bt = hashBytesSha1(bc);
return new PdfName(Utilities.convertToHex(bt));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerification.java
public void merge() throws IOException {
if (used || validated.isEmpty())
return;
used = true;
PdfDictionary catalog = reader.getCatalog();
PdfObject dss = catalog.get(PdfName.DSS);
if (dss == null)
createDss();
else
updateDss();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerification.java
private void updateDss() throws IOException {
PdfDictionary catalog = reader.getCatalog();
stp.markUsed(catalog);
PdfDictionary dss = catalog.getAsDict(PdfName.DSS);
PdfArray ocsps = dss.getAsArray(PdfName.OCSPS);
PdfArray crls = dss.getAsArray(PdfName.CRLS);
PdfArray certs = dss.getAsArray(PdfName.CERTS);
dss.remove(PdfName.OCSPS);
dss.remove(PdfName.CRLS);
dss.remove(PdfName.CERTS);
PdfDictionary vrim = dss.getAsDict(PdfName.VRI);
//delete old validations
if (vrim != null) {
for (PdfName n : vrim.getKeys()) {
if (validated.containsKey(n)) {
PdfDictionary vri = vrim.getAsDict(n);
if (vri != null) {
deleteOldReferences(ocsps, vri.getAsArray(PdfName.OCSP));
deleteOldReferences(crls, vri.getAsArray(PdfName.CRL));
deleteOldReferences(certs, vri.getAsArray(PdfName.CERT));
}
}
}
}
if (ocsps == null)
ocsps = new PdfArray();
if (crls == null)
crls = new PdfArray();
if (certs == null)
certs = new PdfArray();
outputDss(dss, vrim, ocsps, crls, certs);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerification.java
private void createDss() throws IOException {
outputDss(new PdfDictionary(), new PdfDictionary(), new PdfArray(), new PdfArray(), new PdfArray());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerification.java
private void outputDss(PdfDictionary dss, PdfDictionary vrim, PdfArray ocsps, PdfArray crls, PdfArray certs) throws IOException {
PdfDictionary catalog = reader.getCatalog();
stp.markUsed(catalog);
for (PdfName vkey : validated.keySet()) {
PdfArray ocsp = new PdfArray();
PdfArray crl = new PdfArray();
PdfArray cert = new PdfArray();
PdfDictionary vri = new PdfDictionary();
for (byte[] b : validated.get(vkey).crls) {
PdfStream ps = new PdfStream(b);
ps.flateCompress();
PdfIndirectReference iref = writer.addToBody(ps, false).getIndirectReference();
crl.add(iref);
crls.add(iref);
}
for (byte[] b : validated.get(vkey).ocsps) {
PdfStream ps = new PdfStream(b);
ps.flateCompress();
PdfIndirectReference iref = writer.addToBody(ps, false).getIndirectReference();
ocsp.add(iref);
ocsps.add(iref);
}
for (byte[] b : validated.get(vkey).certs) {
PdfStream ps = new PdfStream(b);
ps.flateCompress();
PdfIndirectReference iref = writer.addToBody(ps, false).getIndirectReference();
cert.add(iref);
certs.add(iref);
}
if (ocsp.size() > 0)
vri.put(PdfName.OCSP, writer.addToBody(ocsp, false).getIndirectReference());
if (crl.size() > 0)
vri.put(PdfName.CRL, writer.addToBody(crl, false).getIndirectReference());
if (cert.size() > 0)
vri.put(PdfName.CERT, writer.addToBody(cert, false).getIndirectReference());
vrim.put(vkey, writer.addToBody(vri, false).getIndirectReference());
}
dss.put(PdfName.VRI, writer.addToBody(vrim, false).getIndirectReference());
if (ocsps.size() > 0)
dss.put(PdfName.OCSPS, writer.addToBody(ocsps, false).getIndirectReference());
if (crls.size() > 0)
dss.put(PdfName.CRLS, writer.addToBody(crls, false).getIndirectReference());
if (certs.size() > 0)
dss.put(PdfName.CERTS, writer.addToBody(certs, false).getIndirectReference());
catalog.put(PdfName.DSS, writer.addToBody(dss, false).getIndirectReference());
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws OCSPException, IOException,
OperatorException, CertificateEncodingException {
//Add provider BC
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// Generate the id for the certificate we are looking for
CertificateID id = new CertificateID(
new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1),
new JcaX509CertificateHolder(issuerCert), serialNumber);
// basic request generation with nonce
OCSPReqBuilder gen = new OCSPReqBuilder();
gen.addRequest(id);
Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded()));
gen.setRequestExtensions(new Extensions(new Extension[]{ext}));
return gen.build();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
private OCSPResp getOcspResponse(X509Certificate checkCert, X509Certificate rootCert, String url) throws GeneralSecurityException, OCSPException, IOException, OperatorException {
if (checkCert == null || rootCert == null)
return null;
if (url == null) {
url = CertificateUtil.getOCSPURL(checkCert);
}
if (url == null)
return null;
LOGGER.info("Getting OCSP from " + url);
OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber());
byte[] array = request.getEncoded();
URL urlt = new URL(url);
HttpURLConnection con = (HttpURLConnection)urlt.openConnection();
con.setRequestProperty("Content-Type", "application/ocsp-request");
con.setRequestProperty("Accept", "application/ocsp-response");
con.setDoOutput(true);
OutputStream out = con.getOutputStream();
DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out));
dataOut.write(array);
dataOut.flush();
dataOut.close();
if (con.getResponseCode() / 100 != 2) {
throw new IOException(MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode()));
}
//Get Response
InputStream in = (InputStream) con.getContent();
return new OCSPResp(StreamUtil.inputStreamToArray(in));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
public List<VerificationOK> verify(X509Certificate signCert,
X509Certificate issuerCert, Date signDate)
throws GeneralSecurityException, IOException {
List<VerificationOK> result = new ArrayList<VerificationOK>();
int validOCSPsFound = 0;
// first check in the list of OCSP responses that was provided
if (ocsps != null) {
for (BasicOCSPResp ocspResp : ocsps) {
if (verify(ocspResp, signCert, issuerCert, signDate))
validOCSPsFound++;
}
}
// then check online if allowed
boolean online = false;
if (onlineCheckingAllowed && validOCSPsFound == 0) {
if (verify(getOcspResponse(signCert, issuerCert), signCert, issuerCert, signDate)) {
validOCSPsFound++;
online = true;
}
}
// show how many valid OCSP responses were found
LOGGER.info("Valid OCSPs found: " + validOCSPsFound);
if (validOCSPsFound > 0)
result.add(new VerificationOK(signCert, this.getClass(), "Valid OCSPs Found: " + validOCSPsFound + (online ? " (online)" : "")));
if (verifier != null)
result.addAll(verifier.verify(signCert, issuerCert, signDate));
// verify using the previous verifier in the chain (if any)
return result;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
public boolean verify(BasicOCSPResp ocspResp, X509Certificate signCert, X509Certificate issuerCert, Date signDate) throws GeneralSecurityException, IOException {
if (ocspResp == null)
return false;
// Getting the responses
SingleResp[] resp = ocspResp.getResponses();
for (int i = 0; i < resp.length; i++) {
// check if the serial number corresponds
if (!signCert.getSerialNumber().equals(resp[i].getCertID().getSerialNumber())) {
continue;
}
// check if the issuer matches
try {
if (issuerCert == null) issuerCert = signCert;
if (!resp[i].getCertID().matchesIssuer(new X509CertificateHolder(issuerCert.getEncoded()), new BcDigestCalculatorProvider())) {
LOGGER.info("OCSP: Issuers doesn't match.");
continue;
}
} catch (OCSPException e) {
continue;
}
// check if the OCSP response was valid at the time of signing
Date nextUpdate = resp[i].getNextUpdate();
if (nextUpdate == null) {
nextUpdate = new Date(resp[i].getThisUpdate().getTime() + 180000l);
LOGGER.info(String.format("No 'next update' for OCSP Response; assuming %s", nextUpdate));
}
if (signDate.after(nextUpdate)) {
LOGGER.info(String.format("OCSP no longer valid: %s after %s", signDate, nextUpdate));
continue;
}
// check the status of the certificate
Object status = resp[i].getCertStatus();
if (status == CertificateStatus.GOOD) {
// check if the OCSP response was genuine
isValidResponse(ocspResp, issuerCert);
return true;
}
}
return false;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
public void isValidResponse(BasicOCSPResp ocspResp, X509Certificate issuerCert) throws GeneralSecurityException, IOException {
// by default the OCSP responder certificate is the issuer certificate
X509Certificate responderCert = issuerCert;
// check if there's a responder certificate
X509CertificateHolder[] certHolders = ocspResp.getCerts();
if (certHolders.length > 0) {
responderCert = new JcaX509CertificateConverter().setProvider( "BC" ).getCertificate(certHolders[0]);
try {
responderCert.verify(issuerCert.getPublicKey());
}
catch(GeneralSecurityException e) {
if (super.verify(responderCert, issuerCert, null).size() == 0)
throw new VerificationException(responderCert, "Responder certificate couldn't be verified");
}
}
// verify if the signature of the response is valid
if (!verifyResponse(ocspResp, responderCert))
throw new VerificationException(responderCert, "OCSP response could not be verified");
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/MakeSignature.java
public static void signExternalContainer(PdfSignatureAppearance sap, ExternalSignatureContainer externalSignatureContainer, int estimatedSize) throws GeneralSecurityException, IOException, DocumentException {
PdfSignature dic = new PdfSignature(null, null);
dic.setReason(sap.getReason());
dic.setLocation(sap.getLocation());
dic.setContact(sap.getContact());
dic.setDate(new PdfDate(sap.getSignDate())); // time-stamp will over-rule this
externalSignatureContainer.modifySigningDictionary(dic);
sap.setCryptoDictionary(dic);
HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));
sap.preClose(exc);
InputStream data = sap.getRangeStream();
byte[] encodedSig = externalSignatureContainer.sign(data);
if (estimatedSize < encodedSig.length)
throw new IOException("Not enough space");
byte[] paddedSig = new byte[estimatedSize];
System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
PdfDictionary dic2 = new PdfDictionary();
dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
sap.close(dic2);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/MakeSignature.java
public static void signDeferred(PdfReader reader, String fieldName, OutputStream outs, ExternalSignatureContainer externalSignatureContainer) throws DocumentException, IOException, GeneralSecurityException {
AcroFields af = reader.getAcroFields();
PdfDictionary v = af.getSignatureDictionary(fieldName);
if (v == null)
throw new DocumentException("No field");
if (!af.signatureCoversWholeDocument(fieldName))
throw new DocumentException("Not the last signature");
PdfArray b = v.getAsArray(PdfName.BYTERANGE);
long[] gaps = b.asLongArray();
if (b.size() != 4 || gaps[0] != 0)
throw new DocumentException("Single exclusion space supported");
RandomAccessSource readerSource = reader.getSafeFile().createSourceView();
InputStream rg = new RASInputStream(new RandomAccessSourceFactory().createRanged(readerSource, gaps));
byte[] signedContent = externalSignatureContainer.sign(rg);
int spaceAvailable = (int)(gaps[2] - gaps[1]) - 2;
if ((spaceAvailable & 1) != 0)
throw new DocumentException("Gap is not a multiple of 2");
spaceAvailable /= 2;
if (spaceAvailable < signedContent.length)
throw new DocumentException("Not enough space");
StreamUtil.CopyBytes(readerSource, 0, gaps[1] + 1, outs);
ByteBuffer bb = new ByteBuffer(spaceAvailable * 2);
for (byte bi : signedContent) {
bb.appendHex(bi);
}
int remain = (spaceAvailable - signedContent.length) * 2;
for (int k = 0; k < remain; ++k) {
bb.append((byte)48);
}
bb.writeTo(outs);
StreamUtil.CopyBytes(readerSource, gaps[2] - 1, gaps[3] + 1, outs);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/DigestAlgorithms.java
public static byte[] digest(InputStream data, String hashAlgorithm, String provider)
throws GeneralSecurityException, IOException {
MessageDigest messageDigest = getMessageDigest(hashAlgorithm, provider);
return digest(data, messageDigest);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/DigestAlgorithms.java
public static byte[] digest(InputStream data, MessageDigest messageDigest)
throws GeneralSecurityException, IOException {
byte buf[] = new byte[8192];
int n;
while ((n = data.read(buf)) > 0) {
messageDigest.update(buf, 0, n);
}
return messageDigest.digest();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
private void init(FileChannel channel, FileChannel.MapMode mapMode)
throws IOException {
this.channel = channel;
size = channel.size();
pos = 0;
int requiredBuffers = (int)(size/BUFSIZE) + (size % BUFSIZE == 0 ? 0 : 1);
//System.out.println("This will require " + requiredBuffers + " buffers");
mappedBuffers = new MappedByteBuffer[requiredBuffers];
try{
int index = 0;
for(long offset = 0; offset < size; offset += BUFSIZE){
long size2 = Math.min(size - offset, BUFSIZE);
mappedBuffers[index] = channel.map(mapMode, offset, size2);
mappedBuffers[index].load();
index++;
}
if (index != requiredBuffers){
throw new Error("Should never happen - " + index + " != " + requiredBuffers);
}
} catch (IOException e){
close();
throw e;
} catch (RuntimeException e){
close();
throw e;
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
public void close() throws IOException {
for(int i = 0; i < mappedBuffers.length; i++){
if (mappedBuffers[i] != null){
clean(mappedBuffers[i]);
mappedBuffers[i] = null;
}
}
if (channel != null)
channel.close();
channel = null;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfLiteral.java
public void toPdf(PdfWriter writer, java.io.OutputStream os) throws java.io.IOException {
if (os instanceof OutputStreamCounter)
position = ((OutputStreamCounter)os).getCounter();
super.toPdf(writer, os);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void startElement(HTMLWorker worker, String tag, Map<String, String> attrs) throws DocumentException, IOException {
worker.updateChain(tag, attrs);
worker.processImage(worker.createImage(attrs), attrs);
worker.updateChain(tag);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
public Image createImage(
String src,
final Map<String, String> attrs,
final ChainedProperties chain,
final DocListener document,
final ImageProvider img_provider,
final HashMap<String, Image> img_store,
final String img_baseurl) throws DocumentException, IOException {
Image img = null;
// getting the image using an image provider
if (img_provider != null)
img = img_provider.getImage(src, attrs, chain, document);
// getting the image from an image store
if (img == null && img_store != null) {
Image tim = img_store.get(src);
if (tim != null)
img = Image.getInstance(tim);
}
if (img != null)
return img;
// introducing a base url
// relative src references only
if (!src.startsWith("http") && img_baseurl != null) {
src = img_baseurl + src;
}
else if (img == null && !src.startsWith("http")) {
String path = chain.getProperty(HtmlTags.IMAGEPATH);
if (path == null)
path = "";
src = new File(path, src).getPath();
}
img = Image.getInstance(src);
if (img == null)
return null;
float actualFontSize = HtmlUtilities.parseLength(
chain.getProperty(HtmlTags.SIZE),
HtmlUtilities.DEFAULT_FONT_SIZE);
if (actualFontSize <= 0f)
actualFontSize = HtmlUtilities.DEFAULT_FONT_SIZE;
String width = attrs.get(HtmlTags.WIDTH);
float widthInPoints = HtmlUtilities.parseLength(width, actualFontSize);
String height = attrs.get(HtmlTags.HEIGHT);
float heightInPoints = HtmlUtilities.parseLength(height, actualFontSize);
if (widthInPoints > 0 && heightInPoints > 0) {
img.scaleAbsolute(widthInPoints, heightInPoints);
} else if (widthInPoints > 0) {
heightInPoints = img.getHeight() * widthInPoints
/ img.getWidth();
img.scaleAbsolute(widthInPoints, heightInPoints);
} else if (heightInPoints > 0) {
widthInPoints = img.getWidth() * heightInPoints
/ img.getHeight();
img.scaleAbsolute(widthInPoints, heightInPoints);
}
String before = chain.getProperty(HtmlTags.BEFORE);
if (before != null)
img.setSpacingBefore(Float.parseFloat(before));
String after = chain.getProperty(HtmlTags.AFTER);
if (after != null)
img.setSpacingAfter(Float.parseFloat(after));
img.setWidthPercentage(0);
return img;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void parse(final Reader reader) throws IOException {
LOGGER.info("Please note, there is a more extended version of the HTMLWorker available in the iText XMLWorker");
SimpleXMLParser.parse(this, null, reader, true);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public Image createImage(final Map<String, String> attrs) throws DocumentException, IOException {
String src = attrs.get(HtmlTags.SRC);
if (src == null)
return null;
Image img = factory.createImage(
src, attrs, chain, document,
(ImageProvider)providers.get(IMG_PROVIDER),
(ImageStore)providers.get(IMG_STORE),
(String)providers.get(IMG_BASEURL));
return img;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public static List<Element> parseToList(final Reader reader, final StyleSheet style)
throws IOException {
return parseToList(reader, style, null);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public static List<Element> parseToList(final Reader reader, final StyleSheet style,
final HashMap<String, Object> providers) throws IOException {
return parseToList(reader, style, null, providers);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public static List<Element> parseToList(final Reader reader, final StyleSheet style,
final Map<String, HTMLTagProcessor> tags, final HashMap<String, Object> providers) throws IOException {
HTMLWorker worker = new HTMLWorker(null, tags, style);
worker.document = worker;
worker.setProviders(providers);
worker.objectList = new ArrayList<Element>();
worker.parse(reader);
return worker.objectList;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Jpeg2000.java
private int cio_read(int n) throws IOException {
int v = 0;
for (int i = n - 1; i >= 0; i--) {
v += inp.read() << (i << 3);
}
return v;
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Jpeg2000.java
public void jp2_read_boxhdr() throws IOException {
boxLength = cio_read(4);
boxType = cio_read(4);
if (boxLength == 1) {
if (cio_read(4) != 0) {
throw new IOException(MessageLocalization.getComposedMessage("cannot.handle.box.sizes.higher.than.2.32"));
}
boxLength = cio_read(4);
if (boxLength == 0)
throw new IOException(MessageLocalization.getComposedMessage("unsupported.box.size.eq.eq.0"));
}
else if (boxLength == 0) {
throw new IOException(MessageLocalization.getComposedMessage("unsupported.box.size.eq.eq.0"));
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Jpeg2000.java
private void processParameters() throws IOException {
type = JPEG2000;
originalType = ORIGINAL_JPEG2000;
inp = null;
try {
if (rawData == null){
inp = url.openStream();
}
else{
inp = new java.io.ByteArrayInputStream(rawData);
}
boxLength = cio_read(4);
if (boxLength == 0x0000000c) {
boxType = cio_read(4);
if (JP2_JP != boxType) {
throw new IOException(MessageLocalization.getComposedMessage("expected.jp.marker"));
}
if (0x0d0a870a != cio_read(4)) {
throw new IOException(MessageLocalization.getComposedMessage("error.with.jp.marker"));
}
jp2_read_boxhdr();
if (JP2_FTYP != boxType) {
throw new IOException(MessageLocalization.getComposedMessage("expected.ftyp.marker"));
}
Utilities.skip(inp, boxLength - 8);
jp2_read_boxhdr();
do {
if (JP2_JP2H != boxType) {
if (boxType == JP2_JP2C) {
throw new IOException(MessageLocalization.getComposedMessage("expected.jp2h.marker"));
}
Utilities.skip(inp, boxLength - 8);
jp2_read_boxhdr();
}
} while(JP2_JP2H != boxType);
jp2_read_boxhdr();
if (JP2_IHDR != boxType) {
throw new IOException(MessageLocalization.getComposedMessage("expected.ihdr.marker"));
}
scaledHeight = cio_read(4);
setTop(scaledHeight);
scaledWidth = cio_read(4);
setRight(scaledWidth);
bpc = -1;
}
else if (boxLength == 0xff4fff51) {
Utilities.skip(inp, 4);
int x1 = cio_read(4);
int y1 = cio_read(4);
int x0 = cio_read(4);
int y0 = cio_read(4);
Utilities.skip(inp, 16);
colorspace = cio_read(2);
bpc = 8;
scaledHeight = y1 - y0;
setTop(scaledHeight);
scaledWidth = x1 - x0;
setRight(scaledWidth);
}
else {
throw new IOException(MessageLocalization.getComposedMessage("not.a.valid.jpeg2000.file"));
}
}
finally {
if (inp != null) {
try{inp.close();}catch(Exception e){}
inp = null;
}
}
plainWidth = getWidth();
plainHeight = getHeight();
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
protected void write(String string) throws IOException {
os.write(getISOBytes(string));
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
protected void addTabs(int indent) throws IOException {
os.write(NEWLINE);
for (int i = 0; i < indent; i++) {
os.write(TAB);
}
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
protected void write(String key, String value)
throws IOException {
os.write(SPACE);
write(key);
os.write(EQUALS);
os.write(QUOTE);
write(value);
os.write(QUOTE);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
protected void writeStart(String tag)
throws IOException {
os.write(LT);
write(tag);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
protected void writeEnd(String tag)
throws IOException {
os.write(LT);
os.write(FORWARD);
write(tag);
os.write(GT);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
protected void writeEnd()
throws IOException {
os.write(SPACE);
os.write(FORWARD);
os.write(GT);
}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
protected boolean writeMarkupAttributes(Properties markup)
throws IOException {
if (markup == null) return false;
Iterator<Object> attributeIterator = markup.keySet().iterator();
String name;
while (attributeIterator.hasNext()) {
name = String.valueOf(attributeIterator.next());
write(name, markup.getProperty(name));
}
markup.clear();
return true;
}