Exception Fact Sheet for "itext"

The goal of an Exception Fact Sheet is to reveal the design of exception handling in an application.

--Maxence, Martin

For feedback, please contact Martin

Table of contents

Basic Statistics

Number of Classes 692
Number of Domain Exception Types (Thrown or Caught) 19
Number of Domain Checked Exception Types 13
Number of Domain Runtime Exception Types 5
Number of Domain Unknown Exception Types 1
nTh = Number of Throw 881
nTh = Number of Throw in Catch 216
Number of Catch-Rethrow (may not be correct) 9
nC = Number of Catch 459
nCTh = Number of Catch with Throw 215
Number of Empty Catch (really Empty) 75
Number of Empty Catch (with comments) 43
Number of Empty Catch 118
nM = Number of Methods 6964
nbFunctionWithCatch = Number of Methods with Catch 352 / 6964
nbFunctionWithThrow = Number of Methods with Throw 609 / 6964
nbFunctionWithThrowS = Number of Methods with ThrowS 947 / 6964
nbFunctionTransmitting = Number of Methods with "Throws" but NO catch, NO throw (only transmitting) 696 / 6964
P1 = nCTh / nC 46.8% (0.468)
P2 = nMC / nM 5.1% (0.051)
P3 = nbFunctionWithThrow / nbFunction 8.7% (0.087)
P4 = nbFunctionTransmitting / nbFunction 10% (0.1)
P5 = nbThrowInCatch / nbThrow 24.5% (0.245)
R2 = nCatch / nThrow 0.521
A1 = Number of Caught Exception Types From External Libraries 28
A2 = Number of Reused Exception Types From External Libraries (thrown from application code) 20

W1 is a rough estimation of the richness of the exception model. It does not take into account the inheritance relationships between domain exceptions.

Proportion P1 measures the overall exception flow. According to our experience, it varies from 5% to 70%. Early-catch design generally yields a low P1, libraries that must warn clients about errors (e.g. databases) generally have a high P1.

Proportion P2 measures the dispersion of catch blocks in the application. According to our experience, it varies from 2% to 15%. A small P2 indicates a rather centralized management of errors.

R1 shows how many exceptions types from libraries (incl. JDK) are thrown from application code. For instance, IllegalArgumentException comes from the JDK but is used in many applications.

A1 measures the awareness of the application to library exceptions. A high value of A1 means either that the application is polluted with checked exceptions or that it is able to apply specific recovery depending on the library exception.

Exception Hierachy

Exception Map

Each exception that is used at least once in the project is a dot. A orange dot represents a domain exception that is defined in the application. A blue dot exception is defined in the JDK or in a library. The x-axis represents the number of times an exception is caught, the y-axis the number of times an exception is thrown.

Exceptions With State

State means fields. Number of exceptions with state: 2
ExceptionConverter
              package com.itextpdf.text;public class ExceptionConverter extends RuntimeException {
    private static final long serialVersionUID = 8657630363395849399L;
	/** we keep a handle to the wrapped exception */
    private Exception ex;
    /** prefix for the exception */
    private String prefix;

    /**
     * Construct a RuntimeException based on another Exception
     * @param ex the exception that has to be turned into a RuntimeException
     */
    public ExceptionConverter(Exception ex) {
        super(ex);
        this.ex = ex;
        prefix = (ex instanceof RuntimeException) ? "" : "ExceptionConverter: ";
    }

    /**
     * Convert an Exception into an unchecked exception. Return the exception if it is
     * already an unchecked exception or return an ExceptionConverter wrapper otherwise
     *
     * @param ex the exception to convert
     * @return an unchecked exception 
     * @since 2.1.6
     */
    public static final RuntimeException convertException(Exception ex) {
        if (ex instanceof RuntimeException) {
            return (RuntimeException) ex;
        }
        return new ExceptionConverter(ex);
    }

    /**
     * and allow the user of ExceptionConverter to get a handle to it. 
     * @return the original exception
     */
    public Exception getException() {
        return ex;
    }

    /**
     * We print the message of the checked exception 
     * @return message of the original exception
     */
    public String getMessage() {
        return ex.getMessage();
    }

    /**
     * and make sure we also produce a localized version
     * @return localized version of the message
     */
    public String getLocalizedMessage() {
        return ex.getLocalizedMessage();
    }

    /**
     * The toString() is changed to be prefixed with ExceptionConverter 
     * @return String version of the exception
     */
    public String toString() {
        return prefix + ex;
    }

    /** we have to override this as well */
    public void printStackTrace() {
        printStackTrace(System.err);
    }

    /**
     * here we prefix, with s.print(), not s.println(), the stack
     * trace with "ExceptionConverter:" 
     * @param s
     */
    public void printStackTrace(java.io.PrintStream s) {
        synchronized (s) {
            s.print(prefix);
            ex.printStackTrace(s);
        }
    }

    /**
     * Again, we prefix the stack trace with "ExceptionConverter:" 
     * @param s
     */
    public void printStackTrace(java.io.PrintWriter s) {
        synchronized (s) {
            s.print(prefix);
            ex.printStackTrace(s);
        }
    }

    /**
     * requests to fill in the stack trace we will have to ignore.
     * We can't throw an exception here, because this method
     * is called by the constructor of Throwable 
     * @return a Throwable
     */
    public Throwable fillInStackTrace() {
        return this;
    }
}
            
InvalidPdfException
              package com.itextpdf.text.exceptions;public class InvalidPdfException extends IOException {

	/** a serial version UID */
	private static final long serialVersionUID = -2319614911517026938L;
	private final Throwable cause;

	/**
	 * Creates an instance with a message and no cause
	 * @param	message	the reason why the document isn't a PDF document according to iText.
	 */
	public InvalidPdfException(String message) {
		this(message, null);
	}	
	
	/**
	 * Creates an exception with a message and a cause
	 * @param message	the reason why the document isn't a PDF document according to iText. 
	 * @param cause the cause of the exception, if any
	 */
	public InvalidPdfException(String message, Throwable cause){
		super(message);
		this.cause = cause;
	}
	
	/**
	 * This method is included (instead of using super(message, cause) in the constructors) to support backwards compatabilty with
	 * JDK 1.5, which did not have cause constructors for Throwable
	 * @return the cause of this exception
	 */
	public Throwable getCause() {
		return cause;
	}
}
            

Thrown Exceptions Summary

A (Domain) exception is defined in the application. A (Lib) exception is defined in the JDK or in a library. An exception can be thrown, thrown from within a catch, or declared in the signature of a method (usually for checked exceptions). Hovering over a number triggers showing code snippets from the application code.

Type Exception Thrown Thrown
from Catch
Declared
- Unknown 18
              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Invalid compression specified in BMP file.");

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Not implemented yet.");

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Not implemented yet.");

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                RuntimeException("BMP version 5 not implemented yet.");

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Invalid compression specified for BMP file.");

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Invalid compression specified for BMP file.");

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Invalid compression specified for BMP file.");

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Invalid compression specified for BMP file.");

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
throw e;

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
throw e;

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
throw e;

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
throw e;

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
throw e;

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Version.java
throw iae;

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
throw ExceptionConverter.convertException(e);

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
throw ex;

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
throw e;

              
//in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
throw e;

            
- -
- Builder 9
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Invalid compression specified in BMP file.");

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Not implemented yet.");

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Not implemented yet.");

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                RuntimeException("BMP version 5 not implemented yet.");

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Invalid compression specified for BMP file.");

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Invalid compression specified for BMP file.");

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Invalid compression specified for BMP file.");

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
throw new
                        RuntimeException("Invalid compression specified for BMP file.");

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
throw ExceptionConverter.convertException(e);

            
- -
- Variable 9
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
throw e;

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
throw e;

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
throw e;

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
throw e;

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
throw e;

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Version.java
throw iae;

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
throw ex;

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
throw e;

              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
throw e;

            
- -
(Lib) IllegalArgumentException 168
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/misc/RenderingHints.java
public Object put(Object key, Object value) { if (!((Key)key).isCompatibleValue(value)) { throw new IllegalArgumentException(); } return map.put(key, value); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
public void setWindingRule(int rule) { if (rule != WIND_EVEN_ODD && rule != WIND_NON_ZERO) { // awt.209=Invalid winding rule value throw new java.lang.IllegalArgumentException(Messages.getString("awt.209")); //$NON-NLS-1$ } this.rule = rule; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
private boolean drawImage(Image img, Image mask, AffineTransform xform, Color bgColor, ImageObserver obs) { if (xform==null) xform = new AffineTransform(); else xform = new AffineTransform(xform); xform.translate(0, img.getHeight(obs)); xform.scale(img.getWidth(obs), img.getHeight(obs)); AffineTransform inverse = this.normalizeMatrix(); AffineTransform flipper = AffineTransform.getScaleInstance(1,-1); inverse.concatenate(xform); inverse.concatenate(flipper); double[] mx = new double[6]; inverse.getMatrix(mx); if (currentFillGState != 255) { PdfGState gs = fillGState[255]; if (gs == null) { gs = new PdfGState(); gs.setFillOpacity(1); fillGState[255] = gs; } cb.setGState(gs); } try { com.itextpdf.text.Image image = null; if(!convertImagesToJPEG){ image = com.itextpdf.text.Image.getInstance(img, bgColor); } else{ BufferedImage scaled = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g3 = scaled.createGraphics(); g3.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null); g3.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault()); iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwparam.setCompressionQuality(jpegQuality);//Set here your compression rate ImageWriter iw = ImageIO.getImageWritersByFormatName("jpg").next(); ImageOutputStream ios = ImageIO.createImageOutputStream(baos); iw.setOutput(ios); iw.write(null, new IIOImage(scaled, null, null), iwparam); iw.dispose(); ios.close(); scaled.flush(); scaled = null; image = com.itextpdf.text.Image.getInstance(baos.toByteArray()); } if (mask!=null) { com.itextpdf.text.Image msk = com.itextpdf.text.Image.getInstance(mask, null, true); msk.makeMask(); msk.setInverted(true); image.setImageMask(msk); } cb.addImage(image, (float)mx[0], (float)mx[1], (float)mx[2], (float)mx[3], (float)mx[4], (float)mx[5]); Object url = getRenderingHint(HyperLinkKey.KEY_INSTANCE); if (url != null && !url.equals(HyperLinkKey.VALUE_HYPERLINKKEY_OFF)) { PdfAction action = new PdfAction(url.toString()); cb.setAction(action, (float)mx[4], (float)mx[5], (float)(mx[0]+mx[4]), (float)(mx[3]+mx[5])); } } catch (Exception ex) { throw new IllegalArgumentException(ex); } if (currentFillGState >= 0 && currentFillGState != 255) { PdfGState gs = fillGState[currentFillGState]; cb.setGState(gs); } return true; }
// 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/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/pdf/codec/JBIG2Image.java
public static Image getJbig2Image(RandomAccessFileOrArray ra, int page) { if (page < 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.page.number.must.be.gt.eq.1")); try { JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.read(); JBIG2SegmentReader.JBIG2Page p = sr.getPage(page); Image img = new ImgJBIG2(p.pageBitmapWidth, p.pageBitmapHeight, p.getData(true), sr.getGlobal(true)); return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// 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
public static Image getTiffImage(RandomAccessFileOrArray s, int page, boolean direct) { if (page < 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.page.number.must.be.gt.eq.1")); try { TIFFDirectory dir = new TIFFDirectory(s, page - 1); if (dir.isTagPresent(TIFFConstants.TIFFTAG_TILEWIDTH)) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("tiles.are.not.supported")); int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: case TIFFConstants.COMPRESSION_CCITTFAX3: case TIFFConstants.COMPRESSION_CCITTFAX4: break; default: return getTiffImageColor(dir, s); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } Image img = null; long tiffT4Options = 0; long tiffT6Options = 0; int fillOrder = 1; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; float XYRatio = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); if (resolutionUnit == TIFFConstants.RESUNIT_NONE) { if (dpiY != 0) XYRatio = (float)dpiX / (float)dpiY; dpiX = 0; dpiY = 0; } int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int params = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_PHOTOMETRIC)) { long photo = dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); if (photo == TIFFConstants.PHOTOMETRIC_MINISBLACK) params |= Image.CCITT_BLACKIS1; } int imagecomp = 0; switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: imagecomp = Image.CCITTG3_1D; params |= Image.CCITT_ENCODEDBYTEALIGN | Image.CCITT_ENDOFBLOCK; break; case TIFFConstants.COMPRESSION_CCITTFAX3: imagecomp = Image.CCITTG3_1D; params |= Image.CCITT_ENDOFLINE | Image.CCITT_ENDOFBLOCK; TIFFField t4OptionsField = dir.getField(TIFFConstants.TIFFTAG_GROUP3OPTIONS); if (t4OptionsField != null) { tiffT4Options = t4OptionsField.getAsLong(0); if ((tiffT4Options & TIFFConstants.GROUP3OPT_2DENCODING) != 0) imagecomp = Image.CCITTG3_2D; if ((tiffT4Options & TIFFConstants.GROUP3OPT_FILLBITS) != 0) params |= Image.CCITT_ENCODEDBYTEALIGN; } break; case TIFFConstants.COMPRESSION_CCITTFAX4: imagecomp = Image.CCITTG4; TIFFField t6OptionsField = dir.getField(TIFFConstants.TIFFTAG_GROUP4OPTIONS); if (t6OptionsField != null) tiffT6Options = t6OptionsField.getAsLong(0); break; } if (direct && rowsStrip == h) { //single strip, direct byte im[] = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(im); img = Image.getInstance(w, h, false, imagecomp, params, im); img.setInverted(true); } else { int rowsLeft = h; CCITTG4Encoder g4 = new CCITTG4Encoder(w); for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); TIFFFaxDecoder decoder = new TIFFFaxDecoder(fillOrder, w, height); byte outBuf[] = new byte[(w + 7) / 8 * height]; switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: decoder.decode1D(outBuf, im, 0, height); g4.fax4Encode(outBuf,height); break; case TIFFConstants.COMPRESSION_CCITTFAX3: try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e) { // let's flip the fill bits and try again... tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS; try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e2) { throw e; } } g4.fax4Encode(outBuf, height); break; case TIFFConstants.COMPRESSION_CCITTFAX4: decoder.decodeT6(outBuf, im, 0, height, tiffT6Options); g4.fax4Encode(outBuf, height); break; } rowsLeft -= rowsStrip; } byte g4pic[] = g4.close(); img = Image.getInstance(w, h, false, Image.CCITTG4, params & Image.CCITT_BLACKIS1, g4pic); } img.setDpi(dpiX, dpiY); img.setXYRatio(XYRatio); if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (icc_prof.getNumComponents() == 1) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } img.setOriginalType(Image.ORIGINAL_TIFF); if (rotation != 0) img.setInitialRotation(rotation); return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
protected static Image getTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s) { try { int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); int predictor = 1; TIFFLZWDecoder lzwDecoder = null; switch (compression) { case TIFFConstants.COMPRESSION_NONE: case TIFFConstants.COMPRESSION_LZW: case TIFFConstants.COMPRESSION_PACKBITS: case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: case TIFFConstants.COMPRESSION_OJPEG: case TIFFConstants.COMPRESSION_JPEG: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.compression.1.is.not.supported", compression)); } int photometric = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); switch (photometric) { case TIFFConstants.PHOTOMETRIC_MINISWHITE: case TIFFConstants.PHOTOMETRIC_MINISBLACK: case TIFFConstants.PHOTOMETRIC_RGB: case TIFFConstants.PHOTOMETRIC_SEPARATED: case TIFFConstants.PHOTOMETRIC_PALETTE: break; default: if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.photometric.1.is.not.supported", photometric)); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } if (dir.isTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) && dir.getFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("planar.images.are.not.supported")); int extraSamples = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES)) extraSamples = 1; int samplePerPixel = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4 samplePerPixel = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL); int bitsPerSample = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE)) bitsPerSample = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE); switch (bitsPerSample) { case 1: case 2: case 4: case 8: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample)); } Image img = null; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); int fillOrder = 1; boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE) { TIFFField predictorField = dir.getField(TIFFConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.getAsInt(0); if (predictor != 1 && predictor != 2) { throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.value.for.predictor.in.tiff.file")); } if (predictor == 2 && bitsPerSample != 8) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample)); } } } if (compression == TIFFConstants.COMPRESSION_LZW) { lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel); } int rowsLeft = h; ByteArrayOutputStream stream = null; ByteArrayOutputStream mstream = null; DeflaterOutputStream zip = null; DeflaterOutputStream mzip = null; if (extraSamples > 0) { mstream = new ByteArrayOutputStream(); mzip = new DeflaterOutputStream(mstream); } CCITTG4Encoder g4 = null; if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4 = new CCITTG4Encoder(w); } else { stream = new ByteArrayOutputStream(); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) zip = new DeflaterOutputStream(stream); } if (compression == TIFFConstants.COMPRESSION_OJPEG) { // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and // is often missing if ((!dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET))) { throw new IOException(MessageLocalization.getComposedMessage("missing.tag.s.for.ojpeg.compression")); } int jpegOffset = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET); int jpegLength = (int)s.length() - jpegOffset; if (dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT)) { jpegLength = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0]; } byte[] jpeg = new byte[Math.min(jpegLength, (int)s.length() - jpegOffset)]; int posFilePointer = (int)s.getFilePointer(); posFilePointer += jpegOffset; s.seek(posFilePointer); s.readFully(jpeg); img = new Jpeg(jpeg); } else if (compression == TIFFConstants.COMPRESSION_JPEG) { if (size.length > 1) throw new IOException(MessageLocalization.getComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.length)); byte[] jpeg = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(jpeg); // if quantization and/or Huffman tables are stored separately in the tiff, // we need to add them to the jpeg data TIFFField jpegtables = dir.getField(TIFFConstants.TIFFTAG_JPEGTABLES); if (jpegtables != null) { byte[] temp = jpegtables.getAsBytes(); int tableoffset = 0; int tablelength = temp.length; // remove FFD8 from start if (temp[0] == (byte) 0xFF && temp[1] == (byte) 0xD8) { tableoffset = 2; tablelength -= 2; } // remove FFD9 from end if (temp[temp.length-2] == (byte) 0xFF && temp[temp.length-1] == (byte) 0xD9) tablelength -= 2; byte[] tables = new byte[tablelength]; System.arraycopy(temp, tableoffset, tables, 0, tablelength); // TODO insert after JFIF header, instead of at the start byte[] jpegwithtables = new byte[jpeg.length + tables.length]; System.arraycopy(jpeg, 0, jpegwithtables, 0, 2); System.arraycopy(tables, 0, jpegwithtables, 2, tables.length); System.arraycopy(jpeg, 2, jpegwithtables, tables.length+2, jpeg.length-2); jpeg = jpegwithtables; } img = new Jpeg(jpeg); } else { for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); byte outBuf[] = null; if (compression != TIFFConstants.COMPRESSION_NONE) outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height]; if (reverse) TIFFFaxDecoder.reverseBits(im); switch (compression) { case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: inflate(im, outBuf); applyPredictor(outBuf, predictor, w, height, samplePerPixel); break; case TIFFConstants.COMPRESSION_NONE: outBuf = im; break; case TIFFConstants.COMPRESSION_PACKBITS: decodePackbits(im, outBuf); break; case TIFFConstants.COMPRESSION_LZW: lzwDecoder.decode(im, outBuf, height); break; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4.fax4Encode(outBuf, height); } else { if (extraSamples > 0) ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height); else zip.write(outBuf); } rowsLeft -= rowsStrip; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { img = Image.getInstance(w, h, false, Image.CCITTG4, photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.close()); } else { zip.close(); img = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.toByteArray()); img.setDeflated(true); } } img.setDpi(dpiX, dpiY); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) { if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (samplePerPixel - extraSamples == icc_prof.getNumComponents()) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } if (dir.isTagPresent(TIFFConstants.TIFFTAG_COLORMAP)) { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_COLORMAP); char rgb[] = fd.getAsChars(); byte palette[] = new byte[rgb.length]; int gColor = rgb.length / 3; int bColor = gColor * 2; for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)(rgb[k] >>> 8); palette[k * 3 + 1] = (byte)(rgb[k + gColor] >>> 8); palette[k * 3 + 2] = (byte)(rgb[k + bColor] >>> 8); } // Colormap components are supposed to go from 0 to 655535 but, // as usually, some tiff producers just put values from 0 to 255. // Let's check for these broken tiffs. boolean colormapBroken = true; for (int k = 0; k < palette.length; ++k) { if (palette[k] != 0) { colormapBroken = false; break; } } if (colormapBroken) { for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)rgb[k]; palette[k * 3 + 1] = (byte)rgb[k + gColor]; palette[k * 3 + 2] = (byte)rgb[k + bColor]; } } PdfArray indexed = new PdfArray(); indexed.add(PdfName.INDEXED); indexed.add(PdfName.DEVICERGB); indexed.add(new PdfNumber(gColor - 1)); indexed.add(new PdfString(palette)); PdfDictionary additional = new PdfDictionary(); additional.put(PdfName.COLORSPACE, indexed); img.setAdditional(additional); } img.setOriginalType(Image.ORIGINAL_TIFF); } if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE) img.setInverted(true); if (rotation != 0) img.setInitialRotation(rotation); if (extraSamples > 0) { mzip.close(); Image mimg = Image.getInstance(w, h, 1, bitsPerSample, mstream.toByteArray()); mimg.makeMask(); mimg.setDeflated(true); img.setImageMask(mimg); } return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// 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/TIFFField.java
public int compareTo(TIFFField o) { if(o == null) { throw new IllegalArgumentException(); } int oTag = o.getTag(); if(tag < oTag) { return -1; } else if(tag > oTag) { return 1; } else { return 0; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
PdfIndirectReference getIndirectReference() { if (refFont == null) throw new IllegalArgumentException("Font reuse not allowed with direct font objects."); return refFont; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseField.java
public void setRotation(int rotation) { if (rotation % 90 != 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("rotation.must.be.a.multiple.of.90")); rotation %= 360; if (rotation < 0) rotation += 360; this.rotation = rotation; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public void addElement(Element element) { if (element == null) return; if (element instanceof Image) { Image img = (Image)element; PdfPTable t = new PdfPTable(1); float w = img.getWidthPercentage(); if (w == 0) { t.setTotalWidth(img.getScaledWidth()); t.setLockedWidth(true); } else t.setWidthPercentage(w); t.setSpacingAfter(img.getSpacingAfter()); t.setSpacingBefore(img.getSpacingBefore()); switch (img.getAlignment()) { case Image.LEFT: t.setHorizontalAlignment(Element.ALIGN_LEFT); break; case Image.RIGHT: t.setHorizontalAlignment(Element.ALIGN_RIGHT); break; default: t.setHorizontalAlignment(Element.ALIGN_CENTER); break; } PdfPCell c = new PdfPCell(img, true); c.setPadding(0); c.setBorder(img.getBorder()); c.setBorderColor(img.getBorderColor()); c.setBorderWidth(img.getBorderWidth()); c.setBackgroundColor(img.getBackgroundColor()); t.addCell(c); element = t; } if (element.type() == Element.CHUNK) { element = new Paragraph((Chunk)element); } else if (element.type() == Element.PHRASE) { element = new Paragraph((Phrase)element); } if (element.type() != Element.PARAGRAPH && element.type() != Element.LIST && element.type() != Element.PTABLE && element.type() != Element.YMARK && element.type() != Element.DIV) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("element.not.allowed")); if (!composite) { composite = true; compositeElements = new LinkedList<Element>(); bidiLine = null; waitPhrase = null; } if (element.type() == Element.PARAGRAPH) { Paragraph p = (Paragraph)element; compositeElements.addAll(p.breakUp()); return; } compositeElements.add(element); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setListOption(String fieldName, String[] exportValues, String[] displayValues) { if (exportValues == null && displayValues == null) return false; if (exportValues != null && displayValues != null && exportValues.length != displayValues.length) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.export.and.the.display.array.must.have.the.same.size")); int ftype = getFieldType(fieldName); if (ftype != FIELD_TYPE_COMBO && ftype != FIELD_TYPE_LIST) return false; Item fd = fields.get(fieldName); String[] sing = null; if (exportValues == null && displayValues != null) sing = displayValues; else if (exportValues != null && displayValues == null) sing = exportValues; PdfArray opt = new PdfArray(); if (sing != null) { for (int k = 0; k < sing.length; ++k) opt.add(new PdfString(sing[k], PdfObject.TEXT_UNICODE)); } else { for (int k = 0; k < exportValues.length; ++k) { PdfArray a = new PdfArray(); a.add(new PdfString(exportValues[k], PdfObject.TEXT_UNICODE)); a.add(new PdfString(displayValues[k], PdfObject.TEXT_UNICODE)); opt.add(a); } } fd.writeToAll( PdfName.OPT, opt, Item.WRITE_VALUE | Item.WRITE_MERGED ); return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAction.java
public static PdfAction setOCGstate(ArrayList<Object> state, boolean preserveRB) { PdfAction action = new PdfAction(); action.put(PdfName.S, PdfName.SETOCGSTATE); PdfArray a = new PdfArray(); for (int k = 0; k < state.size(); ++k) { Object o = state.get(k); if (o == null) continue; if (o instanceof PdfIndirectReference) a.add((PdfIndirectReference)o); else if (o instanceof PdfLayer) a.add(((PdfLayer)o).getRef()); else if (o instanceof PdfName) a.add((PdfName)o); else if (o instanceof String) { PdfName name = null; String s = (String)o; if (s.equalsIgnoreCase("on")) name = PdfName.ON; else if (s.equalsIgnoreCase("off")) name = PdfName.OFF; else if (s.equalsIgnoreCase("toggle")) name = PdfName.TOGGLE; else throw new IllegalArgumentException(MessageLocalization.getComposedMessage("a.string.1.was.passed.in.state.only.on.off.and.toggle.are.allowed", s)); a.add(name); } else throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.type.was.passed.in.state.1", o.getClass().getName())); } action.put(PdfName.STATE, a); if (!preserveRB) action.put(PdfName.PRESERVERB, PdfBoolean.PDFFALSE); return action; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setTagged() { if (open) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("tagging.must.be.set.before.opening.the.document")); tagged = true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
void registerLayer(final PdfOCG layer) { PdfWriter.checkPdfIsoConformance(this, PdfIsoKeys.PDFISOKEY_LAYER, null); if (layer instanceof PdfLayer) { PdfLayer la = (PdfLayer)layer; if (la.getTitle() == null) { if (!documentOCG.contains(layer)) { documentOCG.add(layer); documentOCGorder.add(layer); } } else { documentOCGorder.add(layer); } } else throw new IllegalArgumentException(MessageLocalization.getComposedMessage("only.pdflayer.is.accepted")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/crypto/AESCipherCBCnoPad.java
public byte[] processBlock(byte[] inp, int inpOff, int inpLen) { if ((inpLen % cbc.getBlockSize()) != 0) throw new IllegalArgumentException("Not multiple of block: " + inpLen); byte[] outp = new byte[inpLen]; int baseOffset = 0; while (inpLen > 0) { cbc.processBlock(inp, inpOff, outp, baseOffset); inpLen -= cbc.getBlockSize(); baseOffset += cbc.getBlockSize(); inpOff += cbc.getBlockSize(); } return outp; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
public void setVisibleSignature(Rectangle pageRect, int page, String fieldName) { if (fieldName != null) { if (fieldName.indexOf('.') >= 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("field.names.cannot.contain.a.dot")); AcroFields af = writer.getAcroFields(); AcroFields.Item item = af.getFieldItem(fieldName); if (item != null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.field.1.already.exists", fieldName)); this.fieldName = fieldName; } if (page < 1 || page > writer.reader.getNumberOfPages()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.page.number.1", page)); this.pageRect = new Rectangle(pageRect); this.pageRect.normalize(); rect = new Rectangle(this.pageRect.getWidth(), this.pageRect.getHeight()); this.page = page; newField = true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
public void setVisibleSignature(String fieldName) { AcroFields af = writer.getAcroFields(); AcroFields.Item item = af.getFieldItem(fieldName); if (item == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.field.1.does.not.exist", fieldName)); PdfDictionary merged = item.getMerged(0); if (!PdfName.SIG.equals(PdfReader.getPdfObject(merged.get(PdfName.FT)))) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.field.1.is.not.a.signature.field", fieldName)); this.fieldName = fieldName; PdfArray r = merged.getAsArray(PdfName.RECT); float llx = r.getAsNumber(0).floatValue(); float lly = r.getAsNumber(1).floatValue(); float urx = r.getAsNumber(2).floatValue(); float ury = r.getAsNumber(3).floatValue(); pageRect = new Rectangle(llx, lly, urx, ury); pageRect.normalize(); page = item.getPage(0).intValue(); int rotation = writer.reader.getPageRotation(page); Rectangle pageSize = writer.reader.getPageSizeWithRotation(page); switch (rotation) { case 90: pageRect = new Rectangle( pageRect.getBottom(), pageSize.getTop() - pageRect.getLeft(), pageRect.getTop(), pageSize.getTop() - pageRect.getRight()); break; case 180: pageRect = new Rectangle( pageSize.getRight() - pageRect.getLeft(), pageSize.getTop() - pageRect.getBottom(), pageSize.getRight() - pageRect.getRight(), pageSize.getTop() - pageRect.getTop()); break; case 270: pageRect = new Rectangle( pageSize.getRight() - pageRect.getBottom(), pageRect.getLeft(), pageSize.getRight() - pageRect.getTop(), pageRect.getRight()); break; } if (rotation != 0) pageRect.normalize(); rect = new Rectangle(this.pageRect.getWidth(), this.pageRect.getHeight()); }
// 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 flatFields() { if (append) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("field.flattening.is.not.supported.in.append.mode")); getAcroFields(); Map<String, Item> fields = acroFields.getFields(); if (fieldsAdded && partialFlattening.isEmpty()) { for (String s: fields.keySet()) { partialFlattening.add(s); } } PdfDictionary acroForm = reader.getCatalog().getAsDict(PdfName.ACROFORM); PdfArray acroFds = null; if (acroForm != null) { acroFds = (PdfArray)PdfReader.getPdfObject(acroForm.get(PdfName.FIELDS), acroForm); } for (Map.Entry<String, Item> entry: fields.entrySet()) { String name = entry.getKey(); if (!partialFlattening.isEmpty() && !partialFlattening.contains(name)) continue; AcroFields.Item item = entry.getValue(); for (int k = 0; k < item.size(); ++k) { PdfDictionary merged = item.getMerged(k); PdfNumber ff = merged.getAsNumber(PdfName.F); int flags = 0; if (ff != null) flags = ff.intValue(); int page = item.getPage(k).intValue(); PdfDictionary appDic = merged.getAsDict(PdfName.AP); if (appDic != null && (flags & PdfFormField.FLAGS_PRINT) != 0 && (flags & PdfFormField.FLAGS_HIDDEN) == 0) { PdfObject obj = appDic.get(PdfName.N); PdfAppearance app = null; if (obj != null) { PdfObject objReal = PdfReader.getPdfObject(obj); if (obj instanceof PdfIndirectReference && !obj.isIndirect()) app = new PdfAppearance((PdfIndirectReference)obj); else if (objReal instanceof PdfStream) { ((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM); app = new PdfAppearance((PdfIndirectReference)obj); } else { if (objReal != null && objReal.isDictionary()) { PdfName as = merged.getAsName(PdfName.AS); if (as != null) { PdfIndirectReference iref = (PdfIndirectReference)((PdfDictionary)objReal).get(as); if (iref != null) { app = new PdfAppearance(iref); if (iref.isIndirect()) { objReal = PdfReader.getPdfObject(iref); ((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM); } } } } } } if (app != null) { Rectangle box = PdfReader.getNormalizedRectangle(merged.getAsArray(PdfName.RECT)); PdfContentByte cb = getOverContent(page); cb.setLiteral("Q "); cb.addTemplate(app, box.getLeft(), box.getBottom()); cb.setLiteral("q "); } } if (partialFlattening.isEmpty()) continue; PdfDictionary pageDic = reader.getPageN(page); PdfArray annots = pageDic.getAsArray(PdfName.ANNOTS); if (annots == null) continue; for (int idx = 0; idx < annots.size(); ++idx) { PdfObject ran = annots.getPdfObject(idx); if (!ran.isIndirect()) continue; PdfObject ran2 = item.getWidgetRef(k); if (!ran2.isIndirect()) continue; if (((PRIndirectReference)ran).getNumber() == ((PRIndirectReference)ran2).getNumber()) { annots.remove(idx--); PRIndirectReference wdref = (PRIndirectReference)ran2; while (true) { PdfDictionary wd = (PdfDictionary)PdfReader.getPdfObject(wdref); PRIndirectReference parentRef = (PRIndirectReference)wd.get(PdfName.PARENT); PdfReader.killIndirect(wdref); if (parentRef == null) { // reached AcroForm for (int fr = 0; fr < acroFds.size(); ++fr) { PdfObject h = acroFds.getPdfObject(fr); if (h.isIndirect() && ((PRIndirectReference)h).getNumber() == wdref.getNumber()) { acroFds.remove(fr); --fr; } } break; } PdfDictionary parent = (PdfDictionary)PdfReader.getPdfObject(parentRef); PdfArray kids = parent.getAsArray(PdfName.KIDS); for (int fr = 0; fr < kids.size(); ++fr) { PdfObject h = kids.getPdfObject(fr); if (h.isIndirect() && ((PRIndirectReference)h).getNumber() == wdref.getNumber()) { kids.remove(fr); --fr; } } if (!kids.isEmpty()) break; wdref = parentRef; } } } if (annots.isEmpty()) { PdfReader.killIndirect(pageDic.get(PdfName.ANNOTS)); pageDic.remove(PdfName.ANNOTS); } } } if (!fieldsAdded && partialFlattening.isEmpty()) { for (int page = 1; page <= reader.getNumberOfPages(); ++page) { PdfDictionary pageDic = reader.getPageN(page); PdfArray annots = pageDic.getAsArray(PdfName.ANNOTS); if (annots == null) continue; for (int idx = 0; idx < annots.size(); ++idx) { PdfObject annoto = annots.getDirectObject(idx); if (annoto instanceof PdfIndirectReference && !annoto.isIndirect()) continue; if (!annoto.isDictionary() || PdfName.WIDGET.equals(((PdfDictionary)annoto).get(PdfName.SUBTYPE))) { annots.remove(idx); --idx; } } if (annots.isEmpty()) { PdfReader.killIndirect(pageDic.get(PdfName.ANNOTS)); pageDic.remove(PdfName.ANNOTS); } } eliminateAcroformObjects(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
protected void flatFreeTextFields() { if (append) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("freetext.flattening.is.not.supported.in.append.mode")); for (int page = 1; page <= reader.getNumberOfPages(); ++page) { PdfDictionary pageDic = reader.getPageN(page); PdfArray annots = pageDic.getAsArray(PdfName.ANNOTS); if (annots == null) continue; for (int idx = 0; idx < annots.size(); ++idx) { PdfObject annoto = annots.getDirectObject(idx); if (annoto instanceof PdfIndirectReference && !annoto.isIndirect()) continue; PdfDictionary annDic = (PdfDictionary)annoto; if (!((PdfName)annDic.get(PdfName.SUBTYPE)).equals(PdfName.FREETEXT)) continue; PdfNumber ff = annDic.getAsNumber(PdfName.F); int flags = ff != null ? ff.intValue() : 0; if ( (flags & PdfFormField.FLAGS_PRINT) != 0 && (flags & PdfFormField.FLAGS_HIDDEN) == 0) { PdfObject obj1 = annDic.get(PdfName.AP); if (obj1 == null) continue; PdfDictionary appDic = obj1 instanceof PdfIndirectReference ? (PdfDictionary) PdfReader.getPdfObject(obj1) : (PdfDictionary) obj1; PdfObject obj = appDic.get(PdfName.N); PdfAppearance app = null; PdfObject objReal = PdfReader.getPdfObject(obj); if (obj instanceof PdfIndirectReference && !obj.isIndirect()) app = new PdfAppearance((PdfIndirectReference)obj); else if (objReal instanceof PdfStream) { ((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM); app = new PdfAppearance((PdfIndirectReference)obj); } else { if (objReal.isDictionary()) { PdfName as_p = appDic.getAsName(PdfName.AS); if (as_p != null) { PdfIndirectReference iref = (PdfIndirectReference)((PdfDictionary)objReal).get(as_p); if (iref != null) { app = new PdfAppearance(iref); if (iref.isIndirect()) { objReal = PdfReader.getPdfObject(iref); ((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM); } } } } } if (app != null) { Rectangle box = PdfReader.getNormalizedRectangle(annDic.getAsArray(PdfName.RECT)); PdfContentByte cb = getOverContent(page); cb.setLiteral("Q "); cb.addTemplate(app, box.getLeft(), box.getBottom()); cb.setLiteral("q "); } } } for (int idx = 0; idx < annots.size(); ++idx) { PdfDictionary annot = annots.getAsDict(idx); if (annot != null) { if (PdfName.FREETEXT.equals(annot.get(PdfName.SUBTYPE))) { annots.remove(idx); --idx; } } } if (annots.isEmpty()) { PdfReader.killIndirect(pageDic.get(PdfName.ANNOTS)); pageDic.remove(PdfName.ANNOTS); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public PdfIndirectReference getPageReference(int page) { PdfIndirectReference ref = reader.getPageOrigRef(page); if (ref == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.page.number.1", page)); return ref; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPCell.java
public void setRotation(int rotation) { rotation %= 360; if (rotation < 0) rotation += 360; if (rotation % 90 != 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("rotation.must.be.a.multiple.of.90")); this.rotation = rotation; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/events/FieldPositioningEvents.java
public void cellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] canvases) { if (cellField == null || fieldWriter == null && parent == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.used.the.wrong.constructor.for.this.fieldpositioningevents.class")); cellField.put(PdfName.RECT, new PdfRectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding), rect.getTop(padding))); if (parent == null) fieldWriter.addAnnotation(cellField); else parent.addKid(cellField); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
private byte[] convertToBytesAfterGlyphSubstitution(final String text) throws UnsupportedEncodingException { if (!canApplyGlyphSubstitution()) { throw new IllegalArgumentException("Make sure the font type if TTF Unicode and a valid GlyphSubstitutionTable exists!"); } Map<String, Glyph> glyphSubstitutionMap = ttu.getGlyphSubstitutionMap(); // generate a regex from the characters to be substituted // for Indic languages: push back the CompositeCharacters with smaller length Set<String> compositeCharacters = new TreeSet<String>(new IndicCompositeCharacterComparator()); compositeCharacters.addAll(glyphSubstitutionMap.keySet()); // convert the text to a list of Glyph, also take care of the substitution ArrayBasedStringTokenizer tokenizer = new ArrayBasedStringTokenizer(compositeCharacters.toArray(new String[0])); String[] tokens = tokenizer.tokenize(text); List<Glyph> glyphList = new ArrayList<Glyph>(50); for (String token : tokens) { // first check whether this is in the substitution map Glyph subsGlyph = glyphSubstitutionMap.get(token); if (subsGlyph != null) { glyphList.add(subsGlyph); } else { // break up the string into individual characters for (char c : token.toCharArray()) { int[] metrics = ttu.getMetricsTT(c); int glyphCode = metrics[0]; int glyphWidth = metrics[1]; glyphList.add(new Glyph(glyphCode, glyphWidth, String.valueOf(c))); } } } GlyphRepositioner glyphRepositioner = getGlyphRepositioner(); if (glyphRepositioner != null) { glyphRepositioner.repositionGlyphs(glyphList); } char[] charEncodedGlyphCodes = new char[glyphList.size()]; // process each Glyph thus obtained for (int i = 0; i < glyphList.size(); i++) { Glyph glyph = glyphList.get(i); charEncodedGlyphCodes[i] = (char) glyph.code; Integer glyphCode = Integer.valueOf(glyph.code); if (!longTag.containsKey(glyphCode)) { // FIXME: this is buggy as the 3rd arg. should be a String as a Glyph can represent more than 1 char longTag.put(glyphCode, new int[]{glyph.code, glyph.width, glyph.chars.charAt(0)}); } } return new String(charEncodedGlyphCodes).getBytes(CJKFont.CJK_ENCODING); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
private GlyphRepositioner getGlyphRepositioner() { Language language = ttu.getSupportedLanguage(); if (language == null) { throw new IllegalArgumentException("The supported language field cannot be null in " + ttu.getClass().getName()); } switch (language) { case BENGALI: return new BanglaGlyphRepositioner(Collections.unmodifiableMap(ttu.cmap31), ttu.getGlyphSubstitutionMap()); default: return null; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/ReedSolomonEncoder.java
public void encode(int[] toEncode, int ecBytes) { if (ecBytes == 0) { throw new IllegalArgumentException("No error correction bytes"); } int dataBytes = toEncode.length - ecBytes; if (dataBytes <= 0) { throw new IllegalArgumentException("No data bytes provided"); } GF256Poly generator = buildGenerator(ecBytes); int[] infoCoefficients = new int[dataBytes]; System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes); GF256Poly info = new GF256Poly(field, infoCoefficients); info = info.multiplyByMonomial(ecBytes, 1); GF256Poly remainder = info.divide(generator)[1]; int[] coefficients = remainder.getCoefficients(); int numZeroCoefficients = ecBytes - coefficients.length; for (int i = 0; i < numZeroCoefficients; i++) { toEncode[dataBytes + i] = 0; } System.arraycopy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.length); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Version.java
public static Version getProvisionalVersionForDimension(int dimension) { if (dimension % 4 != 1) { throw new IllegalArgumentException(); } try { return getVersionForNumber((dimension - 17) >> 2); } catch (IllegalArgumentException iae) { throw iae; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Version.java
public static Version getVersionForNumber(int versionNumber) { if (versionNumber < 1 || versionNumber > 40) { throw new IllegalArgumentException(); } return VERSIONS[versionNumber - 1]; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Mode.java
public static Mode forBits(int bits) { switch (bits) { case 0x0: return TERMINATOR; case 0x1: return NUMERIC; case 0x2: return ALPHANUMERIC; case 0x3: return STRUCTURED_APPEND; case 0x4: return BYTE; case 0x5: return FNC1_FIRST_POSITION; case 0x7: return ECI; case 0x8: return KANJI; case 0x9: return FNC1_SECOND_POSITION; default: throw new IllegalArgumentException(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Mode.java
public int getCharacterCountBits(Version version) { if (characterCountBitsForVersions == null) { throw new IllegalArgumentException("Character count doesn't apply to this mode"); } int number = version.getVersionNumber(); int offset; if (number <= 9) { offset = 0; } else if (number <= 26) { offset = 1; } else { offset = 2; } return characterCountBitsForVersions[offset]; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256Poly.java
GF256Poly addOrSubtract(GF256Poly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GF256Polys do not have same GF256 field"); } if (isZero()) { return other; } if (other.isZero()) { return this; } int[] smallerCoefficients = this.coefficients; int[] largerCoefficients = other.coefficients; if (smallerCoefficients.length > largerCoefficients.length) { int[] temp = smallerCoefficients; smallerCoefficients = largerCoefficients; largerCoefficients = temp; } int[] sumDiff = new int[largerCoefficients.length]; int lengthDiff = largerCoefficients.length - smallerCoefficients.length; // Copy high-order terms only found in higher-degree polynomial's coefficients System.arraycopy(largerCoefficients, 0, sumDiff, 0, lengthDiff); for (int i = lengthDiff; i < largerCoefficients.length; i++) { sumDiff[i] = GF256.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]); } return new GF256Poly(field, sumDiff); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256Poly.java
GF256Poly multiply(GF256Poly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GF256Polys do not have same GF256 field"); } if (isZero() || other.isZero()) { return field.getZero(); } int[] aCoefficients = this.coefficients; int aLength = aCoefficients.length; int[] bCoefficients = other.coefficients; int bLength = bCoefficients.length; int[] product = new int[aLength + bLength - 1]; for (int i = 0; i < aLength; i++) { int aCoeff = aCoefficients[i]; for (int j = 0; j < bLength; j++) { product[i + j] = GF256.addOrSubtract(product[i + j], field.multiply(aCoeff, bCoefficients[j])); } } return new GF256Poly(field, product); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256Poly.java
GF256Poly multiplyByMonomial(int degree, int coefficient) { if (degree < 0) { throw new IllegalArgumentException(); } if (coefficient == 0) { return field.getZero(); } int size = coefficients.length; int[] product = new int[size + degree]; for (int i = 0; i < size; i++) { product[i] = field.multiply(coefficients[i], coefficient); } return new GF256Poly(field, product); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256Poly.java
GF256Poly[] divide(GF256Poly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GF256Polys do not have same GF256 field"); } if (other.isZero()) { throw new IllegalArgumentException("Divide by 0"); } GF256Poly quotient = field.getZero(); GF256Poly remainder = this; int denominatorLeadingTerm = other.getCoefficient(other.getDegree()); int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm); while (remainder.getDegree() >= other.getDegree() && !remainder.isZero()) { int degreeDifference = remainder.getDegree() - other.getDegree(); int scale = field.multiply(remainder.getCoefficient(remainder.getDegree()), inverseDenominatorLeadingTerm); GF256Poly term = other.multiplyByMonomial(degreeDifference, scale); GF256Poly iterationQuotient = field.buildMonomial(degreeDifference, scale); quotient = quotient.addOrSubtract(iterationQuotient); remainder = remainder.addOrSubtract(term); } return new GF256Poly[] { quotient, remainder }; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/ErrorCorrectionLevel.java
public static ErrorCorrectionLevel forBits(int bits) { if (bits < 0 || bits >= FOR_BITS.length) { throw new IllegalArgumentException(); } return FOR_BITS[bits]; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitArray.java
public boolean isRange(int start, int end, boolean value) { if (end < start) { throw new IllegalArgumentException(); } if (end == start) { return true; // empty range matches } end--; // will be easier to treat this as the last actually set bit -- inclusive int firstInt = start >> 5; int lastInt = end >> 5; for (int i = firstInt; i <= lastInt; i++) { int firstBit = i > firstInt ? 0 : start & 0x1F; int lastBit = i < lastInt ? 31 : end & 0x1F; int mask; if (firstBit == 0 && lastBit == 31) { mask = -1; } else { mask = 0; for (int j = firstBit; j <= lastBit; j++) { mask |= 1 << j; } } // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is, // equals the mask, or we're looking for 0s and the masked portion is not all 0s if ((bits[i] & mask) != (value ? mask : 0)) { return false; } } return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitMatrix.java
public void setRegion(int left, int top, int width, int height) { if (top < 0 || left < 0) { throw new IllegalArgumentException("Left and top must be nonnegative"); } if (height < 1 || width < 1) { throw new IllegalArgumentException("Height and width must be at least 1"); } int right = left + width; int bottom = top + height; if (bottom > this.height || right > this.width) { throw new IllegalArgumentException("The region must fit inside the matrix"); } for (int y = top; y < bottom; y++) { int offset = y * rowSize; for (int x = left; x < right; x++) { bits[offset + (x >> 5)] |= 1 << (x & 0x1f); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256.java
GF256Poly buildMonomial(int degree, int coefficient) { if (degree < 0) { throw new IllegalArgumentException(); } if (coefficient == 0) { return zero; } int[] coefficients = new int[degree + 1]; coefficients[0] = coefficient; return new GF256Poly(this, coefficients); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256.java
int log(int a) { if (a == 0) { throw new IllegalArgumentException(); } return logTable[a]; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/QRCodeWriter.java
public ByteMatrix encode(String contents, int width, int height, Map<EncodeHintType,Object> hints) throws WriterException { if (contents == null || contents.length() == 0) { throw new IllegalArgumentException("Found empty contents"); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height); } ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; if (hints != null) { ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints.get(EncodeHintType.ERROR_CORRECTION); if (requestedECLevel != null) { errorCorrectionLevel = requestedECLevel; } } QRCode code = new QRCode(); Encoder.encode(contents, errorCorrectionLevel, hints, code); return renderResult(code, width, height); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitVector.java
public int at(int index) { if (index < 0 || index >= sizeInBits) { throw new IllegalArgumentException("Bad index: " + index); } int value = array[index >> 3] & 0xff; return (value >> (7 - (index & 0x7))) & 1; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitVector.java
public void appendBit(int bit) { if (!(bit == 0 || bit == 1)) { throw new IllegalArgumentException("Bad bit"); } int numBitsInLastByte = sizeInBits & 0x7; // We'll expand array if we don't have bits in the last byte. if (numBitsInLastByte == 0) { appendByte(0); sizeInBits -= 8; } // Modify the last byte. array[sizeInBits >> 3] |= (bit << (7 - numBitsInLastByte)); ++sizeInBits; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitVector.java
public void appendBits(int value, int numBits) { if (numBits < 0 || numBits > 32) { throw new IllegalArgumentException("Num bits must be between 0 and 32"); } int numBitsLeft = numBits; while (numBitsLeft > 0) { // Optimization for byte-oriented appending. if ((sizeInBits & 0x7) == 0 && numBitsLeft >= 8) { int newByte = (value >> (numBitsLeft - 8)) & 0xff; appendByte(newByte); numBitsLeft -= 8; } else { int bit = (value >> (numBitsLeft - 1)) & 1; appendBit(bit); --numBitsLeft; } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitVector.java
public void xor(BitVector other) { if (sizeInBits != other.size()) { throw new IllegalArgumentException("BitVector sizes don't match"); } int sizeInBytes = (sizeInBits + 7) >> 3; for (int i = 0; i < sizeInBytes; ++i) { // The last byte could be incomplete (i.e. not have 8 bits in // it) but there is no problem since 0 XOR 0 == 0. array[i] ^= other.array[i]; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitVector.java
public String toString() { StringBuffer result = new StringBuffer(sizeInBits); for (int i = 0; i < sizeInBits; ++i) { if (at(i) == 0) { result.append('0'); } else if (at(i) == 1) { result.append('1'); } else { throw new IllegalArgumentException("Byte isn't 0 or 1"); } } return result.toString(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MaskUtil.java
public static boolean getDataMaskBit(int maskPattern, int x, int y) { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new IllegalArgumentException("Invalid mask pattern"); } int intermediate, temp; switch (maskPattern) { case 0: intermediate = (y + x) & 0x1; break; case 1: intermediate = y & 0x1; break; case 2: intermediate = x % 3; break; case 3: intermediate = (y + x) % 3; break; case 4: intermediate = ((y >>> 1) + (x / 3)) & 0x1; break; case 5: temp = y * x; intermediate = (temp & 0x1) + (temp % 3); break; case 6: temp = y * x; intermediate = (((temp & 0x1) + (temp % 3)) & 0x1); break; case 7: temp = y * x; intermediate = (((temp % 3) + ((y + x) & 0x1)) & 0x1); break; default: throw new IllegalArgumentException("Invalid mask pattern: " + maskPattern); } return intermediate == 0; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void setFontAndSize(final BaseFont bf, final float size) { if (!inText && isTagged()) { beginText(true); } checkWriter(); if (size < 0.0001f && size > -0.0001f) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("font.size.too.small.1", String.valueOf(size))); state.size = size; state.fontDetails = writer.addSimple(bf); PageResources prs = getPageResources(); PdfName name = state.fontDetails.getFontName(); name = prs.addFont(name, state.fontDetails.getIndirectReference()); content.append(name.getBytes()).append(' ').append(size).append(" Tf").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void beginLayer(final PdfOCG layer) { if (layer instanceof PdfLayer && ((PdfLayer)layer).getTitle() != null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("a.title.is.not.a.layer")); if (layerDepth == null) layerDepth = new ArrayList<Integer>(); if (layer instanceof PdfLayerMembership) { layerDepth.add(Integer.valueOf(1)); beginLayer2(layer); return; } int n = 0; PdfLayer la = (PdfLayer)layer; while (la != null) { if (la.getTitle() == null) { beginLayer2(la); ++n; } la = la.getParent(); } layerDepth.add(Integer.valueOf(n)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void beginMarkedContentSequence(final PdfStructureElement struc) { PdfObject obj = struc.get(PdfName.K); int mark = pdf.getMarkPoint(); if (obj != null) { PdfArray ar = null; if (obj.isNumber()) { ar = new PdfArray(); ar.add(obj); struc.put(PdfName.K, ar); } else if (obj.isArray()) { ar = (PdfArray)obj; } else throw new IllegalArgumentException(MessageLocalization.getComposedMessage("unknown.object.at.k.1", obj.getClass().toString())); if (ar.getAsNumber(0) != null) { PdfDictionary dic = new PdfDictionary(PdfName.MCR); dic.put(PdfName.PG, writer.getCurrentPage()); dic.put(PdfName.MCID, new PdfNumber(mark)); ar.add(dic); } struc.setPageMark(writer.getPageNumber() - 1, -1); } else { struc.setPageMark(writer.getPageNumber() - 1, mark); struc.put(PdfName.PG, writer.getCurrentPage()); } pdf.incMarkPoint(); setMcDepth(getMcDepth() + 1); int contentSize = content.size(); content.append(struc.get(PdfName.S).getBytes()).append(" <</MCID ").append(mark).append(">> BDC").append_i(separator); markedContentSize += content.size() - contentSize; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
public static byte[] getBarsCode39(String text) { text = "*" + text + "*"; byte bars[] = new byte[text.length() * 10 - 1]; for (int k = 0; k < text.length(); ++k) { int idx = CHARS.indexOf(text.charAt(k)); if (idx < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.character.1.is.illegal.in.code.39", text.charAt(k))); System.arraycopy(BARS[idx], 0, bars, k * 10, 9); } return bars; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
public static String getCode39Ex(String text) { StringBuilder out = new StringBuilder(""); for (int k = 0; k < text.length(); ++k) { char c = text.charAt(k); if (c > 127) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.character.1.is.illegal.in.code.39.extended", c)); char c1 = EXTENDED.charAt(c * 2); char c2 = EXTENDED.charAt(c * 2 + 1); if (c1 != ' ') out.append(c1); out.append(c2); } return out.toString(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
static char getChecksum(String text) { int chk = 0; for (int k = 0; k < text.length(); ++k) { int idx = CHARS.indexOf(text.charAt(k)); if (idx < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.character.1.is.illegal.in.code.39", text.charAt(k))); chk += idx; } return CHARS.charAt(chk % 43); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfLayer.java
public void addChild(PdfLayer child) { if (child.parent != null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.layer.1.already.has.a.parent", child.getAsString(PdfName.NAME).toUnicodeString())); child.parent = this; if (children == null) children = new ArrayList<PdfLayer>(); children.add(child); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type3Font.java
public PdfContentByte defineGlyph(char c, float wx, float llx, float lly, float urx, float ury) { if (c == 0 || c > 255) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.char.1.doesn.t.belong.in.this.type3.font", c)); usedSlot[c] = true; Integer ck = Integer.valueOf(c); Type3Glyph glyph = char2glyph.get(ck); if (glyph != null) return glyph; widths3.put(c, (int)wx); if (!colorized) { if (Float.isNaN(this.llx)) { this.llx = llx; this.lly = lly; this.urx = urx; this.ury = ury; } else { this.llx = Math.min(this.llx, llx); this.lly = Math.min(this.lly, lly); this.urx = Math.max(this.urx, urx); this.ury = Math.max(this.ury, ury); } } glyph = new Type3Glyph(writer, pageResources, wx, llx, lly, urx, ury, colorized); char2glyph.put(ck, glyph); return glyph; }
// 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/Type3Font.java
Override public int getWidth(int char1) { if (!widths3.containsKey(char1)) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.char.1.is.not.defined.in.a.type3.font", char1)); return widths3.get(char1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReaderInstance.java
PdfImportedPage getImportedPage(int pageNumber) { if (!reader.isOpenedWithFullPermissions()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password")); if (pageNumber < 1 || pageNumber > reader.getNumberOfPages()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.page.number.1", pageNumber)); Integer i = Integer.valueOf(pageNumber); PdfImportedPage pageT = importedPages.get(i); if (pageT == null) { pageT = new PdfImportedPage(this, writer, pageNumber); importedPages.put(i, pageT); } return pageT; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfVisibilityExpression.java
Override public void add(int index, PdfObject element) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.ve.value")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfVisibilityExpression.java
Override public boolean add(PdfObject object) { if (object instanceof PdfLayer) return super.add(((PdfLayer)object).getRef()); if (object instanceof PdfVisibilityExpression) return super.add(object); throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.ve.value")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfVisibilityExpression.java
Override public void addFirst(PdfObject object) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.ve.value")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfVisibilityExpression.java
Override public boolean add(float[] values) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.ve.value")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfVisibilityExpression.java
Override public boolean add(int[] values) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.ve.value")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFormsImp.java
public void copyDocumentFields(PdfReader reader) throws DocumentException { if (!reader.isOpenedWithFullPermissions()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password")); 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()); fields.add(reader.getAcroFields()); updateCalculationOrder(reader); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/collection/PdfCollectionSort.java
public void setSortOrder(boolean ascending) { PdfObject o = get(PdfName.S); if (o instanceof PdfName) { put(PdfName.A, new PdfBoolean(ascending)); } else { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.to.define.a.boolean.array.for.this.collection.sort.dictionary")); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/collection/PdfCollectionSort.java
public void setSortOrder(boolean[] ascending) { PdfObject o = get(PdfName.S); if (o instanceof PdfArray) { if (((PdfArray)o).size() != ascending.length) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.number.of.booleans.in.this.array.doesn.t.correspond.with.the.number.of.fields")); } PdfArray array = new PdfArray(); for (int i = 0; i < ascending.length; i++) { array.add(new PdfBoolean(ascending[i])); } put(PdfName.A, array); } else { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.need.a.single.boolean.for.this.collection.sort.dictionary")); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/collection/PdfCollectionItem.java
public void setPrefix(String key, String prefix) { PdfName fieldname = new PdfName(key); PdfObject o = get(fieldname); if (o == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.must.set.a.value.before.adding.a.prefix")); PdfDictionary dict = new PdfDictionary(PdfName.COLLECTIONSUBITEM); dict.put(PdfName.D, o); dict.put(PdfName.P, new PdfString(prefix, PdfObject.TEXT_UNICODE)); put(fieldname, dict); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/collection/PdfCollectionField.java
public PdfObject getValue(String v) { switch(fieldType) { case TEXT: return new PdfString(v, PdfObject.TEXT_UNICODE); case DATE: return new PdfDate(PdfDate.decode(v)); case NUMBER: return new PdfNumber(v); } throw new IllegalArgumentException(MessageLocalization.getComposedMessage("1.is.not.an.acceptable.value.for.the.field.2", v, get(PdfName.N).toString())); }
// 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) { PdfName dictionaryName = (PdfName)operands.get(0); PdfDictionary extGState = processor.resources.getAsDict(PdfName.EXTGSTATE); if (extGState == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("resources.do.not.contain.extgstate.entry.unable.to.process.operator.1", operator)); PdfDictionary gsDic = extGState.getAsDict(dictionaryName); if (gsDic == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("1.is.an.unknown.graphics.state.dictionary", dictionaryName)); // at this point, all we care about is the FONT entry in the GS dictionary PdfArray fontParameter = gsDic.getAsArray(PdfName.FONT); if (fontParameter != null){ CMapAwareDocumentFont font = processor.getFont((PRIndirectReference)fontParameter.getPdfObject(0)); float size = fontParameter.getAsNumber(1).floatValue(); processor.gs().font = font; processor.gs().fontSize = size; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/InlineImageUtils.java
private static int getComponentsPerPixel(PdfName colorSpaceName, PdfDictionary colorSpaceDic){ if (colorSpaceName == null) return 1; if (colorSpaceName.equals(PdfName.DEVICEGRAY)) return 1; if (colorSpaceName.equals(PdfName.DEVICERGB)) return 3; if (colorSpaceName.equals(PdfName.DEVICECMYK)) return 4; if (colorSpaceDic != null){ PdfArray colorSpace = colorSpaceDic.getAsArray(colorSpaceName); if (colorSpace != null){ if (PdfName.INDEXED.equals(colorSpace.getAsName(0))){ return 1; } } } throw new IllegalArgumentException("Unexpected color space " + colorSpaceName); }
// 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/ICC_Profile.java
public static ICC_Profile getInstance(byte[] data, int numComponents) { if (data.length < 128 || data[36] != 0x61 || data[37] != 0x63 || data[38] != 0x73 || data[39] != 0x70) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); try { ICC_Profile icc = new ICC_Profile(); icc.data = data; Integer cs; cs = cstags.get(new String(data, 16, 4, "US-ASCII")); int nc = cs == null ? 0 : cs.intValue(); icc.numComponents = nc; // invalid ICC if (nc != numComponents) { throw new IllegalArgumentException("ICC profile contains " + nc + " component(s), the image data contains " + numComponents + " component(s)"); } return icc; } catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
public static ICC_Profile getInstance(InputStream file) { try { byte[] head = new byte[128]; int remain = head.length; int ptr = 0; while (remain > 0) { int n = file.read(head, ptr, remain); if (n < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain -= n; ptr += n; } if (head[36] != 0x61 || head[37] != 0x63 || head[38] != 0x73 || head[39] != 0x70) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain = (head[0] & 0xff) << 24 | (head[1] & 0xff) << 16 | (head[2] & 0xff) << 8 | head[3] & 0xff; byte[] icc = new byte[remain]; System.arraycopy(head, 0, icc, 0, head.length); remain -= head.length; ptr = head.length; while (remain > 0) { int n = file.read(icc, ptr, remain); if (n < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain -= n; ptr += n; } return getInstance(icc); } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
public int getDestinationPage() { if (!isInternal()) return 0; // here destination is something like // [132 0 R, /XYZ, 29.3898, 731.864502, null] PdfIndirectReference ref = destination.getAsIndirectObject(0); PRIndirectReference pr = (PRIndirectReference) ref; PdfReader r = pr.getReader(); for (int i = 1; i <= r.getNumberOfPages(); i++) { PRIndirectReference pp = r.getPageOrigRef(i); if (pp.getGeneration() == pr.getGeneration() && pp.getNumber() == pr.getNumber()) return i; } throw new IllegalArgumentException(MessageLocalization.getComposedMessage("page.not.found")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
public void setDestinationPage(int newPage) { if (!isInternal()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("cannot.change.destination.of.external.link")); this.newPage=newPage; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
public void transformDestination(float a, float b, float c, float d, float e, float f) { if (!isInternal()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("cannot.change.destination.of.external.link")); if (destination.getAsName(1).equals(PdfName.XYZ)) { float x = destination.getAsNumber(2).floatValue(); float y = destination.getAsNumber(3).floatValue(); float xx = x * a + y * c + e; float yy = x * b + y * d + f; destination.set(2, new PdfNumber(xx)); destination.set(3, new PdfNumber(yy)); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
public void paintCode() { int maxErr, lenErr, tot, pad; if ((options & PDF417_USE_RAW_CODEWORDS) != 0) { if (lenCodewords > MAX_DATA_CODEWORDS || lenCodewords < 1 || lenCodewords != codewords[0]) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.codeword.size")); } } else { if (text == null) throw new NullPointerException(MessageLocalization.getComposedMessage("text.cannot.be.null")); if (text.length > ABSOLUTE_MAX_TEXT_SIZE) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } segmentList = new SegmentList(); breakString(); //dumpList(); assemble(); segmentList = null; codewords[0] = lenCodewords = cwPtr; } maxErr = maxPossibleErrorLevel(MAX_DATA_CODEWORDS + 2 - lenCodewords); if ((options & PDF417_USE_ERROR_LEVEL) == 0) { if (lenCodewords < 41) errorLevel = 2; else if (lenCodewords < 161) errorLevel = 3; else if (lenCodewords < 321) errorLevel = 4; else errorLevel = 5; } if (errorLevel < 0) errorLevel = 0; else if (errorLevel > maxErr) errorLevel = maxErr; if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) codeRows = 90; lenErr = 2 << errorLevel; boolean fixedColumn = (options & PDF417_FIXED_ROWS) == 0; boolean skipRowColAdjust = false; tot = lenCodewords + lenErr; if ((options & PDF417_FIXED_RECTANGLE) != 0) { tot = codeColumns * codeRows; if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } if (tot < lenCodewords + lenErr) tot = lenCodewords + lenErr; else skipRowColAdjust = true; } else if ((options & (PDF417_FIXED_COLUMNS | PDF417_FIXED_ROWS)) == 0) { double c, b; fixedColumn = true; if (aspectRatio < 0.001) aspectRatio = 0.001f; else if (aspectRatio > 1000) aspectRatio = 1000; b = 73 * aspectRatio - 4; c = (-b + Math.sqrt(b * b + 4 * 17 * aspectRatio * (lenCodewords + lenErr) * yHeight)) / (2 * 17 * aspectRatio); codeColumns = (int)(c + 0.5); if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; } if (!skipRowColAdjust) { if (fixedColumn) { codeRows = (tot - 1) / codeColumns + 1; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) { codeRows = 90; codeColumns = (tot - 1) / 90 + 1; } } else { codeColumns = (tot - 1) / codeRows + 1; if (codeColumns > 30) { codeColumns = 30; codeRows = (tot - 1) / 30 + 1; } } tot = codeRows * codeColumns; } if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } errorLevel = maxPossibleErrorLevel(tot - lenCodewords); lenErr = 2 << errorLevel; pad = tot - lenErr - lenCodewords; if ((options & PDF417_USE_MACRO) != 0) { // the padding comes before the control block System.arraycopy(codewords, macroIndex, codewords, macroIndex + pad, pad); cwPtr = lenCodewords + pad; while (pad-- != 0) codewords[macroIndex++] = TEXT_MODE; } else { cwPtr = lenCodewords; while (pad-- != 0) codewords[cwPtr++] = TEXT_MODE; } codewords[0] = lenCodewords = cwPtr; calculateErrorCorrection(lenCodewords); lenCodewords = tot; outPaintCode(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeCodabar.java
public static byte[] getBarsCodabar(String text) { text = text.toUpperCase(); int len = text.length(); if (len < 2) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("codabar.must.have.at.least.a.start.and.stop.character")); if (CHARS.indexOf(text.charAt(0)) < START_STOP_IDX || CHARS.indexOf(text.charAt(len - 1)) < START_STOP_IDX) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("codabar.must.have.one.of.abcd.as.start.stop.character")); byte bars[] = new byte[text.length() * 8 - 1]; for (int k = 0; k < len; ++k) { int idx = CHARS.indexOf(text.charAt(k)); if (idx >= START_STOP_IDX && k > 0 && k < len - 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("in.codabar.start.stop.characters.are.only.allowed.at.the.extremes")); if (idx < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.character.1.is.illegal.in.codabar", text.charAt(k))); System.arraycopy(BARS[idx], 0, bars, k * 8, 7); } return bars; }
// 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/cmaps/AbstractCMap.java
void addRange(PdfString from, PdfString to, PdfObject code) { byte[] a1 = decodeStringToByte(from); byte[] a2 = decodeStringToByte(to); if (a1.length != a2.length || a1.length == 0) throw new IllegalArgumentException("Invalid map."); byte[] sout = null; if (code instanceof PdfString) sout = decodeStringToByte((PdfString)code); int start = a1[a1.length - 1] & 0xff; int end = a2[a2.length - 1] & 0xff; for (int k = start; k <= end; ++k) { a1[a1.length - 1] = (byte)k; PdfString s = new PdfString(a1); s.setHexWriting(true); if (code instanceof PdfArray) { addChar(s, ((PdfArray)code).getPdfObject(k - start)); } else if (code instanceof PdfNumber) { int nn = ((PdfNumber)code).intValue() + k - start; addChar(s, new PdfNumber(nn)); } else if (code instanceof PdfString) { PdfString s1 = new PdfString(sout); s1.setHexWriting(true); ++sout[sout.length - 1]; addChar(s, s1); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setWidthPercentage(final float columnWidth[], final Rectangle pageSize) throws DocumentException { if (columnWidth.length != getNumberOfColumns()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); float totalWidth = 0; for (int k = 0; k < columnWidth.length; ++k) totalWidth += columnWidth[k]; widthPercentage = totalWidth / (pageSize.getRight() - pageSize.getLeft()) * 100f; setWidths(columnWidth); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void resetColumnCount(final int newColCount) { if (newColCount <= 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.number.of.columns.in.pdfptable.constructor.must.be.greater.than.zero")); relativeWidths = new float[newColCount]; for (int k = 0; k < newColCount; ++k) relativeWidths[k] = 1; absoluteWidths = new float[relativeWidths.length]; calculateWidths(); currentRow = new PdfPCell[absoluteWidths.length]; totalHeight = 0; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PushbuttonField.java
public void setLayout(int layout) { if (layout < LAYOUT_LABEL_ONLY || layout > LAYOUT_LABEL_OVER_ICON) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("layout.out.of.bounds")); this.layout = layout; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeInter25.java
public static byte[] getBarsInter25(String text) { text = keepNumbers(text); if ((text.length() & 1) != 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.text.length.must.be.even")); byte bars[] = new byte[text.length() * 5 + 7]; int pb = 0; bars[pb++] = 0; bars[pb++] = 0; bars[pb++] = 0; bars[pb++] = 0; int len = text.length() / 2; for (int k = 0; k < len; ++k) { int c1 = text.charAt(k * 2) - '0'; int c2 = text.charAt(k * 2 + 1) - '0'; byte b1[] = BARS[c1]; byte b2[] = BARS[c2]; for (int j = 0; j < 5; ++j) { bars[pb++] = b1[j]; bars[pb++] = b2[j]; } } bars[pb++] = 1; bars[pb++] = 0; bars[pb++] = 0; return bars; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
public void setCode(String code) { if (getCodeType() == Barcode128.CODE128_UCC && code.startsWith("(")) { int idx = 0; StringBuilder ret = new StringBuilder(""); while (idx >= 0) { int end = code.indexOf(')', idx); if (end < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("badly.formed.ucc.string.1", code)); String sai = code.substring(idx + 1, end); if (sai.length() < 2) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("ai.too.short.1", sai)); int ai = Integer.parseInt(sai); int len = ais.get(ai); if (len == 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("ai.not.found.1", sai)); sai = String.valueOf(ai); if (sai.length() == 1) sai = "0" + sai; idx = code.indexOf('(', end); int next = (idx < 0 ? code.length() : idx); ret.append(sai).append(code.substring(end + 1, next)); if (len < 0) { if (idx >= 0) ret.append(FNC1); } else if (next - end - 1 + sai.length() != len) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.ai.length.1", sai)); } super.setCode(ret.toString()); } else super.setCode(code); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfShading.java
public static void throwColorSpaceError() { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("a.tiling.or.shading.pattern.cannot.be.used.as.a.color.space.in.a.shading.pattern")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfShading.java
public static void checkCompatibleColors(BaseColor c1, BaseColor c2) { int type1 = ExtendedColor.getType(c1); int type2 = ExtendedColor.getType(c2); if (type1 != type2) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("both.colors.must.be.of.the.same.type")); if (type1 == ExtendedColor.TYPE_SEPARATION && ((SpotColor)c1).getPdfSpotColor() != ((SpotColor)c2).getPdfSpotColor()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.spot.color.must.be.the.same.only.the.tint.can.vary")); if (type1 == ExtendedColor.TYPE_PATTERN || type1 == ExtendedColor.TYPE_SHADING) throwColorSpaceError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfShading.java
public void setBBox(float[] bBox) { if (bBox.length != 4) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bbox.must.be.a.4.element.array")); this.bBox = bBox; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public void setCryptoMode(int mode, int kl) { cryptoMode = mode; encryptMetadata = (mode & PdfWriter.DO_NOT_ENCRYPT_METADATA) != PdfWriter.DO_NOT_ENCRYPT_METADATA; embeddedFilesOnly = (mode & PdfWriter.EMBEDDED_FILES_ONLY) == PdfWriter.EMBEDDED_FILES_ONLY; mode &= PdfWriter.ENCRYPTION_MASK; switch (mode) { case PdfWriter.STANDARD_ENCRYPTION_40: encryptMetadata = true; embeddedFilesOnly = false; keyLength = 40; revision = STANDARD_ENCRYPTION_40; break; case PdfWriter.STANDARD_ENCRYPTION_128: embeddedFilesOnly = false; if (kl > 0) keyLength = kl; else keyLength = 128; revision = STANDARD_ENCRYPTION_128; break; case PdfWriter.ENCRYPTION_AES_128: keyLength = 128; revision = AES_128; break; case PdfWriter.ENCRYPTION_AES_256: keyLength = 256; keySize = 32; revision = AES_256; break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("no.valid.encryption.mode")); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPageLabels.java
public void addPageLabel(int page, int numberStyle, String text, int firstPage) { if (page < 1 || firstPage < 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("in.a.page.label.the.page.numbers.must.be.greater.or.equal.to.1")); PdfDictionary dic = new PdfDictionary(); if (numberStyle >= 0 && numberStyle < numberingStyle.length) dic.put(PdfName.S, numberingStyle[numberStyle]); if (text != null) dic.put(PdfName.P, new PdfString(text, PdfObject.TEXT_UNICODE)); if (firstPage != 1) dic.put(PdfName.ST, new PdfNumber(firstPage)); map.put(Integer.valueOf(page - 1), dic); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BidiOrder.java
private static void validateTypes(byte[] types) { if (types == null) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("types.is.null")); } for (int i = 0; i < types.length; ++i) { if (types[i] < TYPE_MIN || types[i] > TYPE_MAX) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.type.value.at.1.2", String.valueOf(i), String.valueOf(types[i]))); } } for (int i = 0; i < types.length - 1; ++i) { if (types[i] == B) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("b.type.before.end.of.paragraph.at.index.1", i)); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BidiOrder.java
private static void validateParagraphEmbeddingLevel(byte paragraphEmbeddingLevel) { if (paragraphEmbeddingLevel != -1 && paragraphEmbeddingLevel != 0 && paragraphEmbeddingLevel != 1) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.paragraph.embedding.level.1", paragraphEmbeddingLevel)); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BidiOrder.java
private static void validateLineBreaks(int[] linebreaks, int textLength) { int prev = 0; for (int i = 0; i < linebreaks.length; ++i) { int next = linebreaks[i]; if (next <= prev) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bad.linebreak.1.at.index.2", String.valueOf(next), String.valueOf(i))); } prev = next; } if (prev != textLength) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("last.linebreak.must.be.at.1", textLength)); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/BaseColor.java
private static void validate(final int value) { if (value < 0 || value > 255) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("color.value.outside.range.0.255")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/WebColors.java
public static BaseColor getRGBColor(String name) throws IllegalArgumentException { int[] c = { 0, 0, 0, 255 }; name = name.toLowerCase(); boolean colorStrWithoutHash = missingHashColorFormat(name); if (name.startsWith("#") || colorStrWithoutHash) { if (!colorStrWithoutHash) { name = name.substring(1); // lop off the # to unify hex parsing. } if (name.length() == 3) { String s = name.substring(0, 1); c[0] = Integer.parseInt(s+s, 16); String s2 = name.substring(1, 2); c[1] = Integer.parseInt(s2+s2, 16); String s3 = name.substring(2); c[2] = Integer.parseInt(s3+s3, 16); return new BaseColor(c[0], c[1], c[2], c[3]); } if (name.length() == 6) { c[0] = Integer.parseInt(name.substring(0, 2), 16); c[1] = Integer.parseInt(name.substring(2, 4), 16); c[2] = Integer.parseInt(name.substring(4), 16); return new BaseColor(c[0], c[1], c[2], c[3]); } throw new IllegalArgumentException(MessageLocalization.getComposedMessage("unknown.color.format.must.be.rgb.or.rrggbb")); } else if (name.startsWith("rgb(")) { StringTokenizer tok = new StringTokenizer(name, "rgb(), \t\r\n\f"); for (int k = 0; k < 3; ++k) { String v = tok.nextToken(); if (v.endsWith("%")) c[k] = Integer.parseInt(v.substring(0, v.length() - 1)) * 255 / 100; else c[k] = Integer.parseInt(v); if (c[k] < 0) c[k] = 0; else if (c[k] > 255) c[k] = 255; } return new BaseColor(c[0], c[1], c[2], c[3]); } if (!NAMES.containsKey(name)) // TODO localize this error message. throw new IllegalArgumentException("Color '" + name + "' not found."); c = NAMES.get(name); return new BaseColor(c[0], c[1], c[2], c[3]); }
3
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { throw new IllegalArgumentException(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
catch (ClassCastException ex) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.to.consolidate.the.named.destinations.of.your.reader")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (IOException e) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object")); }
1
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/WebColors.java
public static BaseColor getRGBColor(String name) throws IllegalArgumentException { int[] c = { 0, 0, 0, 255 }; name = name.toLowerCase(); boolean colorStrWithoutHash = missingHashColorFormat(name); if (name.startsWith("#") || colorStrWithoutHash) { if (!colorStrWithoutHash) { name = name.substring(1); // lop off the # to unify hex parsing. } if (name.length() == 3) { String s = name.substring(0, 1); c[0] = Integer.parseInt(s+s, 16); String s2 = name.substring(1, 2); c[1] = Integer.parseInt(s2+s2, 16); String s3 = name.substring(2); c[2] = Integer.parseInt(s3+s3, 16); return new BaseColor(c[0], c[1], c[2], c[3]); } if (name.length() == 6) { c[0] = Integer.parseInt(name.substring(0, 2), 16); c[1] = Integer.parseInt(name.substring(2, 4), 16); c[2] = Integer.parseInt(name.substring(4), 16); return new BaseColor(c[0], c[1], c[2], c[3]); } throw new IllegalArgumentException(MessageLocalization.getComposedMessage("unknown.color.format.must.be.rgb.or.rrggbb")); } else if (name.startsWith("rgb(")) { StringTokenizer tok = new StringTokenizer(name, "rgb(), \t\r\n\f"); for (int k = 0; k < 3; ++k) { String v = tok.nextToken(); if (v.endsWith("%")) c[k] = Integer.parseInt(v.substring(0, v.length() - 1)) * 255 / 100; else c[k] = Integer.parseInt(v); if (c[k] < 0) c[k] = 0; else if (c[k] > 255) c[k] = 255; } return new BaseColor(c[0], c[1], c[2], c[3]); } if (!NAMES.containsKey(name)) // TODO localize this error message. throw new IllegalArgumentException("Color '" + name + "' not found."); c = NAMES.get(name); return new BaseColor(c[0], c[1], c[2], c[3]); }
(Domain) ExceptionConverter 161
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/DefaultFontMapper.java
public BaseFont awtToPdf(Font font) { try { BaseFontParameters p = getBaseFontParameters(font.getFontName()); if (p != null) return BaseFont.createFont(p.fontName, p.encoding, p.embedded, p.cached, p.ttfAfm, p.pfb); String fontKey = null; String logicalName = font.getName(); if (logicalName.equalsIgnoreCase("DialogInput") || logicalName.equalsIgnoreCase("Monospaced") || logicalName.equalsIgnoreCase("Courier")) { if (font.isItalic()) { if (font.isBold()) { fontKey = BaseFont.COURIER_BOLDOBLIQUE; } else { fontKey = BaseFont.COURIER_OBLIQUE; } } else { if (font.isBold()) { fontKey = BaseFont.COURIER_BOLD; } else { fontKey = BaseFont.COURIER; } } } else if (logicalName.equalsIgnoreCase("Serif") || logicalName.equalsIgnoreCase("TimesRoman")) { if (font.isItalic()) { if (font.isBold()) { fontKey = BaseFont.TIMES_BOLDITALIC; } else { fontKey = BaseFont.TIMES_ITALIC; } } else { if (font.isBold()) { fontKey = BaseFont.TIMES_BOLD; } else { fontKey = BaseFont.TIMES_ROMAN; } } } else { // default, this catches Dialog and SansSerif if (font.isItalic()) { if (font.isBold()) { fontKey = BaseFont.HELVETICA_BOLDOBLIQUE; } else { fontKey = BaseFont.HELVETICA_OBLIQUE; } } else { if (font.isBold()) { fontKey = BaseFont.HELVETICA_BOLD; } else { fontKey = BaseFont.HELVETICA; } } } return BaseFont.createFont(fontKey, BaseFont.CP1252, false); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final Image image) { if (image == null) return null; try { Class<? extends Image> cs = image.getClass(); Constructor<? extends Image> constructor = cs .getDeclaredConstructor(new Class[] { Image.class }); return constructor.newInstance(new Object[] { image }); } catch (Exception e) { throw new ExceptionConverter(e); } }
// 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/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
private void read24Bit(byte[] bdata) { // Padding bytes at the end of each scanline int padding = 0; // width * bitsPerPixel should be divisible by 32 int bitsPerScanline = width * 24; if ( bitsPerScanline%32 != 0) { padding = (bitsPerScanline/32 + 1)*32 - bitsPerScanline; padding = (int)Math.ceil(padding/8.0); } int imSize = (width * 3 + 3) / 4 * 4 * height; // Read till we have the whole image byte values[] = new byte[imSize]; try { int bytesRead = 0; while (bytesRead < imSize) { int r = inputStream.read(values, bytesRead, imSize - bytesRead); if (r < 0) break; bytesRead += r; } } catch (IOException ioe) { throw new ExceptionConverter(ioe); } int l=0, count; if (isBottomUp) { int max = width*height*3-1; count = -padding; for (int i=0; i<height; i++) { l = max - (i+1)*width*3 + 1; count += padding; for (int j=0; j<width; j++) { bdata[l + 2] = values[count++]; bdata[l + 1] = values[count++]; bdata[l] = values[count++]; l += 3; } } } else { count = -padding; for (int i=0; i<height; i++) { count += padding; for (int j=0; j<width; j++) { bdata[l + 2] = values[count++]; bdata[l + 1] = values[count++]; bdata[l] = values[count++]; l += 3; } } } }
// 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/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/JBIG2Image.java
public static Image getJbig2Image(RandomAccessFileOrArray ra, int page) { if (page < 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.page.number.must.be.gt.eq.1")); try { JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.read(); JBIG2SegmentReader.JBIG2Page p = sr.getPage(page); Image img = new ImgJBIG2(p.pageBitmapWidth, p.pageBitmapHeight, p.getData(true), sr.getGlobal(true)); return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
public static int getNumberOfPages(RandomAccessFileOrArray ra) { try { JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.read(); return sr.numberOfPages(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
public BaseFont getFont() { if (font != null) return font; Font ff2 = FontFactory.getFont(faceName, BaseFont.CP1252, true, 10, ((italic != 0) ? Font.ITALIC : 0) | ((bold != 0) ? Font.BOLD : 0)); font = ff2.getBaseFont(); if (font != null) return font; String fontName; if (faceName.indexOf("courier") != -1 || faceName.indexOf("terminal") != -1 || faceName.indexOf("fixedsys") != -1) { fontName = fontNames[MARKER_COURIER + italic + bold]; } else if (faceName.indexOf("ms sans serif") != -1 || faceName.indexOf("arial") != -1 || faceName.indexOf("system") != -1) { fontName = fontNames[MARKER_HELVETICA + italic + bold]; } else if (faceName.indexOf("arial black") != -1) { fontName = fontNames[MARKER_HELVETICA + italic + MARKER_BOLD]; } else if (faceName.indexOf("times") != -1 || faceName.indexOf("ms serif") != -1 || faceName.indexOf("roman") != -1) { fontName = fontNames[MARKER_TIMES + italic + bold]; } else if (faceName.indexOf("symbol") != -1) { fontName = fontNames[MARKER_SYMBOL]; } else { int pitch = pitchAndFamily & 3; int family = (pitchAndFamily >> 4) & 7; switch (family) { case FF_MODERN: fontName = fontNames[MARKER_COURIER + italic + bold]; break; case FF_ROMAN: fontName = fontNames[MARKER_TIMES + italic + bold]; break; case FF_SWISS: case FF_SCRIPT: case FF_DECORATIVE: fontName = fontNames[MARKER_HELVETICA + italic + bold]; break; default: { switch (pitch) { case FIXED_PITCH: fontName = fontNames[MARKER_COURIER + italic + bold]; break; default: fontName = fontNames[MARKER_HELVETICA + italic + bold]; break; } } } } try { font = BaseFont.createFont(fontName, "Cp1252", false); } catch (Exception e) { throw new ExceptionConverter(e); } return font; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
public static int getNumberOfPages(RandomAccessFileOrArray s) { try { return TIFFDirectory.getNumDirectories(s); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
public static Image getTiffImage(RandomAccessFileOrArray s, int page, boolean direct) { if (page < 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.page.number.must.be.gt.eq.1")); try { TIFFDirectory dir = new TIFFDirectory(s, page - 1); if (dir.isTagPresent(TIFFConstants.TIFFTAG_TILEWIDTH)) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("tiles.are.not.supported")); int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: case TIFFConstants.COMPRESSION_CCITTFAX3: case TIFFConstants.COMPRESSION_CCITTFAX4: break; default: return getTiffImageColor(dir, s); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } Image img = null; long tiffT4Options = 0; long tiffT6Options = 0; int fillOrder = 1; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; float XYRatio = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); if (resolutionUnit == TIFFConstants.RESUNIT_NONE) { if (dpiY != 0) XYRatio = (float)dpiX / (float)dpiY; dpiX = 0; dpiY = 0; } int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int params = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_PHOTOMETRIC)) { long photo = dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); if (photo == TIFFConstants.PHOTOMETRIC_MINISBLACK) params |= Image.CCITT_BLACKIS1; } int imagecomp = 0; switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: imagecomp = Image.CCITTG3_1D; params |= Image.CCITT_ENCODEDBYTEALIGN | Image.CCITT_ENDOFBLOCK; break; case TIFFConstants.COMPRESSION_CCITTFAX3: imagecomp = Image.CCITTG3_1D; params |= Image.CCITT_ENDOFLINE | Image.CCITT_ENDOFBLOCK; TIFFField t4OptionsField = dir.getField(TIFFConstants.TIFFTAG_GROUP3OPTIONS); if (t4OptionsField != null) { tiffT4Options = t4OptionsField.getAsLong(0); if ((tiffT4Options & TIFFConstants.GROUP3OPT_2DENCODING) != 0) imagecomp = Image.CCITTG3_2D; if ((tiffT4Options & TIFFConstants.GROUP3OPT_FILLBITS) != 0) params |= Image.CCITT_ENCODEDBYTEALIGN; } break; case TIFFConstants.COMPRESSION_CCITTFAX4: imagecomp = Image.CCITTG4; TIFFField t6OptionsField = dir.getField(TIFFConstants.TIFFTAG_GROUP4OPTIONS); if (t6OptionsField != null) tiffT6Options = t6OptionsField.getAsLong(0); break; } if (direct && rowsStrip == h) { //single strip, direct byte im[] = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(im); img = Image.getInstance(w, h, false, imagecomp, params, im); img.setInverted(true); } else { int rowsLeft = h; CCITTG4Encoder g4 = new CCITTG4Encoder(w); for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); TIFFFaxDecoder decoder = new TIFFFaxDecoder(fillOrder, w, height); byte outBuf[] = new byte[(w + 7) / 8 * height]; switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: decoder.decode1D(outBuf, im, 0, height); g4.fax4Encode(outBuf,height); break; case TIFFConstants.COMPRESSION_CCITTFAX3: try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e) { // let's flip the fill bits and try again... tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS; try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e2) { throw e; } } g4.fax4Encode(outBuf, height); break; case TIFFConstants.COMPRESSION_CCITTFAX4: decoder.decodeT6(outBuf, im, 0, height, tiffT6Options); g4.fax4Encode(outBuf, height); break; } rowsLeft -= rowsStrip; } byte g4pic[] = g4.close(); img = Image.getInstance(w, h, false, Image.CCITTG4, params & Image.CCITT_BLACKIS1, g4pic); } img.setDpi(dpiX, dpiY); img.setXYRatio(XYRatio); if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (icc_prof.getNumComponents() == 1) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } img.setOriginalType(Image.ORIGINAL_TIFF); if (rotation != 0) img.setInitialRotation(rotation); return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
protected static Image getTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s) { try { int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); int predictor = 1; TIFFLZWDecoder lzwDecoder = null; switch (compression) { case TIFFConstants.COMPRESSION_NONE: case TIFFConstants.COMPRESSION_LZW: case TIFFConstants.COMPRESSION_PACKBITS: case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: case TIFFConstants.COMPRESSION_OJPEG: case TIFFConstants.COMPRESSION_JPEG: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.compression.1.is.not.supported", compression)); } int photometric = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); switch (photometric) { case TIFFConstants.PHOTOMETRIC_MINISWHITE: case TIFFConstants.PHOTOMETRIC_MINISBLACK: case TIFFConstants.PHOTOMETRIC_RGB: case TIFFConstants.PHOTOMETRIC_SEPARATED: case TIFFConstants.PHOTOMETRIC_PALETTE: break; default: if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.photometric.1.is.not.supported", photometric)); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } if (dir.isTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) && dir.getFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("planar.images.are.not.supported")); int extraSamples = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES)) extraSamples = 1; int samplePerPixel = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4 samplePerPixel = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL); int bitsPerSample = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE)) bitsPerSample = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE); switch (bitsPerSample) { case 1: case 2: case 4: case 8: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample)); } Image img = null; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); int fillOrder = 1; boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE) { TIFFField predictorField = dir.getField(TIFFConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.getAsInt(0); if (predictor != 1 && predictor != 2) { throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.value.for.predictor.in.tiff.file")); } if (predictor == 2 && bitsPerSample != 8) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample)); } } } if (compression == TIFFConstants.COMPRESSION_LZW) { lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel); } int rowsLeft = h; ByteArrayOutputStream stream = null; ByteArrayOutputStream mstream = null; DeflaterOutputStream zip = null; DeflaterOutputStream mzip = null; if (extraSamples > 0) { mstream = new ByteArrayOutputStream(); mzip = new DeflaterOutputStream(mstream); } CCITTG4Encoder g4 = null; if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4 = new CCITTG4Encoder(w); } else { stream = new ByteArrayOutputStream(); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) zip = new DeflaterOutputStream(stream); } if (compression == TIFFConstants.COMPRESSION_OJPEG) { // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and // is often missing if ((!dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET))) { throw new IOException(MessageLocalization.getComposedMessage("missing.tag.s.for.ojpeg.compression")); } int jpegOffset = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET); int jpegLength = (int)s.length() - jpegOffset; if (dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT)) { jpegLength = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0]; } byte[] jpeg = new byte[Math.min(jpegLength, (int)s.length() - jpegOffset)]; int posFilePointer = (int)s.getFilePointer(); posFilePointer += jpegOffset; s.seek(posFilePointer); s.readFully(jpeg); img = new Jpeg(jpeg); } else if (compression == TIFFConstants.COMPRESSION_JPEG) { if (size.length > 1) throw new IOException(MessageLocalization.getComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.length)); byte[] jpeg = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(jpeg); // if quantization and/or Huffman tables are stored separately in the tiff, // we need to add them to the jpeg data TIFFField jpegtables = dir.getField(TIFFConstants.TIFFTAG_JPEGTABLES); if (jpegtables != null) { byte[] temp = jpegtables.getAsBytes(); int tableoffset = 0; int tablelength = temp.length; // remove FFD8 from start if (temp[0] == (byte) 0xFF && temp[1] == (byte) 0xD8) { tableoffset = 2; tablelength -= 2; } // remove FFD9 from end if (temp[temp.length-2] == (byte) 0xFF && temp[temp.length-1] == (byte) 0xD9) tablelength -= 2; byte[] tables = new byte[tablelength]; System.arraycopy(temp, tableoffset, tables, 0, tablelength); // TODO insert after JFIF header, instead of at the start byte[] jpegwithtables = new byte[jpeg.length + tables.length]; System.arraycopy(jpeg, 0, jpegwithtables, 0, 2); System.arraycopy(tables, 0, jpegwithtables, 2, tables.length); System.arraycopy(jpeg, 2, jpegwithtables, tables.length+2, jpeg.length-2); jpeg = jpegwithtables; } img = new Jpeg(jpeg); } else { for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); byte outBuf[] = null; if (compression != TIFFConstants.COMPRESSION_NONE) outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height]; if (reverse) TIFFFaxDecoder.reverseBits(im); switch (compression) { case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: inflate(im, outBuf); applyPredictor(outBuf, predictor, w, height, samplePerPixel); break; case TIFFConstants.COMPRESSION_NONE: outBuf = im; break; case TIFFConstants.COMPRESSION_PACKBITS: decodePackbits(im, outBuf); break; case TIFFConstants.COMPRESSION_LZW: lzwDecoder.decode(im, outBuf, height); break; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4.fax4Encode(outBuf, height); } else { if (extraSamples > 0) ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height); else zip.write(outBuf); } rowsLeft -= rowsStrip; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { img = Image.getInstance(w, h, false, Image.CCITTG4, photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.close()); } else { zip.close(); img = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.toByteArray()); img.setDeflated(true); } } img.setDpi(dpiX, dpiY); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) { if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (samplePerPixel - extraSamples == icc_prof.getNumComponents()) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } if (dir.isTagPresent(TIFFConstants.TIFFTAG_COLORMAP)) { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_COLORMAP); char rgb[] = fd.getAsChars(); byte palette[] = new byte[rgb.length]; int gColor = rgb.length / 3; int bColor = gColor * 2; for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)(rgb[k] >>> 8); palette[k * 3 + 1] = (byte)(rgb[k + gColor] >>> 8); palette[k * 3 + 2] = (byte)(rgb[k + bColor] >>> 8); } // Colormap components are supposed to go from 0 to 655535 but, // as usually, some tiff producers just put values from 0 to 255. // Let's check for these broken tiffs. boolean colormapBroken = true; for (int k = 0; k < palette.length; ++k) { if (palette[k] != 0) { colormapBroken = false; break; } } if (colormapBroken) { for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)rgb[k]; palette[k * 3 + 1] = (byte)rgb[k + gColor]; palette[k * 3 + 2] = (byte)rgb[k + bColor]; } } PdfArray indexed = new PdfArray(); indexed.add(PdfName.INDEXED); indexed.add(PdfName.DEVICERGB); indexed.add(new PdfNumber(gColor - 1)); indexed.add(new PdfString(palette)); PdfDictionary additional = new PdfDictionary(); additional.put(PdfName.COLORSPACE, indexed); img.setAdditional(additional); } img.setOriginalType(Image.ORIGINAL_TIFF); } if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE) img.setInverted(true); if (rotation != 0) img.setInitialRotation(rotation); if (extraSamples > 0) { mzip.close(); Image mimg = Image.getInstance(w, h, 1, bitsPerSample, mstream.toByteArray()); mimg.makeMask(); mimg.setDeflated(true); img.setImageMask(mimg); } return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
public static void inflate(byte[] deflated, byte[] inflated) { Inflater inflater = new Inflater(); inflater.setInput(deflated); try { inflater.inflate(inflated); } catch(DataFormatException dfe) { throw new ExceptionConverter(dfe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
private void init() { encoding = ""; fontSpecific = false; fontType = FONT_TYPE_DOCUMENT; PdfName baseFont = font.getAsName(PdfName.BASEFONT); fontName = baseFont != null ? PdfName.decodeName(baseFont.toString()) : "Unspecified Font Name"; PdfName subType = font.getAsName(PdfName.SUBTYPE); if (PdfName.TYPE1.equals(subType) || PdfName.TRUETYPE.equals(subType)) doType1TT(); else { PdfName encodingName = font.getAsName(PdfName.ENCODING); if (encodingName != null){ String enc = PdfName.decodeName(encodingName.toString()); String ffontname = CJKFont.GetCompatibleFont(enc); if (ffontname != null) { try { cjkMirror = BaseFont.createFont(ffontname, enc, false); } catch (Exception e) { throw new ExceptionConverter(e); } cjkEncoding = enc; uniMap = ((CJKFont)cjkMirror).getUniMap(); return; } if (PdfName.TYPE0.equals(subType) && enc.equals("Identity-H")) { processType0(font); isType0 = true; } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
private void processType0(PdfDictionary font) { try { PdfObject toUniObject = PdfReader.getPdfObjectRelease(font.get(PdfName.TOUNICODE)); PdfArray df = (PdfArray)PdfReader.getPdfObjectRelease(font.get(PdfName.DESCENDANTFONTS)); PdfDictionary cidft = (PdfDictionary)PdfReader.getPdfObjectRelease(df.getPdfObject(0)); PdfNumber dwo = (PdfNumber)PdfReader.getPdfObjectRelease(cidft.get(PdfName.DW)); int dw = 1000; if (dwo != null) dw = dwo.intValue(); IntHashtable widths = readWidths((PdfArray)PdfReader.getPdfObjectRelease(cidft.get(PdfName.W))); PdfDictionary fontDesc = (PdfDictionary)PdfReader.getPdfObjectRelease(cidft.get(PdfName.FONTDESCRIPTOR)); fillFontDesc(fontDesc); if (toUniObject instanceof PRStream){ fillMetrics(PdfReader.getStreamBytes((PRStream)toUniObject), widths, dw); } } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
private void fillMetrics(byte[] touni, IntHashtable widths, int dw) { try { PdfContentParser ps = new PdfContentParser(new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(touni)))); PdfObject ob = null; boolean notFound = true; int nestLevel = 0; int maxExc = 50; while ((notFound || nestLevel > 0)) { try { ob = ps.readPRObject(); } catch (Exception ex) { if (--maxExc < 0) break; continue; } if (ob == null) break; if (ob.type() == PdfContentParser.COMMAND_TYPE) { if (ob.toString().equals("begin")) { notFound = false; nestLevel++; } else if (ob.toString().equals("end")) { nestLevel--; } else if (ob.toString().equals("beginbfchar")) { while (true) { PdfObject nx = ps.readPRObject(); if (nx.toString().equals("endbfchar")) break; String cid = decodeString((PdfString)nx); String uni = decodeString((PdfString)ps.readPRObject()); if (uni.length() == 1) { int cidc = cid.charAt(0); int unic = uni.charAt(uni.length() - 1); int w = dw; if (widths.containsKey(cidc)) w = widths.get(cidc); metrics.put(Integer.valueOf(unic), new int[]{cidc, w}); } } } else if (ob.toString().equals("beginbfrange")) { while (true) { PdfObject nx = ps.readPRObject(); if (nx.toString().equals("endbfrange")) break; String cid1 = decodeString((PdfString)nx); String cid2 = decodeString((PdfString)ps.readPRObject()); int cid1c = cid1.charAt(0); int cid2c = cid2.charAt(0); PdfObject ob2 = ps.readPRObject(); if (ob2.isString()) { String uni = decodeString((PdfString)ob2); if (uni.length() == 1) { int unic = uni.charAt(uni.length() - 1); for (; cid1c <= cid2c; cid1c++, unic++) { int w = dw; if (widths.containsKey(cid1c)) w = widths.get(cid1c); metrics.put(Integer.valueOf(unic), new int[]{cid1c, w}); } } } else { PdfArray a = (PdfArray)ob2; for (int j = 0; j < a.size(); ++j, ++cid1c) { String uni = decodeString(a.getAsString(j)); if (uni.length() == 1) { int unic = uni.charAt(uni.length() - 1); int w = dw; if (widths.containsKey(cid1c)) w = widths.get(cid1c); metrics.put(Integer.valueOf(unic), new int[]{cid1c, w}); } } } } } } } } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
private void doType1TT() { CMapToUnicode toUnicode = null; PdfObject enc = PdfReader.getPdfObject(font.get(PdfName.ENCODING)); if (enc == null) { fillEncoding(null); try { toUnicode = processToUnicode(); if (toUnicode != null) { Map<Integer, Integer> rm = toUnicode.createReverseMapping(); for (Map.Entry<Integer, Integer> kv : rm.entrySet()) { uni2byte.put(kv.getKey().intValue(), kv.getValue().intValue()); byte2uni.put(kv.getValue().intValue(), kv.getKey().intValue()); } } } catch (Exception ex) { throw new ExceptionConverter(ex); } } else { if (enc.isName()) fillEncoding((PdfName)enc); else if (enc.isDictionary()) { PdfDictionary encDic = (PdfDictionary)enc; enc = PdfReader.getPdfObject(encDic.get(PdfName.BASEENCODING)); if (enc == null) fillEncoding(null); else fillEncoding((PdfName)enc); PdfArray diffs = encDic.getAsArray(PdfName.DIFFERENCES); if (diffs != null) { diffmap = new IntHashtable(); int currentNumber = 0; for (int k = 0; k < diffs.size(); ++k) { PdfObject obj = diffs.getPdfObject(k); if (obj.isNumber()) currentNumber = ((PdfNumber)obj).intValue(); else { int c[] = GlyphList.nameToUnicode(PdfName.decodeName(((PdfName)obj).toString())); if (c != null && c.length > 0) { uni2byte.put(c[0], currentNumber); byte2uni.put(currentNumber, c[0]); diffmap.put(c[0], currentNumber); } else { if (toUnicode == null) { toUnicode = processToUnicode(); if (toUnicode == null) { toUnicode = new CMapToUnicode(); } } final String unicode = toUnicode.lookup(new byte[]{(byte) currentNumber}, 0, 1); if ((unicode != null) && (unicode.length() == 1)) { this.uni2byte.put(unicode.charAt(0), currentNumber); this.byte2uni.put(currentNumber, unicode.charAt(0)); this.diffmap.put(unicode.charAt(0), currentNumber); } } ++currentNumber; } } } } } PdfArray newWidths = font.getAsArray(PdfName.WIDTHS); PdfNumber first = font.getAsNumber(PdfName.FIRSTCHAR); PdfNumber last = font.getAsNumber(PdfName.LASTCHAR); if (BuiltinFonts14.containsKey(fontName)) { BaseFont bf; try { bf = BaseFont.createFont(fontName, WINANSI, false); } catch (Exception e) { throw new ExceptionConverter(e); } int e[] = uni2byte.toOrderedKeys(); for (int k = 0; k < e.length; ++k) { updateWidths(e[k], bf); } if (diffmap != null) { //widths for diffmap must override existing ones e = diffmap.toOrderedKeys(); for (int k = 0; k < e.length; ++k) { updateWidths(e[k], bf); } diffmap = null; } ascender = bf.getFontDescriptor(ASCENT, 1000); capHeight = bf.getFontDescriptor(CAPHEIGHT, 1000); descender = bf.getFontDescriptor(DESCENT, 1000); italicAngle = bf.getFontDescriptor(ITALICANGLE, 1000); fontWeight = bf.getFontDescriptor(FONT_WEIGHT, 1000); llx = bf.getFontDescriptor(BBOXLLX, 1000); lly = bf.getFontDescriptor(BBOXLLY, 1000); urx = bf.getFontDescriptor(BBOXURX, 1000); ury = bf.getFontDescriptor(BBOXURY, 1000); } if (first != null && last != null && newWidths != null) { int f = first.intValue(); int nSize = f + newWidths.size(); if (widths.length < nSize) { int[] tmp = new int[nSize]; System.arraycopy(widths, 0, tmp, 0, f); widths = tmp; } for (int k = 0; k < newWidths.size(); ++k) { widths[f + k] = newWidths.getAsNumber(k).intValue(); } } fillFontDesc(font.getAsDict(PdfName.FONTDESCRIPTOR)); }
// 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/hyphenation/SimplePatternParser.java
public void parse(InputStream stream, PatternConsumer consumer) { this.consumer = consumer; try { SimpleXMLParser.parse(this, stream); } catch (IOException e) { throw new ExceptionConverter(e); } finally { try { stream.close(); } catch (Exception e) { } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public static void showTextAligned(final PdfContentByte canvas, int alignment, final Phrase phrase, final float x, final float y, final float rotation, final int runDirection, final int arabicOptions) { if (alignment != Element.ALIGN_LEFT && alignment != Element.ALIGN_CENTER && alignment != Element.ALIGN_RIGHT) alignment = Element.ALIGN_LEFT; canvas.saveState(); ColumnText ct = new ColumnText(canvas); float lly = -1; float ury = 2; float llx; float urx; switch (alignment) { case Element.ALIGN_LEFT: llx = 0; urx = 20000; break; case Element.ALIGN_RIGHT: llx = -20000; urx = 0; break; default: llx = -20000; urx = 20000; break; } if (rotation == 0) { llx += x; lly += y; urx += x; ury += y; } else { double alpha = rotation * Math.PI / 180.0; float cos = (float)Math.cos(alpha); float sin = (float)Math.sin(alpha); canvas.concatCTM(cos, sin, -sin, cos, x, y); } ct.setSimpleColumn(phrase, llx, lly, urx, ury, 2, alignment); if (runDirection == PdfWriter.RUN_DIRECTION_RTL) { if (alignment == Element.ALIGN_LEFT) alignment = Element.ALIGN_RIGHT; else if (alignment == Element.ALIGN_RIGHT) alignment = Element.ALIGN_LEFT; } ct.setAlignment(alignment); ct.setArabicOptions(arabicOptions); ct.setRunDirection(runDirection); try { ct.go(); } catch (DocumentException e) { throw new ExceptionConverter(e); } canvas.restoreState(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public static float fitText(Font font, String text, Rectangle rect, float maxFontSize, int runDirection) { try { ColumnText ct = null; int status = 0; if (maxFontSize <= 0) { int cr = 0; int lf = 0; char t[] = text.toCharArray(); for (int k = 0; k < t.length; ++k) { if (t[k] == '\n') ++lf; else if (t[k] == '\r') ++cr; } int minLines = Math.max(cr, lf) + 1; maxFontSize = Math.abs(rect.getHeight()) / minLines - 0.001f; } font.setSize(maxFontSize); Phrase ph = new Phrase(text, font); ct = new ColumnText(null); ct.setSimpleColumn(ph, rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop(), maxFontSize, Element.ALIGN_LEFT); ct.setRunDirection(runDirection); status = ct.go(true); if ((status & NO_MORE_TEXT) != 0) return maxFontSize; float precision = 0.1f; float min = 0; float max = maxFontSize; float size = maxFontSize; for (int k = 0; k < 50; ++k) { //just in case it doesn't converge size = (min + max) / 2; ct = new ColumnText(null); font.setSize(size); ct.setSimpleColumn(new Phrase(text, font), rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop(), size, Element.ALIGN_LEFT); ct.setRunDirection(runDirection); status = ct.go(true); if ((status & NO_MORE_TEXT) != 0) { if (max - min < size * precision) return size; min = size; } else max = size; } return size; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public static Object[] splitDAelements(String da) { try { PRTokeniser tk = new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(PdfEncodings.convertToBytes(da, null)))); ArrayList<String> stack = new ArrayList<String>(); Object ret[] = new Object[3]; while (tk.nextToken()) { if (tk.getTokenType() == TokenType.COMMENT) continue; if (tk.getTokenType() == TokenType.OTHER) { String operator = tk.getStringValue(); if (operator.equals("Tf")) { if (stack.size() >= 2) { ret[DA_FONT] = stack.get(stack.size() - 2); ret[DA_SIZE] = new Float(stack.get(stack.size() - 1)); } } else if (operator.equals("g")) { if (stack.size() >= 1) { float gray = new Float(stack.get(stack.size() - 1)).floatValue(); if (gray != 0) ret[DA_COLOR] = new GrayColor(gray); } } else if (operator.equals("rg")) { if (stack.size() >= 3) { float red = new Float(stack.get(stack.size() - 3)).floatValue(); float green = new Float(stack.get(stack.size() - 2)).floatValue(); float blue = new Float(stack.get(stack.size() - 1)).floatValue(); ret[DA_COLOR] = new BaseColor(red, green, blue); } } else if (operator.equals("k")) { if (stack.size() >= 4) { float cyan = new Float(stack.get(stack.size() - 4)).floatValue(); float magenta = new Float(stack.get(stack.size() - 3)).floatValue(); float yellow = new Float(stack.get(stack.size() - 2)).floatValue(); float black = new Float(stack.get(stack.size() - 1)).floatValue(); ret[DA_COLOR] = new CMYKColor(cyan, magenta, yellow, black); } } stack.clear(); } else stack.add(tk.getStringValue()); } return ret; } catch (IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public String getField(String name) { if (xfa.isXfaPresent()) { name = xfa.findFieldName(name, this); if (name == null) return null; name = XfaForm.Xml2Som.getShortName(name); return XfaForm.getNodeText(xfa.findDatasetsNode(name)); } Item item = fields.get(name); if (item == null) return null; lastWasString = false; PdfDictionary mergedDict = item.getMerged( 0 ); // Jose A. Rodriguez posted a fix to the mailing list (May 11, 2009) // explaining that the value can also be a stream value // the fix was made against an old iText version. Bruno adapted it. PdfObject v = PdfReader.getPdfObject(mergedDict.get(PdfName.V)); if (v == null) return ""; if (v instanceof PRStream) { byte[] valBytes; try { valBytes = PdfReader.getStreamBytes((PRStream)v); return new String(valBytes); } catch (IOException e) { throw new ExceptionConverter(e); } } PdfName type = mergedDict.getAsName(PdfName.FT); if (PdfName.BTN.equals(type)) { PdfNumber ff = mergedDict.getAsNumber(PdfName.FF); int flags = 0; if (ff != null) flags = ff.intValue(); if ((flags & PdfFormField.FF_PUSHBUTTON) != 0) return ""; String value = ""; if (v instanceof PdfName) value = PdfName.decodeName(v.toString()); else if (v instanceof PdfString) value = ((PdfString)v).toUnicodeString(); PdfArray opts = item.getValue(0).getAsArray(PdfName.OPT); if (opts != null) { int idx = 0; try { idx = Integer.parseInt(value); PdfString ps = opts.getAsString(idx); value = ps.toUnicodeString(); lastWasString = true; } catch (Exception e) { } } return value; } if (v instanceof PdfString) { lastWasString = true; return ((PdfString)v).toUnicodeString(); } else if (v instanceof PdfName) { return PdfName.decodeName(v.toString()); } else return ""; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setFieldProperty(String field, String name, Object value, int inst[]) { if (writer == null) throw new RuntimeException(MessageLocalization.getComposedMessage("this.acrofields.instance.is.read.only")); try { Item item = fields.get(field); if (item == null) return false; InstHit hit = new InstHit(inst); PdfDictionary merged; PdfString da; if (name.equalsIgnoreCase("textfont")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); PdfDictionary dr = merged.getAsDict(PdfName.DR); if (da != null) { if (dr == null) { dr = new PdfDictionary(); merged.put(PdfName.DR, dr); } Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { BaseFont bf = (BaseFont)value; PdfName psn = PdfAppearance.stdFieldFontNames.get(bf.getPostscriptFontName()); if (psn == null) { psn = new PdfName(bf.getPostscriptFontName()); } PdfDictionary fonts = dr.getAsDict(PdfName.FONT); if (fonts == null) { fonts = new PdfDictionary(); dr.put(PdfName.FONT, fonts); } PdfIndirectReference fref = (PdfIndirectReference)fonts.get(psn); PdfDictionary top = reader.getCatalog().getAsDict(PdfName.ACROFORM); markUsed(top); dr = top.getAsDict(PdfName.DR); if (dr == null) { dr = new PdfDictionary(); top.put(PdfName.DR, dr); } markUsed(dr); PdfDictionary fontsTop = dr.getAsDict(PdfName.FONT); if (fontsTop == null) { fontsTop = new PdfDictionary(); dr.put(PdfName.FONT, fontsTop); } markUsed(fontsTop); PdfIndirectReference frefTop = (PdfIndirectReference)fontsTop.get(psn); if (frefTop != null) { if (fref == null) fonts.put(psn, frefTop); } else if (fref == null) { FontDetails fd; if (bf.getFontType() == BaseFont.FONT_TYPE_DOCUMENT) { fd = new FontDetails(null, ((DocumentFont)bf).getIndirectReference(), bf); } else { bf.setSubset(false); fd = writer.addSimple(bf); localFonts.put(psn.toString().substring(1), bf); } fontsTop.put(psn, fd.getIndirectReference()); fonts.put(psn, fd.getIndirectReference()); } ByteBuffer buf = cb.getInternalBuffer(); buf.append(psn.getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf "); if (dao[DA_COLOR] != null) cb.setColorFill((BaseColor)dao[DA_COLOR]); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("textcolor")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); if (da != null) { Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { ByteBuffer buf = cb.getInternalBuffer(); buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf "); cb.setColorFill((BaseColor)value); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("textsize")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); if (da != null) { Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { ByteBuffer buf = cb.getInternalBuffer(); buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)value).floatValue()).append(" Tf "); if (dao[DA_COLOR] != null) cb.setColorFill((BaseColor)dao[DA_COLOR]); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("bgcolor") || name.equalsIgnoreCase("bordercolor")) { PdfName dname = name.equalsIgnoreCase("bgcolor") ? PdfName.BG : PdfName.BC; for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); PdfDictionary mk = merged.getAsDict(PdfName.MK); if (mk == null) { if (value == null) return true; mk = new PdfDictionary(); item.getMerged(k).put(PdfName.MK, mk); item.getWidget(k).put(PdfName.MK, mk); markUsed(item.getWidget(k)); } else { markUsed( mk ); } if (value == null) mk.remove(dname); else mk.put(dname, PdfFormField.getMKColor((BaseColor)value)); } } } else return false; return true; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public PdfPKCS7 verifySignature(String name, String provider) { PdfDictionary v = getSignatureDictionary(name); if (v == null) return null; try { PdfName sub = v.getAsName(PdfName.SUBFILTER); PdfString contents = v.getAsString(PdfName.CONTENTS); PdfPKCS7 pk = null; if (sub.equals(PdfName.ADBE_X509_RSA_SHA1)) { PdfString cert = v.getAsString(PdfName.CERT); if (cert == null) cert = v.getAsArray(PdfName.CERT).getAsString(0); pk = new PdfPKCS7(contents.getOriginalBytes(), cert.getBytes(), provider); } else pk = new PdfPKCS7(contents.getOriginalBytes(), sub, provider); updateByteRange(pk, v); PdfString str = v.getAsString(PdfName.M); if (str != null) pk.setSignDate(PdfDate.decode(str.toString())); PdfObject obj = PdfReader.getPdfObject(v.get(PdfName.NAME)); if (obj != null) { if (obj.isString()) pk.setSignName(((PdfString)obj).toUnicodeString()); else if(obj.isName()) pk.setSignName(PdfName.decodeName(obj.toString())); } str = v.getAsString(PdfName.REASON); if (str != null) pk.setReason(str.toUnicodeString()); str = v.getAsString(PdfName.LOCATION); if (str != null) pk.setLocation(str.toUnicodeString()); return pk; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
private void updateByteRange(PdfPKCS7 pkcs7, PdfDictionary v) { PdfArray b = v.getAsArray(PdfName.BYTERANGE); RandomAccessFileOrArray rf = reader.getSafeFile(); InputStream rg = null; try { rg = new RASInputStream(new RandomAccessSourceFactory().createRanged(rf.createSourceView(), b.asLongArray())); byte buf[] = new byte[8192]; int rd; while ((rd = rg.read(buf, 0, buf.length)) > 0) { pkcs7.update(buf, 0, rd); } } catch (Exception e) { throw new ExceptionConverter(e); } finally { try { if (rg != null) rg.close(); } catch (IOException e) { // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway throw new ExceptionConverter(e); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public void removeXfa() { PdfDictionary root = reader.getCatalog(); PdfDictionary acroform = root.getAsDict(PdfName.ACROFORM); acroform.remove(PdfName.XFA); try { xfa = new XfaForm(reader); } catch(Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public PushbuttonField getNewPushbuttonFromField(String field, int order) { try { if (getFieldType(field) != FIELD_TYPE_PUSHBUTTON) return null; Item item = getFieldItem(field); if (order >= item.size()) return null; List<FieldPosition> pos = getFieldPositions(field); Rectangle box = pos.get(order).position; PushbuttonField newButton = new PushbuttonField(writer, box, null); PdfDictionary dic = item.getMerged(order); decodeGenericDictionary(dic, newButton); PdfDictionary mk = dic.getAsDict(PdfName.MK); if (mk != null) { PdfString text = mk.getAsString(PdfName.CA); if (text != null) newButton.setText(text.toUnicodeString()); PdfNumber tp = mk.getAsNumber(PdfName.TP); if (tp != null) newButton.setLayout(tp.intValue() + 1); PdfDictionary ifit = mk.getAsDict(PdfName.IF); if (ifit != null) { PdfName sw = ifit.getAsName(PdfName.SW); if (sw != null) { int scale = PushbuttonField.SCALE_ICON_ALWAYS; if (sw.equals(PdfName.B)) scale = PushbuttonField.SCALE_ICON_IS_TOO_BIG; else if (sw.equals(PdfName.S)) scale = PushbuttonField.SCALE_ICON_IS_TOO_SMALL; else if (sw.equals(PdfName.N)) scale = PushbuttonField.SCALE_ICON_NEVER; newButton.setScaleIcon(scale); } sw = ifit.getAsName(PdfName.S); if (sw != null) { if (sw.equals(PdfName.A)) newButton.setProportionalIcon(false); } PdfArray aj = ifit.getAsArray(PdfName.A); if (aj != null && aj.size() == 2) { float left = aj.getAsNumber(0).floatValue(); float bottom = aj.getAsNumber(1).floatValue(); newButton.setIconHorizontalAdjustment(left); newButton.setIconVerticalAdjustment(bottom); } PdfBoolean fb = ifit.getAsBoolean(PdfName.FB); if (fb != null && fb.booleanValue()) newButton.setIconFitToBounds(true); } PdfObject i = mk.get(PdfName.I); if (i != null && i.isIndirect()) newButton.setIconReference((PRIndirectReference)i); } return newButton; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
public void writeCells(int colStart, int colEnd, float xPos, float yPos, PdfContentByte[] canvases, boolean reusable) { if (!calculated) calculateHeights(); if (colEnd < 0) colEnd = cells.length; else colEnd = Math.min(colEnd, cells.length); if (colStart < 0) colStart = 0; if (colStart >= colEnd) return; int newStart; for (newStart = colStart; newStart >= 0; --newStart) { if (cells[newStart] != null) break; if (newStart > 0) xPos -= widths[newStart - 1]; } if (newStart < 0) newStart = 0; if (cells[newStart] != null) xPos -= cells[newStart].getLeft(); if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].openMCBlock(this); } for (int k = newStart; k < colEnd; ++k) { PdfPCell cell = cells[k]; if (cell == null) continue; if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].openMCBlock(cell); } float currentMaxHeight = maxHeight + extraHeights[k]; writeBorderAndBackground(xPos, yPos, currentMaxHeight, cell, canvases); Image img = cell.getImage(); float tly = cell.getTop() + yPos - cell.getEffectivePaddingTop(); if (cell.getHeight() <= currentMaxHeight) { switch (cell.getVerticalAlignment()) { case Element.ALIGN_BOTTOM: tly = cell.getTop() + yPos - currentMaxHeight + cell.getHeight() - cell.getEffectivePaddingTop(); break; case Element.ALIGN_MIDDLE: tly = cell.getTop() + yPos + (cell.getHeight() - currentMaxHeight) / 2 - cell.getEffectivePaddingTop(); break; default: break; } } if (img != null) { if (cell.getRotation() != 0) { img = Image.getInstance(img); img.setRotation(img.getImageRotation() + (float)(cell.getRotation() * Math.PI / 180.0)); } boolean vf = false; if (cell.getHeight() > currentMaxHeight) { if (!img.isScaleToFitLineWhenOverflow()) { continue; } img.scalePercent(100); float scale = (currentMaxHeight - cell.getEffectivePaddingTop() - cell .getEffectivePaddingBottom()) / img.getScaledHeight(); img.scalePercent(scale * 100); vf = true; } float left = cell.getLeft() + xPos + cell.getEffectivePaddingLeft(); if (vf) { switch (cell.getHorizontalAlignment()) { case Element.ALIGN_CENTER: left = xPos + (cell.getLeft() + cell.getEffectivePaddingLeft() + cell.getRight() - cell.getEffectivePaddingRight() - img .getScaledWidth()) / 2; break; case Element.ALIGN_RIGHT: left = xPos + cell.getRight() - cell.getEffectivePaddingRight() - img.getScaledWidth(); break; default: break; } tly = cell.getTop() + yPos - cell.getEffectivePaddingTop(); } img.setAbsolutePosition(left, tly - img.getScaledHeight()); try { if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].openMCBlock(img); } canvases[PdfPTable.TEXTCANVAS].addImage(img); if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].closeMCBlock(img); } } catch (DocumentException e) { throw new ExceptionConverter(e); } } else { // rotation sponsored by Connection GmbH if (cell.getRotation() == 90 || cell.getRotation() == 270) { float netWidth = currentMaxHeight - cell.getEffectivePaddingTop() - cell.getEffectivePaddingBottom(); float netHeight = cell.getWidth() - cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight(); ColumnText ct = ColumnText.duplicate(cell.getColumn()); ct.setCanvases(canvases); ct.setSimpleColumn(0, 0, netWidth + 0.001f, -netHeight); try { ct.go(true); } catch (DocumentException e) { throw new ExceptionConverter(e); } float calcHeight = -ct.getYLine(); if (netWidth <= 0 || netHeight <= 0) calcHeight = 0; if (calcHeight > 0) { if (cell.isUseDescender()) calcHeight -= ct.getDescender(); if (reusable) ct = ColumnText.duplicate(cell.getColumn()); else ct = cell.getColumn(); ct.setCanvases(canvases); ct.setSimpleColumn(-0.003f, -0.001f, netWidth + 0.003f, calcHeight); float pivotX; float pivotY; if (cell.getRotation() == 90) { pivotY = cell.getTop() + yPos - currentMaxHeight + cell.getEffectivePaddingBottom(); switch (cell.getVerticalAlignment()) { case Element.ALIGN_BOTTOM: pivotX = cell.getLeft() + xPos + cell.getWidth() - cell.getEffectivePaddingRight(); break; case Element.ALIGN_MIDDLE: pivotX = cell.getLeft() + xPos + (cell.getWidth() + cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight() + calcHeight) / 2; break; default: //top pivotX = cell.getLeft() + xPos + cell.getEffectivePaddingLeft() + calcHeight; break; } saveAndRotateCanvases(canvases, 0,1,-1,0,pivotX,pivotY); } else { pivotY = cell.getTop() + yPos - cell.getEffectivePaddingTop(); switch (cell.getVerticalAlignment()) { case Element.ALIGN_BOTTOM: pivotX = cell.getLeft() + xPos + cell.getEffectivePaddingLeft(); break; case Element.ALIGN_MIDDLE: pivotX = cell.getLeft() + xPos + (cell.getWidth() + cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight() - calcHeight) / 2; break; default: //top pivotX = cell.getLeft() + xPos + cell.getWidth() - cell.getEffectivePaddingRight() - calcHeight; break; } saveAndRotateCanvases(canvases, 0,-1,1,0,pivotX,pivotY); } try { ct.go(); } catch (DocumentException e) { throw new ExceptionConverter(e); } finally { restoreCanvases(canvases); } } } else { float fixedHeight = cell.getFixedHeight(); float rightLimit = cell.getRight() + xPos - cell.getEffectivePaddingRight(); float leftLimit = cell.getLeft() + xPos + cell.getEffectivePaddingLeft(); if (cell.isNoWrap()) { switch (cell.getHorizontalAlignment()) { case Element.ALIGN_CENTER: rightLimit += 10000; leftLimit -= 10000; break; case Element.ALIGN_RIGHT: if (cell.getRotation() == 180) { rightLimit += RIGHT_LIMIT; } else { leftLimit -= RIGHT_LIMIT; } break; default: if (cell.getRotation() == 180) { leftLimit -= RIGHT_LIMIT; } else { rightLimit += RIGHT_LIMIT; } break; } } ColumnText ct; if (reusable) ct = ColumnText.duplicate(cell.getColumn()); else ct = cell.getColumn(); ct.setCanvases(canvases); float bry = tly - (currentMaxHeight - cell.getEffectivePaddingTop() - cell.getEffectivePaddingBottom()); if (fixedHeight > 0) { if (cell.getHeight() > currentMaxHeight) { tly = cell.getTop() + yPos - cell.getEffectivePaddingTop(); bry = cell.getTop() + yPos - currentMaxHeight + cell.getEffectivePaddingBottom(); } } if ((tly > bry || ct.zeroHeightElement()) && leftLimit < rightLimit) { ct.setSimpleColumn(leftLimit, bry - 0.001f, rightLimit, tly); if (cell.getRotation() == 180) { float shx = leftLimit + rightLimit; float shy = yPos + yPos - currentMaxHeight + cell.getEffectivePaddingBottom() - cell.getEffectivePaddingTop(); saveAndRotateCanvases(canvases, -1,0,0,-1,shx,shy); } try { ct.go(); } catch (DocumentException e) { throw new ExceptionConverter(e); } finally { if (cell.getRotation() == 180) { restoreCanvases(canvases); } } } } } PdfPCellEvent evt = cell.getCellEvent(); if (evt != null) { Rectangle rect = new Rectangle(cell.getLeft() + xPos, cell.getTop() + yPos - currentMaxHeight, cell.getRight() + xPos, cell.getTop() + yPos); evt.cellLayout(cell, rect, canvases); } if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].closeMCBlock(cell); } } if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].closeMCBlock(this); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
public PdfPRow splitRow(PdfPTable table, int rowIndex, float new_height) { LOGGER.info("Splitting " + rowIndex + " " + new_height); // second part of the row PdfPCell newCells[] = new PdfPCell[cells.length]; float fixHs[] = new float[cells.length]; float minHs[] = new float[cells.length]; boolean allEmpty = true; // loop over all the cells for (int k = 0; k < cells.length; ++k) { float newHeight = new_height; PdfPCell cell = cells[k]; if (cell == null) { int index = rowIndex; if (table.rowSpanAbove(index, k)) { while (table.rowSpanAbove(--index, k)) { newHeight += table.getRow(index).getMaxHeights(); } PdfPRow row = table.getRow(index); if (row != null && row.getCells()[k] != null) { newCells[k] = new PdfPCell(row.getCells()[k]); newCells[k].setColumn(null); newCells[k].setRowspan(row.getCells()[k].getRowspan() - rowIndex + index); allEmpty = false; } } continue; } fixHs[k] = cell.getFixedHeight(); minHs[k] = cell.getMinimumHeight(); Image img = cell.getImage(); PdfPCell newCell = new PdfPCell(cell); if (img != null) { float padding = cell.getEffectivePaddingBottom() + cell.getEffectivePaddingTop() + 2; if ((img.isScaleToFitLineWhenOverflow() || img.getScaledHeight() + padding < newHeight) && newHeight > padding) { newCell.setPhrase(null); allEmpty = false; } } else { float y; ColumnText ct = ColumnText.duplicate(cell.getColumn()); float left = cell.getLeft() + cell.getEffectivePaddingLeft(); float bottom = cell.getTop() + cell.getEffectivePaddingBottom() - newHeight; float right = cell.getRight() - cell.getEffectivePaddingRight(); float top = cell.getTop() - cell.getEffectivePaddingTop(); switch (cell.getRotation()) { case 90: case 270: y = setColumn(ct, bottom, left, top, right); break; default: y = setColumn(ct, left, bottom + 0.00001f, cell.isNoWrap() ? RIGHT_LIMIT : right, top); break; } int status; try { status = ct.go(true); } catch (DocumentException e) { throw new ExceptionConverter(e); } boolean thisEmpty = (ct.getYLine() == y); if (thisEmpty) { newCell.setColumn(ColumnText.duplicate(cell.getColumn())); ct.setFilledWidth(0); } else if ((status & ColumnText.NO_MORE_TEXT) == 0) { newCell.setColumn(ct); ct.setFilledWidth(0); } else newCell.setPhrase(null); allEmpty = (allEmpty && thisEmpty); } newCells[k] = newCell; cell.setFixedHeight(newHeight); } if (allEmpty) { for (int k = 0; k < cells.length; ++k) { PdfPCell cell = cells[k]; if (cell == null) continue; if (fixHs[k] > 0) cell.setFixedHeight(fixHs[k]); else cell.setMinimumHeight(minHs[k]); } return null; } calculateHeights(); PdfPRow split = new PdfPRow(newCells, this); split.widths = (float[]) widths.clone(); return split; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAcroForm.java
public void drawCheckBoxAppearences(PdfFormField field, String value, float llx, float lly, float urx, float ury) { BaseFont font = null; try { font = BaseFont.createFont(BaseFont.ZAPFDINGBATS, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); } catch(Exception e) { throw new ExceptionConverter(e); } float size = ury - lly; PdfAppearance tpOn = PdfAppearance.createAppearance(writer, urx - llx, ury - lly); PdfAppearance tp2 = (PdfAppearance)tpOn.getDuplicate(); tp2.setFontAndSize(font, size); tp2.resetRGBColorFill(); field.setDefaultAppearanceString(tp2); tpOn.drawTextField(0f, 0f, urx - llx, ury - lly); tpOn.saveState(); tpOn.resetRGBColorFill(); tpOn.beginText(); tpOn.setFontAndSize(font, size); tpOn.showTextAligned(PdfContentByte.ALIGN_CENTER, "4", (urx - llx) / 2, (ury - lly) / 2 - size * 0.3f, 0); tpOn.endText(); tpOn.restoreState(); field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, value, tpOn); PdfAppearance tpOff = PdfAppearance.createAppearance(writer, urx - llx, ury - lly); tpOff.drawTextField(0f, 0f, urx - llx, ury - lly); field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", tpOff); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
public static final byte[] convertToBytes(String text, String encoding) { if (text == null) return new byte[0]; if (encoding == null || encoding.length() == 0) { int len = text.length(); byte b[] = new byte[len]; for (int k = 0; k < len; ++k) b[k] = (byte)text.charAt(k); return b; } ExtraEncoding extra = extraEncodings.get(encoding.toLowerCase()); if (extra != null) { byte b[] = extra.charToByte(text, encoding); if (b != null) return b; } IntHashtable hash = null; if (encoding.equals(BaseFont.WINANSI)) hash = winansi; else if (encoding.equals(PdfObject.TEXT_PDFDOCENCODING)) hash = pdfEncoding; if (hash != null) { char cc[] = text.toCharArray(); int len = cc.length; int ptr = 0; byte b[] = new byte[len]; int c = 0; for (int k = 0; k < len; ++k) { char char1 = cc[k]; if (char1 < 128 || char1 > 160 && char1 <= 255) c = char1; else c = hash.get(char1); if (c != 0) b[ptr++] = (byte)c; } if (ptr == len) return b; byte b2[] = new byte[ptr]; System.arraycopy(b, 0, b2, 0, ptr); return b2; } if (encoding.equals(PdfObject.TEXT_UNICODE)) { // workaround for jdk 1.2.2 bug char cc[] = text.toCharArray(); int len = cc.length; byte b[] = new byte[cc.length * 2 + 2]; b[0] = -2; b[1] = -1; int bptr = 2; for (int k = 0; k < len; ++k) { char c = cc[k]; b[bptr++] = (byte)(c >> 8); b[bptr++] = (byte)(c & 0xff); } return b; } try { Charset cc = Charset.forName(encoding); CharsetEncoder ce = cc.newEncoder(); ce.onUnmappableCharacter(CodingErrorAction.IGNORE); CharBuffer cb = CharBuffer.wrap(text.toCharArray()); java.nio.ByteBuffer bb = ce.encode(cb); bb.rewind(); int lim = bb.limit(); byte[] br = new byte[lim]; bb.get(br); return br; } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
public static final byte[] convertToBytes(char char1, String encoding) { if (encoding == null || encoding.length() == 0) return new byte[]{(byte)char1}; ExtraEncoding extra = extraEncodings.get(encoding.toLowerCase()); if (extra != null) { byte b[] = extra.charToByte(char1, encoding); if (b != null) return b; } IntHashtable hash = null; if (encoding.equals(BaseFont.WINANSI)) hash = winansi; else if (encoding.equals(PdfObject.TEXT_PDFDOCENCODING)) hash = pdfEncoding; if (hash != null) { int c = 0; if (char1 < 128 || char1 > 160 && char1 <= 255) c = char1; else c = hash.get(char1); if (c != 0) return new byte[]{(byte)c}; else return new byte[0]; } if (encoding.equals(PdfObject.TEXT_UNICODE)) { // workaround for jdk 1.2.2 bug byte b[] = new byte[4]; b[0] = -2; b[1] = -1; b[2] = (byte)(char1 >> 8); b[3] = (byte)(char1 & 0xff); return b; } try { Charset cc = Charset.forName(encoding); CharsetEncoder ce = cc.newEncoder(); ce.onUnmappableCharacter(CodingErrorAction.IGNORE); CharBuffer cb = CharBuffer.wrap(new char[]{char1}); java.nio.ByteBuffer bb = ce.encode(cb); bb.rewind(); int lim = bb.limit(); byte[] br = new byte[lim]; bb.get(br); return br; } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
public static final String convertToString(byte bytes[], String encoding) { if (bytes == null) return PdfObject.NOTHING; if (encoding == null || encoding.length() == 0) { char c[] = new char[bytes.length]; for (int k = 0; k < bytes.length; ++k) c[k] = (char)(bytes[k] & 0xff); return new String(c); } ExtraEncoding extra = extraEncodings.get(encoding.toLowerCase()); if (extra != null) { String text = extra.byteToChar(bytes, encoding); if (text != null) return text; } char ch[] = null; if (encoding.equals(BaseFont.WINANSI)) ch = winansiByteToChar; else if (encoding.equals(PdfObject.TEXT_PDFDOCENCODING)) ch = pdfEncodingByteToChar; if (ch != null) { int len = bytes.length; char c[] = new char[len]; for (int k = 0; k < len; ++k) { c[k] = ch[bytes[k] & 0xff]; } return new String(c); } try { return new String(bytes, encoding); } catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
public void flateCompress(int compressionLevel) { if (!Document.compress) return; // check if the flateCompress-method has already been if (compressed) { return; } this.compressionLevel = compressionLevel; if (inputStream != null) { compressed = true; return; } // check if a filter already exists PdfObject filter = PdfReader.getPdfObject(get(PdfName.FILTER)); if (filter != null) { if (filter.isName()) { if (PdfName.FLATEDECODE.equals(filter)) return; } else if (filter.isArray()) { if (((PdfArray) filter).contains(PdfName.FLATEDECODE)) return; } else { throw new RuntimeException(MessageLocalization.getComposedMessage("stream.could.not.be.compressed.filter.is.not.a.name.or.array")); } } try { // compress ByteArrayOutputStream stream = new ByteArrayOutputStream(); Deflater deflater = new Deflater(compressionLevel); DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater); if (streamBytes != null) streamBytes.writeTo(zip); else zip.write(bytes); zip.close(); deflater.end(); // update the object streamBytes = stream; bytes = null; put(PdfName.LENGTH, new PdfNumber(streamBytes.size())); if (filter == null) { put(PdfName.FILTER, PdfName.FLATEDECODE); } else { PdfArray filters = new PdfArray(filter); filters.add(PdfName.FLATEDECODE); put(PdfName.FILTER, filters); } compressed = true; } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
void addPage(PdfDictionary page) { try { if (pages.size() % leafSize == 0) parents.add(writer.getPdfIndirectReference()); PdfIndirectReference parent = parents.get(parents.size() - 1); page.put(PdfName.PARENT, parent); PdfIndirectReference current = writer.getCurrentPage(); writer.addToBody(page, current); pages.add(current); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
PdfIndirectReference addPageRef(PdfIndirectReference pageRef) { try { if (pages.size() % leafSize == 0) parents.add(writer.getPdfIndirectReference()); pages.add(pageRef); return parents.get(parents.size() - 1); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected void buildStructTreeRootForTagged(PdfDictionary catalog) { if (tagged) { try { getStructureTreeRoot().buildTree(); } catch (Exception e) { throw new ExceptionConverter(e); } catalog.put(PdfName.STRUCTTREEROOT, structureTreeRoot.getReference()); PdfDictionary mi = new PdfDictionary(); mi.put(PdfName.MARKED, PdfBoolean.PDFTRUE); if (userProperties) mi.put(PdfName.USERPROPERTIES, PdfBoolean.PDFTRUE); catalog.put(PdfName.MARKINFO, mi); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectReference add(final PdfPage page, final PdfContents contents) throws PdfException { if (!open) { throw new PdfException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfIndirectObject object; try { object = addToBody(contents); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } page.add(object.getIndirectReference()); // [U5] if (group != null) { page.put(PdfName.GROUP, group); group = null; } else if (rgbTransparencyBlending) { PdfDictionary pp = new PdfDictionary(); pp.put(PdfName.TYPE, PdfName.GROUP); pp.put(PdfName.S, PdfName.TRANSPARENCY); pp.put(PdfName.CS, PdfName.DEVICERGB); page.put(PdfName.GROUP, pp); } root.addPage(page); currentPageNumber++; return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Override public void open() { super.open(); try { pdf_version.writeHeader(os); body = new PdfBody(this); if (isPdfX() && ((PdfXConformanceImp)pdfIsoConformance).isPdfX32002()) { PdfDictionary sec = new PdfDictionary(); sec.put(PdfName.GAMMA, new PdfArray(new float[]{2.2f,2.2f,2.2f})); sec.put(PdfName.MATRIX, new PdfArray(new float[]{0.4124f,0.2126f,0.0193f,0.3576f,0.7152f,0.1192f,0.1805f,0.0722f,0.9505f})); sec.put(PdfName.WHITEPOINT, new PdfArray(new float[]{0.9505f,1f,1.089f})); PdfArray arr = new PdfArray(PdfName.CALRGB); arr.add(sec); setDefaultColorspace(PdfName.DEFAULTRGB, addToBody(arr).getIndirectReference()); } } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Override public void close() { if (open) { if (currentPageNumber - 1 != pageReferences.size()) throw new RuntimeException("The page " + pageReferences.size() + " was requested but the document has only " + (currentPageNumber - 1) + " pages."); pdf.close(); try { addSharedObjectsToBody(); for (PdfOCG layer : documentOCG) { addToBody(layer.getPdfObject(), layer.getRef()); } // add the root to the body PdfIndirectReference rootRef = root.writePageTree(); // make the catalog-object and add it to the body PdfDictionary catalog = getCatalog(rootRef); // [C9] if there is XMP data to add: add it if (xmpMetadata != null) { PdfStream xmp = new PdfStream(xmpMetadata); 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); } catalog.put(PdfName.METADATA, body.add(xmp).getIndirectReference()); } // [C10] make pdfx conformant if (isPdfX()) { completeInfoDictionary(getInfo()); completeExtraCatalog(getExtraCatalog()); } // [C11] Output Intents if (extraCatalog != null) { catalog.mergeDifferent(extraCatalog); } writeOutlines(catalog, false); // add the Catalog to the body PdfIndirectObject indirectCatalog = addToBody(catalog, false); // add the info-object to the body PdfIndirectObject infoObj = addToBody(getInfo(), false); // [F1] encryption PdfIndirectReference encryption = null; PdfObject fileID = null; body.flushObjStm(); if (crypto != null) { PdfIndirectObject encryptionObject = addToBody(crypto.getEncryptionDictionary(), false); encryption = encryptionObject.getIndirectReference(); fileID = crypto.getFileID(); } else fileID = PdfEncryption.createInfoId(PdfEncryption.createDocumentId()); // write the cross-reference table of the body body.writeCrossReferenceTable(os, indirectCatalog.getIndirectReference(), infoObj.getIndirectReference(), encryption, fileID, prevxref); // make the trailer // [F2] full compression 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(), indirectCatalog.getIndirectReference(), infoObj.getIndirectReference(), encryption, fileID, prevxref); trailer.toPdf(this, os); } super.close(); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfName addDirectTemplateSimple(PdfTemplate template, final PdfName forcedName) { PdfIndirectReference ref = template.getIndirectReference(); Object obj[] = formXObjects.get(ref); PdfName name = null; try { if (obj == null) { if (forcedName == null) { name = new PdfName("Xf" + formXObjectsCounter); ++formXObjectsCounter; } else name = forcedName; if (template.getType() == PdfTemplate.TYPE_IMPORTED) { // If we got here from PdfCopy we'll have to fill importedPages PdfImportedPage ip = (PdfImportedPage)template; PdfReader r = ip.getPdfReaderInstance().getReader(); if (!readerInstances.containsKey(r)) { readerInstances.put(r, ip.getPdfReaderInstance()); } template = null; } formXObjects.put(ref, new Object[]{name, template}); } else name = (PdfName)obj[0]; } catch (Exception e) { throw new ExceptionConverter(e); } return name; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfName addSimplePattern(final PdfPatternPainter painter) { PdfName name = documentPatterns.get(painter); try { if ( name == null ) { name = new PdfName("P" + patternNumber); ++patternNumber; documentPatterns.put(painter, name); } } catch (Exception e) { throw new ExceptionConverter(e); } return name; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectReference add(final PdfImage pdfImage, PdfIndirectReference fixedRef) throws PdfException { if (! imageDictionary.contains(pdfImage.name())) { PdfWriter.checkPdfIsoConformance(this, PdfIsoKeys.PDFISOKEY_IMAGE, pdfImage); if (fixedRef instanceof PRIndirectReference) { PRIndirectReference r2 = (PRIndirectReference)fixedRef; fixedRef = new PdfIndirectReference(0, getNewObjectNumber(r2.getReader(), r2.getNumber(), r2.getGeneration())); } try { if (fixedRef == null) fixedRef = addToBody(pdfImage).getIndirectReference(); else addToBody(pdfImage, fixedRef); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } imageDictionary.put(pdfImage.name(), fixedRef); return fixedRef; } return (PdfIndirectReference) imageDictionary.get(pdfImage.name()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected PdfIndirectReference add(final PdfICCBased icc) { PdfIndirectObject object; try { object = addToBody(icc); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } return object.getIndirectReference(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void addAnnotation(PdfAnnotation annot, PdfDictionary pageN) { try { ArrayList<PdfAnnotation> allAnnots = new ArrayList<PdfAnnotation>(); if (annot.isForm()) { fieldsAdded = true; getAcroFields(); PdfFormField field = (PdfFormField)annot; if (field.getParent() != null) return; expandFields(field, allAnnots); } else allAnnots.add(annot); for (int k = 0; k < allAnnots.size(); ++k) { annot = allAnnots.get(k); if (annot.getPlaceInPage() > 0) pageN = reader.getPageN(annot.getPlaceInPage()); if (annot.isForm()) { if (!annot.isUsed()) { HashSet<PdfTemplate> templates = annot.getTemplates(); if (templates != null) fieldTemplates.addAll(templates); } PdfFormField field = (PdfFormField)annot; if (field.getParent() == null) addDocumentField(field.getIndirectReference()); } if (annot.isAnnotation()) { PdfObject pdfobj = PdfReader.getPdfObject(pageN.get(PdfName.ANNOTS), pageN); PdfArray annots = null; if (pdfobj == null || !pdfobj.isArray()) { annots = new PdfArray(); pageN.put(PdfName.ANNOTS, annots); markUsed(pageN); } else annots = (PdfArray)pdfobj; annots.add(annot.getIndirectReference()); markUsed(annots); if (!annot.isUsed()) { PdfRectangle rect = (PdfRectangle)annot.get(PdfName.RECT); if (rect != null && (rect.left() != 0 || rect.right() != 0 || rect.top() != 0 || rect.bottom() != 0)) { int rotation = reader.getPageRotation(pageN); Rectangle pageSize = reader.getPageSizeWithRotation(pageN); switch (rotation) { case 90: annot.put(PdfName.RECT, new PdfRectangle( pageSize.getTop() - rect.top(), rect.right(), pageSize.getTop() - rect.bottom(), rect.left())); break; case 180: annot.put(PdfName.RECT, new PdfRectangle( pageSize.getRight() - rect.left(), pageSize.getTop() - rect.bottom(), pageSize.getRight() - rect.right(), pageSize.getTop() - rect.top())); break; case 270: annot.put(PdfName.RECT, new PdfRectangle( rect.bottom(), pageSize.getRight() - rect.left(), rect.top(), pageSize.getRight() - rect.right())); break; } } } } if (!annot.isUsed()) { annot.setUsed(); addToBody(annot, annot.getIndirectReference()); } } } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPCell.java
public float getMaxHeight() { boolean pivoted = getRotation() == 90 || getRotation() == 270; Image img = getImage(); if (img != null) { img.scalePercent(100); float refWidth = pivoted ? img.getScaledHeight() : img.getScaledWidth(); float scale = (getRight() - getEffectivePaddingRight() - getEffectivePaddingLeft() - getLeft()) / refWidth; img.scalePercent(scale * 100); float refHeight = pivoted ? img.getScaledWidth() : img.getScaledHeight(); setBottom(getTop() - getEffectivePaddingTop() - getEffectivePaddingBottom() - refHeight); } else { if ((pivoted && hasFixedHeight()) || getColumn() == null) setBottom(getTop() - getFixedHeight()); else { ColumnText ct = ColumnText.duplicate(getColumn()); float right, top, left, bottom; if (pivoted) { right = PdfPRow.RIGHT_LIMIT; top = getRight() - getEffectivePaddingRight(); left = 0; bottom = getLeft() + getEffectivePaddingLeft(); } else { right = isNoWrap() ? PdfPRow.RIGHT_LIMIT : getRight() - getEffectivePaddingRight(); top = getTop() - getEffectivePaddingTop(); left = getLeft() + getEffectivePaddingLeft(); bottom = hasFixedHeight() ? getTop() + getEffectivePaddingBottom() - getFixedHeight() : PdfPRow.BOTTOM_LIMIT; } PdfPRow.setColumn(ct, left, bottom, right, top); try { ct.go(true); } catch (DocumentException e) { throw new ExceptionConverter(e); } if (pivoted) setBottom(getTop() - getEffectivePaddingTop() - getEffectivePaddingBottom() - ct.getFilledWidth()); else { float yLine = ct.getYLine(); if (isUseDescender()) yLine += ct.getDescender(); setBottom(yLine - getEffectivePaddingBottom()); } } } float height = getHeight(); if (height == getEffectivePaddingTop() + getEffectivePaddingBottom()) height = 0; if (hasFixedHeight()) height = getFixedHeight(); else if (hasMinimumHeight() && height < getMinimumHeight()) height = getMinimumHeight(); return height; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/events/FieldPositioningEvents.java
Override public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) { rect.setBottom(rect.getBottom() - 3); PdfFormField field = genericChunkFields.get(text); if (field == null) { TextField tf = new TextField(writer, new Rectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding), rect.getTop(padding)), text); tf.setFontSize(14); try { field = tf.getTextField(); } catch (Exception e) { throw new ExceptionConverter(e); } } else { field.put(PdfName.RECT, new PdfRectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding), rect.getTop(padding))); } if (parent == null) writer.addAnnotation(field); else parent.addKid(field); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
Override public void close() { if (closing) { super.close(); return; } closing = true; try { closeIt(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
Override protected PdfDictionary getCatalog(PdfIndirectReference rootObj) { try { PdfDictionary cat = pdf.getCatalog(rootObj); if (form != null) { PdfIndirectReference ref = addToBody(form).getIndirectReference(); cat.put(PdfName.ACROFORM, ref); } return cat; } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LZWDecoder.java
public void writeString(byte string[]) { try { uncompData.write(string); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
byte[] convertToBytes(String text) { byte b[] = null; switch (fontType) { case BaseFont.FONT_TYPE_T3: return baseFont.convertToBytes(text); case BaseFont.FONT_TYPE_T1: case BaseFont.FONT_TYPE_TT: { b = baseFont.convertToBytes(text); int len = b.length; for (int k = 0; k < len; ++k) shortTag[b[k] & 0xff] = 1; break; } case BaseFont.FONT_TYPE_CJK: { int len = text.length(); if (cjkFont.isIdentity()) { for (int k = 0; k < len; ++k) { cjkTag.put(text.charAt(k), 0); } } else { for (int k = 0; k < len; ++k) { int val; if (Utilities.isSurrogatePair(text, k)) { val = Utilities.convertToUtf32(text, k); k++; } else { val = text.charAt(k); } cjkTag.put(cjkFont.getCidCode(val), 0); } } b = cjkFont.convertToBytes(text); break; } case BaseFont.FONT_TYPE_DOCUMENT: { b = baseFont.convertToBytes(text); break; } case BaseFont.FONT_TYPE_TTUNI: { try { int len = text.length(); int metrics[] = null; char glyph[] = new char[len]; int i = 0; if (symbolic) { b = PdfEncodings.convertToBytes(text, "symboltt"); len = b.length; for (int k = 0; k < len; ++k) { metrics = ttu.getMetricsTT(b[k] & 0xff); if (metrics == null) continue; longTag.put(Integer.valueOf(metrics[0]), new int[]{metrics[0], metrics[1], ttu.getUnicodeDifferences(b[k] & 0xff)}); glyph[i++] = (char)metrics[0]; } } else if (canApplyGlyphSubstitution()) { return convertToBytesAfterGlyphSubstitution(text); } else { for (int k = 0; k < len; ++k) { int val; if (Utilities.isSurrogatePair(text, k)) { val = Utilities.convertToUtf32(text, k); k++; } else { val = text.charAt(k); } metrics = ttu.getMetricsTT(val); if (metrics == null) continue; int m0 = metrics[0]; Integer gl = Integer.valueOf(m0); if (!longTag.containsKey(gl)) longTag.put(gl, new int[]{m0, metrics[1], val}); glyph[i++] = (char)m0; } } String s = new String(glyph, 0, i); b = s.getBytes(CJKFont.CJK_ENCODING); } catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); } break; } } return b; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
public void writeFont(PdfWriter writer) { try { switch (fontType) { case BaseFont.FONT_TYPE_T3: baseFont.writeFont(writer, indirectReference, null); break; case BaseFont.FONT_TYPE_T1: case BaseFont.FONT_TYPE_TT: { int firstChar; int lastChar; for (firstChar = 0; firstChar < 256; ++firstChar) { if (shortTag[firstChar] != 0) break; } for (lastChar = 255; lastChar >= firstChar; --lastChar) { if (shortTag[lastChar] != 0) break; } if (firstChar > 255) { firstChar = 255; lastChar = 255; } baseFont.writeFont(writer, indirectReference, new Object[]{Integer.valueOf(firstChar), Integer.valueOf(lastChar), shortTag, Boolean.valueOf(subset)}); break; } case BaseFont.FONT_TYPE_CJK: baseFont.writeFont(writer, indirectReference, new Object[]{cjkTag}); break; case BaseFont.FONT_TYPE_TTUNI: baseFont.writeFont(writer, indirectReference, new Object[]{longTag, Boolean.valueOf(subset)}); break; } } catch(Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFunction.java
PdfIndirectReference getReference() { try { if (reference == null) { reference = writer.addToBody(dictionary).getIndirectReference(); } } catch (IOException ioe) { throw new ExceptionConverter(ioe); } return reference; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfAnnotationsImp.java
public PdfArray rotateAnnotations(PdfWriter writer, Rectangle pageSize) { PdfArray array = new PdfArray(); int rotation = pageSize.getRotation() % 360; int currentPage = writer.getCurrentPageNumber(); for (int k = 0; k < annotations.size(); ++k) { PdfAnnotation dic = annotations.get(k); int page = dic.getPlaceInPage(); if (page > currentPage) { delayedAnnotations.add(dic); continue; } if (dic.isForm()) { if (!dic.isUsed()) { HashSet<PdfTemplate> templates = dic.getTemplates(); if (templates != null) acroForm.addFieldTemplates(templates); } PdfFormField field = (PdfFormField)dic; if (field.getParent() == null) acroForm.addDocumentField(field.getIndirectReference()); } if (dic.isAnnotation()) { array.add(dic.getIndirectReference()); if (!dic.isUsed()) { PdfArray tmp = dic.getAsArray(PdfName.RECT); PdfRectangle rect; if (tmp.size() == 4) { rect = new PdfRectangle(tmp.getAsNumber(0).floatValue(), tmp.getAsNumber(1).floatValue(), tmp.getAsNumber(2).floatValue(), tmp.getAsNumber(3).floatValue()); } else { rect = new PdfRectangle(tmp.getAsNumber(0).floatValue(), tmp.getAsNumber(1).floatValue()); } if (rect != null) { switch (rotation) { case 90: dic.put(PdfName.RECT, new PdfRectangle( pageSize.getTop() - rect.bottom(), rect.left(), pageSize.getTop() - rect.top(), rect.right())); break; case 180: dic.put(PdfName.RECT, new PdfRectangle( pageSize.getRight() - rect.left(), pageSize.getTop() - rect.bottom(), pageSize.getRight() - rect.right(), pageSize.getTop() - rect.top())); break; case 270: dic.put(PdfName.RECT, new PdfRectangle( rect.bottom(), pageSize.getRight() - rect.left(), rect.top(), pageSize.getRight() - rect.right())); break; } } } } if (!dic.isUsed()) { dic.setUsed(); try { writer.addToBody(dic, dic.getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } } } return array; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static PdfObject getPdfObject(PdfObject obj) { if (obj == null) return null; if (!obj.isIndirect()) return obj; try { PRIndirectReference ref = (PRIndirectReference)obj; int idx = ref.getNumber(); boolean appendable = ref.getReader().appendable; obj = ref.getReader().getPdfObject(idx); if (obj == null) { return null; } else { if (appendable) { switch (obj.type()) { case PdfObject.NULL: obj = new PdfNull(); break; case PdfObject.BOOLEAN: obj = new PdfBoolean(((PdfBoolean)obj).booleanValue()); break; case PdfObject.NAME: obj = new PdfName(obj.getBytes()); break; } obj.setIndRef(ref); } return obj; } } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public PdfObject getPdfObject(final int idx) { try { lastXrefPartial = -1; if (idx < 0 || idx >= xrefObj.size()) return null; PdfObject obj = xrefObj.get(idx); if (!partial || obj != null) return obj; if (idx * 2 >= xref.length) return null; obj = readSingleObject(idx); lastXrefPartial = -1; if (obj != null) lastXrefPartial = idx; return obj; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public void close() { try { tokens.close(); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public PRIndirectReference getPageOrigRef(int pageNum) { try { --pageNum; if (pageNum < 0 || pageNum >= size()) return null; if (refsn != null) return refsn.get(pageNum); else { int n = refsp.get(pageNum); if (n == 0) { PRIndirectReference ref = getSinglePage(pageNum); if (reader.lastXrefPartial == -1) lastPageRead = -1; else lastPageRead = pageNum; reader.lastXrefPartial = -1; refsp.put(pageNum, ref.getNumber()); if (keepPages) lastPageRead = -1; return ref; } else { if (lastPageRead != pageNum) lastPageRead = -1; if (keepPages) lastPageRead = -1; return new PRIndirectReference(reader, n); } } } catch (Exception e) { throw new ExceptionConverter(e); } }
// 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/CFFFont.java
char getCard8() { try { byte i = buf.readByte(); return (char)(i & 0xff); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
char getCard16() { try { return buf.readChar(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
void seek(int offset) { try { buf.seek(offset); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
short getShort() { try { return buf.readShort(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
int getInt() { try { return buf.readInt(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
int getPosition() { try { return (int)buf.getFilePointer(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
Override public void emit(byte[] buffer) { //System.err.println("range emit offset "+offset+" size="+length); try { buf.seek(offset); for (int i=myOffset; i<myOffset+length; i++) buffer[i] = buf.readByte(); } catch (Exception e) { throw new ExceptionConverter(e); } //System.err.println("finished range emit"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void beginMarkedContentSequence(final PdfName tag, final PdfDictionary property, final boolean inline) { int contentSize = content.size(); if (property == null) { content.append(tag.getBytes()).append(" BMC").append_i(separator); setMcDepth(getMcDepth() + 1); } else { content.append(tag.getBytes()).append(' '); if (inline) try { property.toPdf(writer, content); } catch (Exception e) { throw new ExceptionConverter(e); } else { PdfObject[] objs; if (writer.propertyExists(property)) objs = writer.addSimpleProperty(property, null); else objs = writer.addSimpleProperty(property, writer.getPdfIndirectReference()); PdfName name = (PdfName)objs[0]; PageResources prs = getPageResources(); name = prs.addProperty(name, (PdfIndirectReference)objs[1]); content.append(name.getBytes()); } content.append(" BDC").append_i(separator); setMcDepth(getMcDepth() + 1); } markedContentSize += content.size() - contentSize; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addNames(final TreeMap<String, Destination> localDestinations, final HashMap<String, PdfObject> documentLevelJS, final HashMap<String, PdfObject> documentFileAttachment, final PdfWriter writer) { if (localDestinations.isEmpty() && documentLevelJS.isEmpty() && documentFileAttachment.isEmpty()) return; try { PdfDictionary names = new PdfDictionary(); if (!localDestinations.isEmpty()) { PdfArray ar = new PdfArray(); for (Map.Entry<String, Destination> entry : localDestinations.entrySet()) { String name = entry.getKey(); Destination dest = entry.getValue(); if (dest.destination == null) //no destination continue; PdfIndirectReference ref = dest.reference; ar.add(new PdfString(name, null)); ar.add(ref); } if (ar.size() > 0) { PdfDictionary dests = new PdfDictionary(); dests.put(PdfName.NAMES, ar); names.put(PdfName.DESTS, writer.addToBody(dests).getIndirectReference()); } } if (!documentLevelJS.isEmpty()) { PdfDictionary tree = PdfNameTree.writeTree(documentLevelJS, writer); names.put(PdfName.JAVASCRIPT, writer.addToBody(tree).getIndirectReference()); } if (!documentFileAttachment.isEmpty()) { names.put(PdfName.EMBEDDEDFILES, writer.addToBody(PdfNameTree.writeTree(documentFileAttachment, writer)).getIndirectReference()); } if (names.size() > 0) put(PdfName.NAMES, writer.addToBody(names).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void setAdditionalActions(final PdfDictionary actions) { try { put(PdfName.AA, writer.addToBody(actions).getIndirectReference()); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public void open() { if (!open) { super.open(); writer.open(); rootOutline = new PdfOutline(writer); currentOutline = rootOutline; } try { initPage(); if (isTagged(writer)) { openMCDocument = true; } } catch(DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public boolean newPage() { try { flushFloatingElements(); } catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } lastElementType = -1; if (isPageEmpty()) { setNewPageSizeAndMargins(); return false; } if (!open || close) { throw new RuntimeException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) pageEvent.onEndPage(writer, this); //Added to inform any listeners that we are moving to a new page (added by David Freels) super.newPage(); // the following 2 lines were added by Pelikan Stephan indentation.imageIndentLeft = 0; indentation.imageIndentRight = 0; try { // we flush the arraylist with recently written lines flushLines(); // we prepare the elements of the page dictionary // [U1] page size and rotation int rotation = pageSize.getRotation(); // [C10] if (writer.isPdfIso()) { if (thisBoxSize.containsKey("art") && thisBoxSize.containsKey("trim")) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("only.one.of.artbox.or.trimbox.can.exist.in.the.page")); if (!thisBoxSize.containsKey("art") && !thisBoxSize.containsKey("trim")) { if (thisBoxSize.containsKey("crop")) thisBoxSize.put("trim", thisBoxSize.get("crop")); else thisBoxSize.put("trim", new PdfRectangle(pageSize, pageSize.getRotation())); } } // [M1] pageResources.addDefaultColorDiff(writer.getDefaultColorspace()); if (writer.isRgbTransparencyBlending()) { PdfDictionary dcs = new PdfDictionary(); dcs.put(PdfName.CS, PdfName.DEVICERGB); pageResources.addDefaultColorDiff(dcs); } PdfDictionary resources = pageResources.getResources(); // we create the page dictionary PdfPage page = new PdfPage(new PdfRectangle(pageSize, rotation), thisBoxSize, resources, rotation); if (isTagged(writer)) { page.put(PdfName.TABS, PdfName.S); } else { page.put(PdfName.TABS, writer.getTabs()); } page.putAll(writer.getPageDictEntries()); writer.resetPageDictEntries(); // we complete the page dictionary // [U3] page actions: additional actions if (pageAA != null) { page.put(PdfName.AA, writer.addToBody(pageAA).getIndirectReference()); pageAA = null; } // [C5] and [C8] we add the annotations if (annotationsImp.hasUnusedAnnotations()) { PdfArray array = annotationsImp.rotateAnnotations(writer, pageSize); if (array.size() != 0) page.put(PdfName.ANNOTS, array); } // [F12] we add tag info if (isTagged(writer)) page.put(PdfName.STRUCTPARENTS, new PdfNumber(writer.getCurrentPageNumber() - 1)); if (text.size() > textEmptySize || isTagged(writer)) text.endText(); else text = null; ArrayList<IAccessibleElement> mcBlocks = null; if (isTagged(writer)) { mcBlocks = writer.getDirectContent().saveMCBlocks(); } writer.add(page, new PdfContents(writer.getDirectContentUnder(), graphics, !isTagged(writer) ? text : null, writer.getDirectContent(), pageSize)); // we initialize the new page initPage(); if (isTagged(writer)) { writer.getDirectContentUnder().restoreMCBlocks(mcBlocks); } } catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } catch (IOException ioe) { throw new ExceptionConverter(ioe); } return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void initPage() throws DocumentException { // the pagenumber is incremented pageN++; // initialization of some page objects annotationsImp.resetAnnotations(); pageResources = new PageResources(); writer.resetContent(); if (isTagged(writer)) { graphics = writer.getDirectContentUnder().getDuplicate(); writer.getDirectContent().duplicatedFrom = graphics; } else { graphics = new PdfContentByte(writer); } markPoint = 0; setNewPageSizeAndMargins(); imageEnd = -1; indentation.imageIndentRight = 0; indentation.imageIndentLeft = 0; indentation.indentBottom = 0; indentation.indentTop = 0; currentHeight = 0; // backgroundcolors, etc... thisBoxSize = new HashMap<String, PdfRectangle>(boxSize); if (pageSize.getBackgroundColor() != null || pageSize.hasBorders() || pageSize.getBorderColor() != null) { add(pageSize); } float oldleading = leading; int oldAlignment = alignment; pageEmpty = true; // if there is an image waiting to be drawn, draw it try { if (imageWait != null) { add(imageWait); imageWait = null; } } catch(Exception e) { throw new ExceptionConverter(e); } leading = oldleading; alignment = oldAlignment; carriageReturn(); PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) { if (firstPageEvent) { pageEvent.onOpenDocument(writer, this); } pageEvent.onStartPage(writer, this); } firstPageEvent = false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void ensureNewLine() { try { if (lastElementType == Element.PHRASE || lastElementType == Element.CHUNK) { newLine(); flushLines(); } } catch (DocumentException ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
PdfCatalog getCatalog(final PdfIndirectReference pages) { PdfCatalog catalog = new PdfCatalog(pages, writer); // [C1] outlines if (rootOutline.getKids().size() > 0) { catalog.put(PdfName.PAGEMODE, PdfName.USEOUTLINES); catalog.put(PdfName.OUTLINES, rootOutline.indirectReference()); } // [C2] version writer.getPdfVersion().addToCatalog(catalog); // [C3] preferences viewerPreferences.addToCatalog(catalog); // [C4] pagelabels if (pageLabels != null) { catalog.put(PdfName.PAGELABELS, pageLabels.getDictionary(writer)); } // [C5] named objects catalog.addNames(localDestinations, getDocumentLevelJS(), documentFileAttachment, writer); // [C6] actions if (openActionName != null) { PdfAction action = getLocalGotoAction(openActionName); catalog.setOpenAction(action); } else if (openActionAction != null) catalog.setOpenAction(openActionAction); if (additionalActions != null) { catalog.setAdditionalActions(additionalActions); } // [C7] portable collections if (collection != null) { catalog.put(PdfName.COLLECTION, collection); } // [C8] AcroForm if (annotationsImp.hasValidAcroForm()) { try { catalog.put(PdfName.ACROFORM, writer.addToBody(annotationsImp.getAcroForm()).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } } if (language != null) { catalog.put(PdfName.LANG, language); } return catalog; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addJavaScript(final PdfAction js) { if (js.get(PdfName.JS) == null) throw new RuntimeException(MessageLocalization.getComposedMessage("only.javascript.actions.are.allowed")); try { documentLevelJS.put(SIXTEEN_DIGITS.format(jsCounter++), writer.addToBody(js).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addJavaScript(final String name, final PdfAction js) { if (js.get(PdfName.JS) == null) throw new RuntimeException(MessageLocalization.getComposedMessage("only.javascript.actions.are.allowed")); try { documentLevelJS.put(name, writer.addToBody(js).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
Override protected PdfDictionary getCatalog(PdfIndirectReference rootObj) { try { PdfDictionary theCat = pdf.getCatalog(rootObj); buildStructTreeRootForTagged(theCat); if (fieldArray == null) { if (acroForm != null) theCat.put(PdfName.ACROFORM, acroForm); } else addFieldResources(theCat); return theCat; } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
public void addAnnotation(PdfAnnotation annot) { try { ArrayList<PdfAnnotation> allAnnots = new ArrayList<PdfAnnotation>(); if (annot.isForm()) { PdfFormField field = (PdfFormField)annot; if (field.getParent() != null) return; expandFields(field, allAnnots); if (cstp.fieldTemplates == null) cstp.fieldTemplates = new HashSet<PdfTemplate>(); } else allAnnots.add(annot); for (int k = 0; k < allAnnots.size(); ++k) { annot = allAnnots.get(k); if (annot.isForm()) { if (!annot.isUsed()) { HashSet<PdfTemplate> templates = annot.getTemplates(); if (templates != null) cstp.fieldTemplates.addAll(templates); } PdfFormField field = (PdfFormField)annot; if (field.getParent() == null) addDocumentField(field.getIndirectReference()); } if (annot.isAnnotation()) { PdfObject pdfobj = PdfReader.getPdfObject(pageN.get(PdfName.ANNOTS), pageN); PdfArray annots = null; if (pdfobj == null || !pdfobj.isArray()) { annots = new PdfArray(); pageN.put(PdfName.ANNOTS, annots); } else annots = (PdfArray)pdfobj; annots.add(annot.getIndirectReference()); if (!annot.isUsed()) { PdfRectangle rect = (PdfRectangle)annot.get(PdfName.RECT); if (rect != null && (rect.left() != 0 || rect.right() != 0 || rect.top() != 0 || rect.bottom() != 0)) { int rotation = reader.getPageRotation(pageN); Rectangle pageSize = reader.getPageSizeWithRotation(pageN); switch (rotation) { case 90: annot.put(PdfName.RECT, new PdfRectangle( pageSize.getTop() - rect.bottom(), rect.left(), pageSize.getTop() - rect.top(), rect.right())); break; case 180: annot.put(PdfName.RECT, new PdfRectangle( pageSize.getRight() - rect.left(), pageSize.getTop() - rect.bottom(), pageSize.getRight() - rect.right(), pageSize.getTop() - rect.top())); break; case 270: annot.put(PdfName.RECT, new PdfRectangle( rect.bottom(), pageSize.getRight() - rect.left(), rect.top(), pageSize.getRight() - rect.right())); break; } } } } if (!annot.isUsed()) { annot.setUsed(); cstp.addToBody(annot, annot.getIndirectReference()); } } } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
public void setData(byte[] data, boolean compress, int compressionLevel) { remove(PdfName.FILTER); this.offset = -1; if (Document.compress && compress) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); Deflater deflater = new Deflater(compressionLevel); DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater); zip.write(data); zip.close(); deflater.end(); bytes = stream.toByteArray(); this.compressionLevel = compressionLevel; } catch (IOException ioe) { throw new ExceptionConverter(ioe); } put(PdfName.FILTER, PdfName.FLATEDECODE); } else bytes = data; setLength(bytes.length); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
public void processContent(byte[] contentBytes, PdfDictionary resources){ this.resources.push(resources); try { PRTokeniser tokeniser = new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(contentBytes))); PdfContentParser ps = new PdfContentParser(tokeniser); ArrayList<PdfObject> operands = new ArrayList<PdfObject>(); while (ps.parse(operands).size() > 0){ PdfLiteral operator = (PdfLiteral)operands.get(operands.size()-1); if ("BI".equals(operator.toString())){ // we don't call invokeOperator for embedded images - this is one area of the PDF spec that is particularly nasty and inconsistent PdfDictionary colorSpaceDic = resources != null ? resources.getAsDict(PdfName.COLORSPACE) : null; ImageRenderInfo renderInfo = ImageRenderInfo.createForEmbeddedImage(gs().ctm, InlineImageUtils.parseInlineImage(ps, colorSpaceDic), colorSpaceDic); renderListener.renderImage(renderInfo); } else { invokeOperator(operator, operands); } } } catch (Exception e) { throw new ExceptionConverter(e); } this.resources.pop(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
public void handleXObject(PdfContentStreamProcessor processor, PdfStream stream, PdfIndirectReference ref) { final PdfDictionary resources = stream.getAsDict(PdfName.RESOURCES); // we read the content bytes up here so if it fails we don't leave the graphics state stack corrupted // this is probably not necessary (if we fail on this, probably the entire content stream processing // operation should be rejected byte[] contentBytes; try { contentBytes = ContentByteUtils.getContentBytesFromContentObject(stream); } catch (IOException e1) { throw new ExceptionConverter(e1); } final PdfArray matrix = stream.getAsArray(PdfName.MATRIX); new PushGraphicsState().invoke(processor, null, null); if (matrix != null){ float a = matrix.getAsNumber(0).floatValue(); float b = matrix.getAsNumber(1).floatValue(); float c = matrix.getAsNumber(2).floatValue(); float d = matrix.getAsNumber(3).floatValue(); float e = matrix.getAsNumber(4).floatValue(); float f = matrix.getAsNumber(5).floatValue(); Matrix formMatrix = new Matrix(a, b, c, d, e, f); processor.gs().ctm = formMatrix.multiply(processor.gs().ctm); } processor.processContent(contentBytes, resources); new PopGraphicsState().invoke(processor, null, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
public static ICC_Profile getInstance(byte[] data, int numComponents) { if (data.length < 128 || data[36] != 0x61 || data[37] != 0x63 || data[38] != 0x73 || data[39] != 0x70) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); try { ICC_Profile icc = new ICC_Profile(); icc.data = data; Integer cs; cs = cstags.get(new String(data, 16, 4, "US-ASCII")); int nc = cs == null ? 0 : cs.intValue(); icc.numComponents = nc; // invalid ICC if (nc != numComponents) { throw new IllegalArgumentException("ICC profile contains " + nc + " component(s), the image data contains " + numComponents + " component(s)"); } return icc; } catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
public static ICC_Profile getInstance(byte[] data) { try { Integer cs; cs = cstags.get(new String(data, 16, 4, "US-ASCII")); int numComponents = cs == null ? 0 : cs.intValue(); return getInstance(data, numComponents); } catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
public static ICC_Profile getInstance(InputStream file) { try { byte[] head = new byte[128]; int remain = head.length; int ptr = 0; while (remain > 0) { int n = file.read(head, ptr, remain); if (n < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain -= n; ptr += n; } if (head[36] != 0x61 || head[37] != 0x63 || head[38] != 0x73 || head[39] != 0x70) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain = (head[0] & 0xff) << 24 | (head[1] & 0xff) << 16 | (head[2] & 0xff) << 8 | head[3] & 0xff; byte[] icc = new byte[remain]; System.arraycopy(head, 0, icc, 0, head.length); remain -= head.length; ptr = head.length; while (remain > 0) { int n = file.read(icc, ptr, remain); if (n < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain -= n; ptr += n; } return getInstance(icc); } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
public static ICC_Profile GetInstance(String fname) { FileInputStream fs = null; try { fs = new FileInputStream(fname); ICC_Profile icc = getInstance(fs); return icc; } catch (Exception ex) { throw new ExceptionConverter(ex); } finally { try{fs.close();}catch(Exception x){} } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
Override void addChar(PdfString mark, PdfObject code) { try { byte[] src = mark.getBytes(); String dest = createStringFromBytes(code.getBytes()); if (src.length == 1) { singleByteMappings.put(Integer.valueOf(src[0] & 0xff), dest); } else if (src.length == 2) { int intSrc = src[0] & 0xFF; intSrc <<= 8; intSrc |= src[1] & 0xFF; doubleByteMappings.put(Integer.valueOf(intSrc), dest); } else { throw new IOException(MessageLocalization.getComposedMessage("mapping.code.should.be.1.or.two.bytes.and.not.1", src.length)); } } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// 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 void setCheckType(int checkType) { if (checkType < TYPE_CHECK || checkType > TYPE_STAR) checkType = TYPE_CIRCLE; this.checkType = checkType; setText(typeChars[checkType - 1]); try { setFont(BaseFont.createFont(BaseFont.ZAPFDINGBATS, BaseFont.WINANSI, false)); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
Override public byte[] convertToBytes(String text) { if (cidDirect) return super.convertToBytes(text); try { if (text.length() == 1) return convertToBytes((int)text.charAt(0)); ByteArrayOutputStream bout = new ByteArrayOutputStream(); for (int k = 0; k < text.length(); ++k) { int val; if (Utilities.isSurrogatePair(text, k)) { val = Utilities.convertToUtf32(text, k); k++; } else { val = text.charAt(k); } bout.write(convertToBytes(val)); } return bout.toByteArray(); } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFont.java
static PdfFont getDefaultFont() { try { BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false); return new PdfFont(bf, 12); } catch (Exception ee) { throw new ExceptionConverter(ee); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode.java
public Image createImageWithBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor) { try { return Image.getInstance(createTemplateWithBarcode(cb, barColor, textColor)); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public void setupAllKeys(byte userPassword[], byte ownerPassword[], int permissions) { if (ownerPassword == null || ownerPassword.length == 0) ownerPassword = md5.digest(createDocumentId()); permissions |= (revision == STANDARD_ENCRYPTION_128 || revision == AES_128 || revision == AES_256) ? 0xfffff0c0 : 0xffffffc0; permissions &= 0xfffffffc; this.permissions = permissions; if (revision == AES_256) { try { if (userPassword == null) userPassword = new byte[0]; documentID = createDocumentId(); byte[] uvs = IVGenerator.getIV(8); byte[] uks = IVGenerator.getIV(8); key = IVGenerator.getIV(32); // Algorithm 3.8.1 MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(userPassword, 0, Math.min(userPassword.length, 127)); md.update(uvs); userKey = new byte[48]; md.digest(userKey, 0, 32); System.arraycopy(uvs, 0, userKey, 32, 8); System.arraycopy(uks, 0, userKey, 40, 8); // Algorithm 3.8.2 md.update(userPassword, 0, Math.min(userPassword.length, 127)); md.update(uks); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(true, md.digest()); ueKey = ac.processBlock(key, 0, key.length); // Algorithm 3.9.1 byte[] ovs = IVGenerator.getIV(8); byte[] oks = IVGenerator.getIV(8); md.update(ownerPassword, 0, Math.min(ownerPassword.length, 127)); md.update(ovs); md.update(userKey); ownerKey = new byte[48]; md.digest(ownerKey, 0, 32); System.arraycopy(ovs, 0, ownerKey, 32, 8); System.arraycopy(oks, 0, ownerKey, 40, 8); // Algorithm 3.9.2 md.update(ownerPassword, 0, Math.min(ownerPassword.length, 127)); md.update(oks); md.update(userKey); ac = new AESCipherCBCnoPad(true, md.digest()); oeKey = ac.processBlock(key, 0, key.length); // Algorithm 3.10 byte[] permsp = IVGenerator.getIV(16); permsp[0] = (byte)permissions; permsp[1] = (byte)(permissions >> 8); permsp[2] = (byte)(permissions >> 16); permsp[3] = (byte)(permissions >> 24); permsp[4] = (byte)(255); permsp[5] = (byte)(255); permsp[6] = (byte)(255); permsp[7] = (byte)(255); permsp[8] = encryptMetadata ? (byte)'T' : (byte)'F'; permsp[9] = (byte)'a'; permsp[10] = (byte)'d'; permsp[11] = (byte)'b'; ac = new AESCipherCBCnoPad(true, key); perms = ac.processBlock(permsp, 0, permsp.length); } catch (Exception ex) { throw new ExceptionConverter(ex); } } else { // PDF reference 3.5.2 Standard Security Handler, Algorithm 3.3-1 // If there is no owner password, use the user password instead. byte userPad[] = padPassword(userPassword); byte ownerPad[] = padPassword(ownerPassword); this.ownerKey = computeOwnerKey(userPad, ownerPad); documentID = createDocumentId(); setupByUserPad(this.documentID, userPad, this.ownerKey, permissions); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public boolean readKey(PdfDictionary enc, byte[] password) throws BadPasswordException { try { if (password == null) password = new byte[0]; byte[] oValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.O).toString()); byte[] uValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.U).toString()); byte[] oeValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.OE).toString()); byte[] ueValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.UE).toString()); byte[] perms = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.PERMS).toString()); boolean isUserPass = false; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); byte[] hash = md.digest(); boolean isOwnerPass = compareArray(hash, oValue, 32); if (isOwnerPass) { md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, KEY_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(oeValue, 0, oeValue.length); } else { md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); isUserPass = compareArray(hash, uValue, 32); if (!isUserPass) throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, KEY_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(ueValue, 0, ueValue.length); } AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, key); byte[] decPerms = ac.processBlock(perms, 0, perms.length); if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b') throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); permissions = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8) | ((decPerms[2] & 0xff) << 16) | ((decPerms[2] & 0xff) << 24); encryptMetadata = decPerms[8] == (byte)'T'; return isOwnerPass; } catch (BadPasswordException ex) { throw ex; } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public static byte[] createDocumentId() { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new ExceptionConverter(e); } long time = System.currentTimeMillis(); long mem = Runtime.getRuntime().freeMemory(); String s = time + "+" + mem + "+" + (seq++); return md5.digest(s.getBytes()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public PdfDictionary getEncryptionDictionary() { PdfDictionary dic = new PdfDictionary(); if (publicKeyHandler.getRecipientsSize() > 0) { PdfArray recipients = null; dic.put(PdfName.FILTER, PdfName.PUBSEC); dic.put(PdfName.R, new PdfNumber(revision)); try { recipients = publicKeyHandler.getEncodedRecipients(); } catch (Exception f) { throw new ExceptionConverter(f); } if (revision == STANDARD_ENCRYPTION_40) { dic.put(PdfName.V, new PdfNumber(1)); dic.put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4); dic.put(PdfName.RECIPIENTS, recipients); } else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata) { dic.put(PdfName.V, new PdfNumber(2)); dic.put(PdfName.LENGTH, new PdfNumber(128)); dic.put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4); dic.put(PdfName.RECIPIENTS, recipients); } else { if (revision == AES_256) { dic.put(PdfName.R, new PdfNumber(AES_256)); dic.put(PdfName.V, new PdfNumber(5)); } else { dic.put(PdfName.R, new PdfNumber(AES_128)); dic.put(PdfName.V, new PdfNumber(4)); } dic.put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S5); PdfDictionary stdcf = new PdfDictionary(); stdcf.put(PdfName.RECIPIENTS, recipients); if (!encryptMetadata) stdcf.put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); if (revision == AES_128) { stdcf.put(PdfName.CFM, PdfName.AESV2); stdcf.put(PdfName.LENGTH, new PdfNumber(128)); } else if (revision == AES_256) { stdcf.put(PdfName.CFM, PdfName.AESV3); stdcf.put(PdfName.LENGTH, new PdfNumber(256)); } else stdcf.put(PdfName.CFM, PdfName.V2); PdfDictionary cf = new PdfDictionary(); cf.put(PdfName.DEFAULTCRYPTFILTER, stdcf); dic.put(PdfName.CF, cf); if (embeddedFilesOnly) { dic.put(PdfName.EFF, PdfName.DEFAULTCRYPTFILTER); dic.put(PdfName.STRF, PdfName.IDENTITY); dic.put(PdfName.STMF, PdfName.IDENTITY); } else { dic.put(PdfName.STRF, PdfName.DEFAULTCRYPTFILTER); dic.put(PdfName.STMF, PdfName.DEFAULTCRYPTFILTER); } } MessageDigest md = null; byte[] encodedRecipient = null; try { if (revision == AES_256) md = MessageDigest.getInstance("SHA-256"); else md = MessageDigest.getInstance("SHA-1"); md.update(publicKeyHandler.getSeed()); for (int i = 0; i < publicKeyHandler.getRecipientsSize(); i++) { encodedRecipient = publicKeyHandler.getEncodedRecipient(i); md.update(encodedRecipient); } if (!encryptMetadata) md.update(new byte[] { (byte) 255, (byte) 255, (byte) 255, (byte) 255 }); } catch (Exception f) { throw new ExceptionConverter(f); } byte[] mdResult = md.digest(); if (revision == AES_256) key = mdResult; else setupByEncryptionKey(mdResult, keyLength); } else { dic.put(PdfName.FILTER, PdfName.STANDARD); dic.put(PdfName.O, new PdfLiteral(PdfContentByte .escapeString(ownerKey))); dic.put(PdfName.U, new PdfLiteral(PdfContentByte .escapeString(userKey))); dic.put(PdfName.P, new PdfNumber(permissions)); dic.put(PdfName.R, new PdfNumber(revision)); if (revision == STANDARD_ENCRYPTION_40) { dic.put(PdfName.V, new PdfNumber(1)); } else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata) { dic.put(PdfName.V, new PdfNumber(2)); dic.put(PdfName.LENGTH, new PdfNumber(128)); } else if (revision == AES_256) { if (!encryptMetadata) dic.put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); dic.put(PdfName.OE, new PdfLiteral(PdfContentByte .escapeString(oeKey))); dic.put(PdfName.UE, new PdfLiteral(PdfContentByte .escapeString(ueKey))); dic.put(PdfName.PERMS, new PdfLiteral(PdfContentByte .escapeString(perms))); dic.put(PdfName.V, new PdfNumber(revision)); dic.put(PdfName.LENGTH, new PdfNumber(256)); PdfDictionary stdcf = new PdfDictionary(); stdcf.put(PdfName.LENGTH, new PdfNumber(32)); if (embeddedFilesOnly) { stdcf.put(PdfName.AUTHEVENT, PdfName.EFOPEN); dic.put(PdfName.EFF, PdfName.STDCF); dic.put(PdfName.STRF, PdfName.IDENTITY); dic.put(PdfName.STMF, PdfName.IDENTITY); } else { stdcf.put(PdfName.AUTHEVENT, PdfName.DOCOPEN); dic.put(PdfName.STRF, PdfName.STDCF); dic.put(PdfName.STMF, PdfName.STDCF); } stdcf.put(PdfName.CFM, PdfName.AESV3); PdfDictionary cf = new PdfDictionary(); cf.put(PdfName.STDCF, stdcf); dic.put(PdfName.CF, cf); } else { if (!encryptMetadata) dic.put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); dic.put(PdfName.R, new PdfNumber(AES_128)); dic.put(PdfName.V, new PdfNumber(4)); dic.put(PdfName.LENGTH, new PdfNumber(128)); PdfDictionary stdcf = new PdfDictionary(); stdcf.put(PdfName.LENGTH, new PdfNumber(16)); if (embeddedFilesOnly) { stdcf.put(PdfName.AUTHEVENT, PdfName.EFOPEN); dic.put(PdfName.EFF, PdfName.STDCF); dic.put(PdfName.STRF, PdfName.IDENTITY); dic.put(PdfName.STMF, PdfName.IDENTITY); } else { stdcf.put(PdfName.AUTHEVENT, PdfName.DOCOPEN); dic.put(PdfName.STRF, PdfName.STDCF); dic.put(PdfName.STMF, PdfName.STDCF); } if (revision == AES_128) stdcf.put(PdfName.CFM, PdfName.AESV2); else stdcf.put(PdfName.CFM, PdfName.V2); PdfDictionary cf = new PdfDictionary(); cf.put(PdfName.STDCF, stdcf); dic.put(PdfName.CF, cf); } } return dic; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public byte[] encryptByteArray(byte[] b) { try { ByteArrayOutputStream ba = new ByteArrayOutputStream(); OutputStreamEncryption os2 = getEncryptionStream(ba); os2.write(b); os2.finish(); return ba.toByteArray(); } catch (IOException ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public byte[] decryptByteArray(byte[] b) { try { ByteArrayOutputStream ba = new ByteArrayOutputStream(); StandardDecryption dec = getDecryptor(); byte[] b2 = dec.update(b, 0, b.length); if (b2 != null) ba.write(b2); b2 = dec.finish(); if (b2 != null) ba.write(b2); return ba.toByteArray(); } catch (IOException ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPageLabels.java
public PdfDictionary getDictionary(PdfWriter writer) { try { return PdfNumberTree.writeTree(map, writer); } catch (IOException e) { throw new ExceptionConverter(e); } }
// 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 initFont() { processToUnicode(); try { //if (toUnicodeCmap == null) processUni2Byte(); spaceWidth = super.getWidth(' '); if (spaceWidth == 0){ spaceWidth = computeAverageWidth(); } if (cjkEncoding != null) { byteCid = CMapCache.getCachedCMapByteCid(cjkEncoding); cidUni = CMapCache.getCachedCMapCidUni(uniMap); } } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
public static X500Name getIssuerFields(X509Certificate cert) { try { return new X500Name((ASN1Sequence)CertificateInfo.getIssuer(cert.getTBSCertificate())); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
public static ASN1Primitive getIssuer(byte[] enc) { try { ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc)); ASN1Sequence seq = (ASN1Sequence)in.readObject(); return (ASN1Primitive)seq.getObjectAt(seq.getObjectAt(0) instanceof ASN1TaggedObject ? 3 : 2); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
public static X500Name getSubjectFields(X509Certificate cert) { try { if (cert != null) return new X500Name((ASN1Sequence)CertificateInfo.getSubject(cert.getTBSCertificate())); } catch (Exception e) { throw new ExceptionConverter(e); } return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
public static ASN1Primitive getSubject(byte[] enc) { try { ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc)); ASN1Sequence seq = (ASN1Sequence)in.readObject(); return (ASN1Primitive)seq.getObjectAt(seq.getObjectAt(0) instanceof ASN1TaggedObject ? 5 : 4); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
public void setExternalDigest(byte digest[], byte RSAdata[], String digestEncryptionAlgorithm) { externalDigest = digest; externalRSAdata = RSAdata; if (digestEncryptionAlgorithm != null) { if (digestEncryptionAlgorithm.equals("RSA")) { this.digestEncryptionAlgorithmOid = SecurityIDs.ID_RSA; } else if (digestEncryptionAlgorithm.equals("DSA")) { this.digestEncryptionAlgorithmOid = SecurityIDs.ID_DSA; } else if (digestEncryptionAlgorithm.equals("ECDSA")) { this.digestEncryptionAlgorithmOid = SecurityIDs.ID_ECDSA; } else throw new ExceptionConverter(new NoSuchAlgorithmException(MessageLocalization.getComposedMessage("unknown.key.algorithm.1", digestEncryptionAlgorithm))); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
public byte[] getEncodedPKCS1() { try { if (externalDigest != null) digest = externalDigest; else digest = sig.sign(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dout = new ASN1OutputStream(bOut); dout.writeObject(new DEROctetString(digest)); dout.close(); return bOut.toByteArray(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
public byte[] getEncodedPKCS7(byte secondDigest[], Calendar signingTime, TSAClient tsaClient, byte[] ocsp, Collection<byte[]> crlBytes, CryptoStandard sigtype) { try { if (externalDigest != null) { digest = externalDigest; if (RSAdata != null) RSAdata = externalRSAdata; } else if (externalRSAdata != null && RSAdata != null) { RSAdata = externalRSAdata; sig.update(RSAdata); digest = sig.sign(); } else { if (RSAdata != null) { RSAdata = messageDigest.digest(); sig.update(RSAdata); } digest = sig.sign(); } // Create the set of Hash algorithms ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector(); for (Object element : digestalgos) { ASN1EncodableVector algos = new ASN1EncodableVector(); algos.add(new ASN1ObjectIdentifier((String)element)); algos.add(DERNull.INSTANCE); digestAlgorithms.add(new DERSequence(algos)); } // Create the contentInfo. ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA)); if (RSAdata != null) v.add(new DERTaggedObject(0, new DEROctetString(RSAdata))); DERSequence contentinfo = new DERSequence(v); // Get all the certificates // v = new ASN1EncodableVector(); for (Object element : certs) { ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(((X509Certificate)element).getEncoded())); v.add(tempstream.readObject()); } DERSet dercertificates = new DERSet(v); // Create signerinfo structure. // ASN1EncodableVector signerinfo = new ASN1EncodableVector(); // Add the signerInfo version // signerinfo.add(new ASN1Integer(signerversion)); v = new ASN1EncodableVector(); v.add(CertificateInfo.getIssuer(signCert.getTBSCertificate())); v.add(new ASN1Integer(signCert.getSerialNumber())); signerinfo.add(new DERSequence(v)); // Add the digestAlgorithm v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(digestAlgorithmOid)); v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // add the authenticated attribute if present if (secondDigest != null && signingTime != null) { signerinfo.add(new DERTaggedObject(false, 0, getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype))); } // Add the digestEncryptionAlgorithm v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(digestEncryptionAlgorithmOid)); v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // Add the digest signerinfo.add(new DEROctetString(digest)); // When requested, go get and add the timestamp. May throw an exception. // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15 // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest if (tsaClient != null) { byte[] tsImprint = tsaClient.getMessageDigest().digest(digest); byte[] tsToken = tsaClient.getTimeStampToken(tsImprint); if (tsToken != null) { ASN1EncodableVector unauthAttributes = buildUnauthenticatedAttributes(tsToken); if (unauthAttributes != null) { signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unauthAttributes))); } } } // Finally build the body out of all the components above ASN1EncodableVector body = new ASN1EncodableVector(); body.add(new ASN1Integer(version)); body.add(new DERSet(digestAlgorithms)); body.add(contentinfo); body.add(new DERTaggedObject(false, 0, dercertificates)); // Only allow one signerInfo body.add(new DERSet(new DERSequence(signerinfo))); // Now we have the body, wrap it in it's PKCS7Signed shell // and return it // ASN1EncodableVector whole = new ASN1EncodableVector(); whole.add(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA)); whole.add(new DERTaggedObject(0, new DERSequence(body))); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dout = new ASN1OutputStream(bOut); dout.writeObject(new DERSequence(whole)); dout.close(); return bOut.toByteArray(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
public byte[] getAuthenticatedAttributeBytes(byte secondDigest[], Calendar signingTime, byte[] ocsp, Collection<byte[]> crlBytes, CryptoStandard sigtype) { try { return getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype).getEncoded(ASN1Encoding.DER); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
private DERSet getAuthenticatedAttributeSet(byte secondDigest[], Calendar signingTime, byte[] ocsp, Collection<byte[]> crlBytes, CryptoStandard sigtype) { try { ASN1EncodableVector attribute = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE)); v.add(new DERSet(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA))); attribute.add(new DERSequence(v)); v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_SIGNING_TIME)); v.add(new DERSet(new DERUTCTime(signingTime.getTime()))); attribute.add(new DERSequence(v)); v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST)); v.add(new DERSet(new DEROctetString(secondDigest))); attribute.add(new DERSequence(v)); boolean haveCrl = false; if (crlBytes != null) { for (byte[] bCrl : crlBytes) { if (bCrl != null) { haveCrl = true; break; } } } if (ocsp != null || haveCrl) { v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION)); ASN1EncodableVector revocationV = new ASN1EncodableVector(); if (haveCrl) { ASN1EncodableVector v2 = new ASN1EncodableVector(); for (byte[] bCrl : crlBytes) { if (bCrl == null) continue; ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(bCrl)); v2.add(t.readObject()); } revocationV.add(new DERTaggedObject(true, 0, new DERSequence(v2))); } if (ocsp != null) { DEROctetString doctet = new DEROctetString(ocsp); ASN1EncodableVector vo1 = new ASN1EncodableVector(); 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))); vo1.add(new DERSequence(v3)); revocationV.add(new DERTaggedObject(true, 1, new DERSequence(vo1))); } v.add(new DERSet(new DERSequence(revocationV))); attribute.add(new DERSequence(v)); } if (sigtype == CryptoStandard.CADES) { v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)); ASN1EncodableVector aaV2 = new ASN1EncodableVector(); AlgorithmIdentifier algoId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(digestAlgorithmOid), null); aaV2.add(algoId); MessageDigest md = interfaceDigest.getMessageDigest(getHashAlgorithm()); byte[] dig = md.digest(signCert.getEncoded()); aaV2.add(new DEROctetString(dig)); v.add(new DERSet(new DERSequence(new DERSequence(new DERSequence(aaV2))))); attribute.add(new DERSequence(v)); } return new DERSet(attribute); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
public static KeyStore loadCacertsKeyStore(String provider) { File file = new File(System.getProperty("java.home"), "lib"); file = new File(file, "security"); file = new File(file, "cacerts"); FileInputStream fin = null; try { fin = new FileInputStream(file); KeyStore k; if (provider == null) k = KeyStore.getInstance("JKS"); else k = KeyStore.getInstance("JKS", provider); k.load(fin, null); return k; } catch (Exception e) { throw new ExceptionConverter(e); } finally { try{if (fin != null) {fin.close();}}catch(Exception ex){} } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Font.java
public BaseFont getCalculatedBaseFont(final boolean specialEncoding) { if (baseFont != null) return baseFont; int style = this.style; if (style == UNDEFINED) { style = NORMAL; } String fontName = BaseFont.HELVETICA; String encoding = BaseFont.WINANSI; BaseFont cfont = null; switch (family) { case COURIER: switch (style & BOLDITALIC) { case BOLD: fontName = BaseFont.COURIER_BOLD; break; case ITALIC: fontName = BaseFont.COURIER_OBLIQUE; break; case BOLDITALIC: fontName = BaseFont.COURIER_BOLDOBLIQUE; break; default: // case NORMAL: fontName = BaseFont.COURIER; break; } break; case TIMES_ROMAN: switch (style & BOLDITALIC) { case BOLD: fontName = BaseFont.TIMES_BOLD; break; case ITALIC: fontName = BaseFont.TIMES_ITALIC; break; case BOLDITALIC: fontName = BaseFont.TIMES_BOLDITALIC; break; default: case NORMAL: fontName = BaseFont.TIMES_ROMAN; break; } break; case SYMBOL: fontName = BaseFont.SYMBOL; if (specialEncoding) encoding = BaseFont.SYMBOL; break; case ZAPFDINGBATS: fontName = BaseFont.ZAPFDINGBATS; if (specialEncoding) encoding = BaseFont.ZAPFDINGBATS; break; default: case HELVETICA: switch (style & BOLDITALIC) { case BOLD: fontName = BaseFont.HELVETICA_BOLD; break; case ITALIC: fontName = BaseFont.HELVETICA_OBLIQUE; break; case BOLDITALIC: fontName = BaseFont.HELVETICA_BOLDOBLIQUE; break; default: case NORMAL: fontName = BaseFont.HELVETICA; break; } break; } try { cfont = BaseFont.createFont(fontName, encoding, false); } catch (Exception ee) { throw new ExceptionConverter(ee); } return cfont; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addHeader(String name, String content) { try { return add(new Header(name, content)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addTitle(String title) { try { return add(new Meta(Element.TITLE, title)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addSubject(String subject) { try { return add(new Meta(Element.SUBJECT, subject)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addKeywords(String keywords) { try { return add(new Meta(Element.KEYWORDS, keywords)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addAuthor(String author) { try { return add(new Meta(Element.AUTHOR, author)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addCreator(String creator) { try { return add(new Meta(Element.CREATOR, creator)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addProducer() { try { return add(new Meta(Element.PRODUCER, Version.getInstance().getVersion())); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addLanguage(String language) { try { return add(new Meta(Element.LANGUAGE, language)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addCreationDate() { try { /* bugfix by 'taqua' (Thomas) */ final SimpleDateFormat sdf = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy"); return add(new Meta(Element.CREATIONDATE, sdf.format(new Date()))); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void startElement(final String tag, final Map<String, String> attrs) { HTMLTagProcessor htmlTag = tags.get(tag); if (htmlTag == null) { return; } // apply the styles to attrs style.applyStyle(tag, attrs); // deal with the style attribute StyleSheet.resolveStyleAttribute(attrs, chain); // process the tag try { htmlTag.startElement(this, tag, attrs); } catch (DocumentException e) { throw new ExceptionConverter(e); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void endElement(final String tag) { HTMLTagProcessor htmlTag = tags.get(tag); if (htmlTag == null) { return; } // process the tag try { htmlTag.endElement(this, tag); } catch (DocumentException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void endDocument() { try { // flush the stack for (int k = 0; k < stack.size(); ++k) document.add(stack.elementAt(k)); // add current paragraph if (currentParagraph != null) document.add(currentParagraph); currentParagraph = null; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
public void close() { open = false; try { os.flush(); if (closeStream) os.close(); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
public void flush() { try { os.flush(); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
public Font getFont(String fontname, final String encoding, final boolean embedded, final float size, int style, final BaseColor color, final boolean cached) { if (fontname == null) return new Font(FontFamily.UNDEFINED, size, style, color); String lowercasefontname = fontname.toLowerCase(); ArrayList<String> tmp = fontFamilies.get(lowercasefontname); if (tmp != null) { // some bugs were fixed here by Daniel Marczisovszky int s = style == Font.UNDEFINED ? Font.NORMAL : style; int fs = Font.NORMAL; boolean found = false; for (String string : tmp) { String f = string; String lcf = f.toLowerCase(); fs = Font.NORMAL; if (lcf.toLowerCase().indexOf("bold") != -1) fs |= Font.BOLD; if (lcf.toLowerCase().indexOf("italic") != -1 || lcf.toLowerCase().indexOf("oblique") != -1) fs |= Font.ITALIC; if ((s & Font.BOLDITALIC) == fs) { fontname = f; found = true; break; } } if (style != Font.UNDEFINED && found) { style &= ~fs; } } BaseFont basefont = null; try { try { // the font is a type 1 font or CJK font basefont = BaseFont.createFont(fontname, encoding, embedded, cached, null, null, true); } catch(DocumentException de) { } if (basefont == null) { // the font is a true type font or an unknown font fontname = trueTypeFonts.get(fontname.toLowerCase()); // the font is not registered as truetype font if (fontname == null) return new Font(FontFamily.UNDEFINED, size, style, color); // the font is registered as truetype font basefont = BaseFont.createFont(fontname, encoding, embedded, cached, null, null); } } catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); } catch(IOException ioe) { // the font is registered as a true type font, but the path was wrong return new Font(FontFamily.UNDEFINED, size, style, color); } catch(NullPointerException npe) { // null was entered as fontname and/or encoding return new Font(FontFamily.UNDEFINED, size, style, color); } return new Font(basefont, size, style, color); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
public void register(final String path, final String alias) { try { if (path.toLowerCase().endsWith(".ttf") || path.toLowerCase().endsWith(".otf") || path.toLowerCase().indexOf(".ttc,") > 0) { Object allNames[] = BaseFont.getAllFontNames(path, BaseFont.WINANSI, null); trueTypeFonts.put(((String)allNames[0]).toLowerCase(), path); if (alias != null) { trueTypeFonts.put(alias.toLowerCase(), path); } // register all the font names with all the locales String[][] names = (String[][])allNames[2]; //full name for (String[] name : names) { trueTypeFonts.put(name[3].toLowerCase(), path); } String fullName = null; String familyName = null; names = (String[][])allNames[1]; //family name for (int k = 0; k < TTFamilyOrder.length; k += 3) { for (String[] name : names) { if (TTFamilyOrder[k].equals(name[0]) && TTFamilyOrder[k + 1].equals(name[1]) && TTFamilyOrder[k + 2].equals(name[2])) { familyName = name[3].toLowerCase(); k = TTFamilyOrder.length; break; } } } if (familyName != null) { String lastName = ""; names = (String[][])allNames[2]; //full name for (String[] name : names) { for (int k = 0; k < TTFamilyOrder.length; k += 3) { if (TTFamilyOrder[k].equals(name[0]) && TTFamilyOrder[k + 1].equals(name[1]) && TTFamilyOrder[k + 2].equals(name[2])) { fullName = name[3]; if (fullName.equals(lastName)) continue; lastName = fullName; registerFamily(familyName, fullName, null); break; } } } } } else if (path.toLowerCase().endsWith(".ttc")) { if (alias != null) LOGGER.error("You can't define an alias for a true type collection."); String[] names = BaseFont.enumerateTTCNames(path); for (int i = 0; i < names.length; i++) { register(path + "," + i); } } else if (path.toLowerCase().endsWith(".afm") || path.toLowerCase().endsWith(".pfm")) { BaseFont bf = BaseFont.createFont(path, BaseFont.CP1252, false); String fullName = bf.getFullFontName()[0][3].toLowerCase(); String familyName = bf.getFamilyFontName()[0][3].toLowerCase(); String psName = bf.getPostscriptFontName().toLowerCase(); registerFamily(familyName, fullName, null); trueTypeFonts.put(psName, path); trueTypeFonts.put(fullName, path); } if (LOGGER.isLogging(Level.TRACE)) { LOGGER.trace(String.format("Registered %s", path)); } } catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
160
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/DefaultFontMapper.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/xmp/XmpReader.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (BadElementException be) { throw new ExceptionConverter(be); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch(DataFormatException dfe) { throw new ExceptionConverter(dfe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEAN.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/SimplePatternParser.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfICCBased.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAcroForm.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPattern.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPCell.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/events/FieldPositioningEvents.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LZWDecoder.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFunction.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfAnnotationsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (SAXException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeQRCode.java
catch (WriterException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (IOException e1) { throw new ExceptionConverter(e1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeCodabar.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RadioCheckField.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFont.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeInter25.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPageLabels.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOffline.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Font.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
0
(Lib) RuntimeException 95
              
// 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 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/TIFFFaxDecoder.java
public void decodeNextScanline(byte[] buffer, int lineOffset, int bitOffset) { int bits = 0, code = 0, isT = 0; int current, entry, twoBits; boolean isWhite = true; // Initialize starting of the changing elements array changingElemSize = 0; // While scanline not complete while (bitOffset < w) { while (isWhite) { // White run current = nextNBits(10); entry = white[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x0f; if (bits == 12) { // Additional Make up code // Get the next 2 bits twoBits = nextLesserThan8Bits(2); // Consolidate the 2 new bits and last 2 bits into 4 bits current = ((current << 2) & 0x000c) | twoBits; entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits bitOffset += code; // Skip white run updatePointer(4 - bits); } else if (bits == 0) { // ERROR throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.encountered")); } else if (bits == 15) { // EOL throw new RuntimeException(MessageLocalization.getComposedMessage("eol.code.word.encountered.in.white.run")); } else { // 11 bits - 0000 0111 1111 1111 = 0x07ff code = (entry >>> 5) & 0x07ff; bitOffset += code; updatePointer(10 - bits); if (isT == 0) { isWhite = false; currChangingElems[changingElemSize++] = bitOffset; } } } // Check whether this run completed one width, if so // advance to next byte boundary for compression = 2. if (bitOffset == w) { if (compression == 2) { advancePointer(); } break; } while (!isWhite) { // Black run current = nextLesserThan8Bits(4); entry = initBlack[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (code == 100) { current = nextNBits(9); entry = black[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (bits == 12) { // Additional makeup codes updatePointer(5); current = nextLesserThan8Bits(4); entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits setToBlack(buffer, lineOffset, bitOffset, code); bitOffset += code; updatePointer(4 - bits); } else if (bits == 15) { // EOL code throw new RuntimeException(MessageLocalization.getComposedMessage("eol.code.word.encountered.in.black.run")); } else { setToBlack(buffer, lineOffset, bitOffset, code); bitOffset += code; updatePointer(9 - bits); if (isT == 0) { isWhite = true; currChangingElems[changingElemSize++] = bitOffset; } } } else if (code == 200) { // Is a Terminating code current = nextLesserThan8Bits(2); entry = twoBitBlack[current]; code = (entry >>> 5) & 0x07ff; bits = (entry >>> 1) & 0x0f; setToBlack(buffer, lineOffset, bitOffset, code); bitOffset += code; updatePointer(2 - bits); isWhite = true; currChangingElems[changingElemSize++] = bitOffset; } else { // Is a Terminating code setToBlack(buffer, lineOffset, bitOffset, code); bitOffset += code; updatePointer(4 - bits); isWhite = true; currChangingElems[changingElemSize++] = bitOffset; } } // Check whether this run completed one width if (bitOffset == w) { if (compression == 2) { advancePointer(); } break; } } currChangingElems[changingElemSize++] = bitOffset; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
public void decode2D(byte[] buffer, byte compData[], int startX, int height, long tiffT4Options) { this.data = compData; compression = 3; bitPointer = 0; bytePointer = 0; int scanlineStride = (w + 7)/8; int a0, a1, b1, b2; int[] b = new int[2]; int entry, code, bits; boolean isWhite; int currIndex = 0; int temp[]; // fillBits - dealt with this in readEOL // 1D/2D encoding - dealt with this in readEOL // uncompressedMode - haven't dealt with this yet. oneD = (int)(tiffT4Options & 0x01); uncompressedMode = (int)((tiffT4Options & 0x02) >> 1); fillBits = (int)((tiffT4Options & 0x04) >> 2); // The data must start with an EOL code if (readEOL(true) != 1) { throw new RuntimeException(MessageLocalization.getComposedMessage("first.scanline.must.be.1d.encoded")); } int lineOffset = 0; int bitOffset; // Then the 1D encoded scanline data will occur, changing elements // array gets set. decodeNextScanline(buffer, lineOffset, startX); lineOffset += scanlineStride; for (int lines = 1; lines < height; lines++) { // Every line must begin with an EOL followed by a bit which // indicates whether the following scanline is 1D or 2D encoded. if (readEOL(false) == 0) { // 2D encoded scanline follows // Initialize previous scanlines changing elements, and // initialize current scanline's changing elements array temp = prevChangingElems; prevChangingElems = currChangingElems; currChangingElems = temp; currIndex = 0; // a0 has to be set just before the start of this scanline. a0 = -1; isWhite = true; bitOffset = startX; lastChangingElement = 0; while (bitOffset < w) { // Get the next changing element getNextChangingElement(a0, isWhite, b); b1 = b[0]; b2 = b[1]; // Get the next seven bits entry = nextLesserThan8Bits(7); // Run these through the 2DCodes table entry = twoDCodes[entry] & 0xff; // Get the code and the number of bits used up code = (entry & 0x78) >>> 3; bits = entry & 0x07; if (code == 0) { if (!isWhite) { setToBlack(buffer, lineOffset, bitOffset, b2 - bitOffset); } bitOffset = a0 = b2; // Set pointer to consume the correct number of bits. updatePointer(7 - bits); } else if (code == 1) { // Horizontal updatePointer(7 - bits); // identify the next 2 codes. int number; if (isWhite) { number = decodeWhiteCodeWord(); bitOffset += number; currChangingElems[currIndex++] = bitOffset; number = decodeBlackCodeWord(); setToBlack(buffer, lineOffset, bitOffset, number); bitOffset += number; currChangingElems[currIndex++] = bitOffset; } else { number = decodeBlackCodeWord(); setToBlack(buffer, lineOffset, bitOffset, number); bitOffset += number; currChangingElems[currIndex++] = bitOffset; number = decodeWhiteCodeWord(); bitOffset += number; currChangingElems[currIndex++] = bitOffset; } a0 = bitOffset; } else if (code <= 8) { // Vertical a1 = b1 + (code - 5); currChangingElems[currIndex++] = a1; // We write the current color till a1 - 1 pos, // since a1 is where the next color starts if (!isWhite) { setToBlack(buffer, lineOffset, bitOffset, a1 - bitOffset); } bitOffset = a0 = a1; isWhite = !isWhite; updatePointer(7 - bits); } else { throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.encountered.while.decoding.2d.group.3.compressed.data")); } } // Add the changing element beyond the current scanline for the // other color too currChangingElems[currIndex++] = bitOffset; changingElemSize = currIndex; } else { // 1D encoded scanline follows decodeNextScanline(buffer, lineOffset, startX); } lineOffset += scanlineStride; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
public void decodeT6(byte[] buffer, byte[] compData, int startX, int height, long tiffT6Options) { this.data = compData; compression = 4; bitPointer = 0; bytePointer = 0; int scanlineStride = (w + 7)/8; int a0, a1, b1, b2; int entry, code, bits; boolean isWhite; int currIndex; int temp[]; // Return values from getNextChangingElement int[] b = new int[2]; // uncompressedMode - have written some code for this, but this // has not been tested due to lack of test images using this optional uncompressedMode = (int)((tiffT6Options & 0x02) >> 1); // Local cached reference int[] cce = currChangingElems; // Assume invisible preceding row of all white pixels and insert // both black and white changing elements beyond the end of this // imaginary scanline. changingElemSize = 0; cce[changingElemSize++] = w; cce[changingElemSize++] = w; int lineOffset = 0; int bitOffset; for (int lines = 0; lines < height; lines++) { // a0 has to be set just before the start of the scanline. a0 = -1; isWhite = true; // Assign the changing elements of the previous scanline to // prevChangingElems and start putting this new scanline's // changing elements into the currChangingElems. temp = prevChangingElems; prevChangingElems = currChangingElems; cce = currChangingElems = temp; currIndex = 0; // Start decoding the scanline at startX in the raster bitOffset = startX; // Reset search start position for getNextChangingElement lastChangingElement = 0; // Till one whole scanline is decoded while (bitOffset < w) { // Get the next changing element getNextChangingElement(a0, isWhite, b); b1 = b[0]; b2 = b[1]; // Get the next seven bits entry = nextLesserThan8Bits(7); // Run these through the 2DCodes table entry = twoDCodes[entry] & 0xff; // Get the code and the number of bits used up code = (entry & 0x78) >>> 3; bits = entry & 0x07; if (code == 0) { // Pass // We always assume WhiteIsZero format for fax. if (!isWhite) { setToBlack(buffer, lineOffset, bitOffset, b2 - bitOffset); } bitOffset = a0 = b2; // Set pointer to only consume the correct number of bits. updatePointer(7 - bits); } else if (code == 1) { // Horizontal // Set pointer to only consume the correct number of bits. updatePointer(7 - bits); // identify the next 2 alternating color codes. int number; if (isWhite) { // Following are white and black runs number = decodeWhiteCodeWord(); bitOffset += number; cce[currIndex++] = bitOffset; number = decodeBlackCodeWord(); setToBlack(buffer, lineOffset, bitOffset, number); bitOffset += number; cce[currIndex++] = bitOffset; } else { // First a black run and then a white run follows number = decodeBlackCodeWord(); setToBlack(buffer, lineOffset, bitOffset, number); bitOffset += number; cce[currIndex++] = bitOffset; number = decodeWhiteCodeWord(); bitOffset += number; cce[currIndex++] = bitOffset; } a0 = bitOffset; } else if (code <= 8) { // Vertical a1 = b1 + (code - 5); cce[currIndex++] = a1; // We write the current color till a1 - 1 pos, // since a1 is where the next color starts if (!isWhite) { setToBlack(buffer, lineOffset, bitOffset, a1 - bitOffset); } bitOffset = a0 = a1; isWhite = !isWhite; updatePointer(7 - bits); } else if (code == 11) { if (nextLesserThan8Bits(3) != 7) { throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.encountered.while.decoding.2d.group.4.compressed.data")); } int zeros = 0; boolean exit = false; while (!exit) { while (nextLesserThan8Bits(1) != 1) { zeros++; } if (zeros > 5) { // Exit code // Zeros before exit code zeros = zeros - 6; if (!isWhite && (zeros > 0)) { cce[currIndex++] = bitOffset; } // Zeros before the exit code bitOffset += zeros; if (zeros > 0) { // Some zeros have been written isWhite = true; } // Read in the bit which specifies the color of // the following run if (nextLesserThan8Bits(1) == 0) { if (!isWhite) { cce[currIndex++] = bitOffset; } isWhite = true; } else { if (isWhite) { cce[currIndex++] = bitOffset; } isWhite = false; } exit = true; } if (zeros == 5) { if (!isWhite) { cce[currIndex++] = bitOffset; } bitOffset += zeros; // Last thing written was white isWhite = true; } else { bitOffset += zeros; cce[currIndex++] = bitOffset; setToBlack(buffer, lineOffset, bitOffset, 1); ++bitOffset; // Last thing written was black isWhite = false; } } } else { //micah_tessler@yahoo.com //Microsoft TIFF renderers seem to treat unknown codes as line-breaks //That is, they give up on the current line and move on to the next one //set bitOffset to w to move on to the next scan line. bitOffset = w; updatePointer(7 - bits); } } // Add the changing element beyond the current scanline for the // other color too //make sure that the index does not exceed the bounds of the array if(currIndex < cce.length) cce[currIndex++] = bitOffset; // Number of changing elements in this scanline. changingElemSize = currIndex; lineOffset += scanlineStride; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
private int decodeWhiteCodeWord() { int current, entry, bits, isT, twoBits, code = -1; int runLength = 0; boolean isWhite = true; while (isWhite) { current = nextNBits(10); entry = white[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x0f; if (bits == 12) { // Additional Make up code // Get the next 2 bits twoBits = nextLesserThan8Bits(2); // Consolidate the 2 new bits and last 2 bits into 4 bits current = ((current << 2) & 0x000c) | twoBits; entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits runLength += code; updatePointer(4 - bits); } else if (bits == 0) { // ERROR throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.encountered")); } else if (bits == 15) { // EOL throw new RuntimeException(MessageLocalization.getComposedMessage("eol.code.word.encountered.in.white.run")); } else { // 11 bits - 0000 0111 1111 1111 = 0x07ff code = (entry >>> 5) & 0x07ff; runLength += code; updatePointer(10 - bits); if (isT == 0) { isWhite = false; } } } return runLength; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
private int decodeBlackCodeWord() { int current, entry, bits, isT, code = -1; int runLength = 0; boolean isWhite = false; while (!isWhite) { current = nextLesserThan8Bits(4); entry = initBlack[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (code == 100) { current = nextNBits(9); entry = black[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (bits == 12) { // Additional makeup codes updatePointer(5); current = nextLesserThan8Bits(4); entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits runLength += code; updatePointer(4 - bits); } else if (bits == 15) { // EOL code throw new RuntimeException(MessageLocalization.getComposedMessage("eol.code.word.encountered.in.black.run")); } else { runLength += code; updatePointer(9 - bits); if (isT == 0) { isWhite = true; } } } else if (code == 200) { // Is a Terminating code current = nextLesserThan8Bits(2); entry = twoBitBlack[current]; code = (entry >>> 5) & 0x07ff; runLength += code; bits = (entry >>> 1) & 0x0f; updatePointer(2 - bits); isWhite = true; } else { // Is a Terminating code runLength += code; updatePointer(4 - bits); isWhite = true; } } return runLength; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
private int readEOL(boolean isFirstEOL) { if (fillBits == 0) { int next12Bits = nextNBits(12); if (isFirstEOL && next12Bits == 0) { // Might have the case of EOL padding being used even // though it was not flagged in the T4Options field. // This was observed to be the case in TIFFs produced // by a well known vendor who shall remain nameless. if(nextNBits(4) == 1) { // EOL must be padded: reset the fillBits flag. fillBits = 1; return 1; } } if(next12Bits != 1) { throw new RuntimeException(MessageLocalization.getComposedMessage("scanline.must.begin.with.eol.code.word")); } } else if (fillBits == 1) { // First EOL code word xxxx 0000 0000 0001 will occur // As many fill bits will be present as required to make // the EOL code of 12 bits end on a byte boundary. int bitsLeft = 8 - bitPointer; if (nextNBits(bitsLeft) != 0) { throw new RuntimeException(MessageLocalization.getComposedMessage("all.fill.bits.preceding.eol.code.must.be.0")); } // If the number of bitsLeft is less than 8, then to have a 12 // bit EOL sequence, two more bytes are certainly going to be // required. The first of them has to be all zeros, so ensure // that. if (bitsLeft < 4) { if (nextNBits(8) != 0) { throw new RuntimeException(MessageLocalization.getComposedMessage("all.fill.bits.preceding.eol.code.must.be.0")); } } // There might be a random number of fill bytes with 0s, so // loop till the EOL of 0000 0001 is found, as long as all // the bytes preceding it are 0's. int n; while ((n = nextNBits(8)) != 1) { // If not all zeros if (n != 0) { throw new RuntimeException(MessageLocalization.getComposedMessage("all.fill.bits.preceding.eol.code.must.be.0")); } } } // If one dimensional encoding mode, then always return 1 if (oneD == 0) { return 1; } else { // Otherwise for 2D encoding mode, // The next one bit signifies 1D/2D encoding of next line. return nextLesserThan8Bits(1); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
private int nextNBits(int bitsToGet) { byte b, next, next2next; int l = data.length - 1; int bp = this.bytePointer; if (fillOrder == 1) { b = data[bp]; if (bp == l) { next = 0x00; next2next = 0x00; } else if ((bp + 1) == l) { next = data[bp + 1]; next2next = 0x00; } else { next = data[bp + 1]; next2next = data[bp + 2]; } } else if (fillOrder == 2) { b = flipTable[data[bp] & 0xff]; if (bp == l) { next = 0x00; next2next = 0x00; } else if ((bp + 1) == l) { next = flipTable[data[bp + 1] & 0xff]; next2next = 0x00; } else { next = flipTable[data[bp + 1] & 0xff]; next2next = flipTable[data[bp + 2] & 0xff]; } } else { throw new RuntimeException(MessageLocalization.getComposedMessage("tiff.fill.order.tag.must.be.either.1.or.2")); } int bitsLeft = 8 - bitPointer; int bitsFromNextByte = bitsToGet - bitsLeft; int bitsFromNext2NextByte = 0; if (bitsFromNextByte > 8) { bitsFromNext2NextByte = bitsFromNextByte - 8; bitsFromNextByte = 8; } bytePointer++; int i1 = (b & table1[bitsLeft]) << (bitsToGet - bitsLeft); int i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte); int i3 = 0; if (bitsFromNext2NextByte != 0) { i2 <<= bitsFromNext2NextByte; i3 = (next2next & table2[bitsFromNext2NextByte]) >>> (8 - bitsFromNext2NextByte); i2 |= i3; bytePointer++; bitPointer = bitsFromNext2NextByte; } else { if (bitsFromNextByte == 8) { bitPointer = 0; bytePointer++; } else { bitPointer = bitsFromNextByte; } } int i = i1 | i2; return i; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
private int nextLesserThan8Bits(int bitsToGet) { byte b, next; int l = data.length - 1; int bp = this.bytePointer; if (fillOrder == 1) { b = data[bp]; if (bp == l) { next = 0x00; } else { next = data[bp + 1]; } } else if (fillOrder == 2) { b = flipTable[data[bp] & 0xff]; if (bp == l) { next = 0x00; } else { next = flipTable[data[bp + 1] & 0xff]; } } else { throw new RuntimeException(MessageLocalization.getComposedMessage("tiff.fill.order.tag.must.be.either.1.or.2")); } int bitsLeft = 8 - bitPointer; int bitsFromNextByte = bitsToGet - bitsLeft; int shift = bitsLeft - bitsToGet; int i1, i2; if (shift >= 0) { i1 = (b & table1[bitsLeft]) >>> shift; bitPointer += bitsToGet; if (bitPointer == 8) { bitPointer = 0; bytePointer++; } } else { i1 = (b & table1[bitsLeft]) << (-shift); i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte); i1 |= i2; bytePointer++; bitPointer = bitsFromNextByte; } return i1; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
void decodePass( int xOffset, int yOffset, int xStep, int yStep, int passWidth, int passHeight) { if ((passWidth == 0) || (passHeight == 0)) { return; } int bytesPerRow = (inputBands*passWidth*bitDepth + 7)/8; byte[] curr = new byte[bytesPerRow]; byte[] prior = new byte[bytesPerRow]; // Decode the (sub)image row-by-row int srcY, dstY; for (srcY = 0, dstY = yOffset; srcY < passHeight; srcY++, dstY += yStep) { // Read the filter type byte and a row of data int filter = 0; try { filter = dataStream.read(); dataStream.readFully(curr, 0, bytesPerRow); } catch (Exception e) { // empty on purpose } switch (filter) { case PNG_FILTER_NONE: break; case PNG_FILTER_SUB: decodeSubFilter(curr, bytesPerRow, bytesPerPixel); break; case PNG_FILTER_UP: decodeUpFilter(curr, prior, bytesPerRow); break; case PNG_FILTER_AVERAGE: decodeAverageFilter(curr, prior, bytesPerRow, bytesPerPixel); break; case PNG_FILTER_PAETH: decodePaethFilter(curr, prior, bytesPerRow, bytesPerPixel); break; default: // Error -- uknown filter type throw new RuntimeException(MessageLocalization.getComposedMessage("png.filter.unknown")); } processPixels(curr, xOffset, xStep, dstY, passWidth); // Swap curr and prior byte[] tmp = prior; prior = curr; curr = tmp; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
public void decodeRaw(byte[] buffer, byte[] compData, int w, int h) { this.buffer = buffer; this.data = compData; this.w = w; this.h = h; this.bitsPerScanline = w; this.lineBitNum = 0; this.bitPointer = 0; this.bytePointer = 0; this.prevChangingElems = new int[w + 1]; this.currChangingElems = new int[w + 1]; fails = 0; try { if (compression == TIFFConstants.COMPRESSION_CCITTRLE) { decodeRLE(); } else if (compression == TIFFConstants.COMPRESSION_CCITTFAX3) { decodeT4(); } else if (compression == TIFFConstants.COMPRESSION_CCITTFAX4) { this.uncompressedMode = (int) ((t6Options & 0x02) >> 1); decodeT6(); } else { throw new RuntimeException("Unknown compression type " + compression); } } catch (ArrayIndexOutOfBoundsException e) { //ignore } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
public void decodeT4() { int height = h; int a0, a1, b1, b2; int[] b = new int[2]; int entry, code, bits, color; boolean isWhite; int currIndex = 0; int temp[]; if (data.length < 2) { throw new RuntimeException("Insufficient data to read initial EOL."); } // The data should start with an EOL code int next12 = nextNBits(12); if (next12 != 1) { ++fails; } updatePointer(12); // Find the first one-dimensionally encoded line. int modeFlag = 0; int lines = -1; // indicates imaginary line before first actual line. while (modeFlag != 1) { try { modeFlag = findNextLine(); lines++; // Normally 'lines' will be 0 on exiting loop. } catch (Exception eofe) { throw new RuntimeException("No reference line present."); } } int bitOffset; // Then the 1D encoded scanline data will occur, changing elements // array gets set. decodeNextScanline(); lines++; lineBitNum += bitsPerScanline; while (lines < height) { // Every line must begin with an EOL followed by a bit which // indicates whether the following scanline is 1D or 2D encoded. try { modeFlag = findNextLine(); } catch (Exception eofe) { ++fails; break; } if (modeFlag == 0) { // 2D encoded scanline follows // Initialize previous scanlines changing elements, and // initialize current scanline's changing elements array temp = prevChangingElems; prevChangingElems = currChangingElems; currChangingElems = temp; currIndex = 0; // a0 has to be set just before the start of this scanline. a0 = -1; isWhite = true; bitOffset = 0; lastChangingElement = 0; while (bitOffset < w) { // Get the next changing element getNextChangingElement(a0, isWhite, b); b1 = b[0]; b2 = b[1]; // Get the next seven bits entry = nextLesserThan8Bits(7); // Run these through the 2DCodes table entry = (int) (twoDCodes[entry] & 0xff); // Get the code and the number of bits used up code = (entry & 0x78) >>> 3; bits = entry & 0x07; if (code == 0) { if (!isWhite) { setToBlack(bitOffset, b2 - bitOffset); } bitOffset = a0 = b2; // Set pointer to consume the correct number of bits. updatePointer(7 - bits); } else if (code == 1) { // Horizontal updatePointer(7 - bits); // identify the next 2 codes. int number; if (isWhite) { number = decodeWhiteCodeWord(); bitOffset += number; currChangingElems[currIndex++] = bitOffset; number = decodeBlackCodeWord(); setToBlack(bitOffset, number); bitOffset += number; currChangingElems[currIndex++] = bitOffset; } else { number = decodeBlackCodeWord(); setToBlack(bitOffset, number); bitOffset += number; currChangingElems[currIndex++] = bitOffset; number = decodeWhiteCodeWord(); bitOffset += number; currChangingElems[currIndex++] = bitOffset; } a0 = bitOffset; } else if (code <= 8) { // Vertical a1 = b1 + (code - 5); currChangingElems[currIndex++] = a1; // We write the current color till a1 - 1 pos, // since a1 is where the next color starts if (!isWhite) { setToBlack(bitOffset, a1 - bitOffset); } bitOffset = a0 = a1; isWhite = !isWhite; updatePointer(7 - bits); } else { ++fails; // Find the next one-dimensionally encoded line. int numLinesTested = 0; while (modeFlag != 1) { try { modeFlag = findNextLine(); numLinesTested++; } catch (Exception eofe) { return; } } lines += numLinesTested - 1; updatePointer(13); break; } } // Add the changing element beyond the current scanline for the // other color too currChangingElems[currIndex++] = bitOffset; changingElemSize = currIndex; } else { // modeFlag == 1 // 1D encoded scanline follows decodeNextScanline(); } lineBitNum += bitsPerScanline; lines++; } // while(lines < height) }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
private int decodeWhiteCodeWord() { int current, entry, bits, isT, twoBits, code = -1; int runLength = 0; boolean isWhite = true; while (isWhite) { current = nextNBits(10); entry = white[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x0f; if (bits == 12) { // Additional Make up code // Get the next 2 bits twoBits = nextLesserThan8Bits(2); // Consolidate the 2 new bits and last 2 bits into 4 bits current = ((current << 2) & 0x000c) | twoBits; entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits runLength += code; updatePointer(4 - bits); } else if (bits == 0) { // ERROR throw new RuntimeException("Error 0"); } else if (bits == 15) { // EOL throw new RuntimeException("Error 1"); } else { // 11 bits - 0000 0111 1111 1111 = 0x07ff code = (entry >>> 5) & 0x07ff; runLength += code; updatePointer(10 - bits); if (isT == 0) { isWhite = false; } } } return runLength; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
private int decodeBlackCodeWord() { int current, entry, bits, isT, twoBits, code = -1; int runLength = 0; boolean isWhite = false; while (!isWhite) { current = nextLesserThan8Bits(4); entry = initBlack[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (code == 100) { current = nextNBits(9); entry = black[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (bits == 12) { // Additional makeup codes updatePointer(5); current = nextLesserThan8Bits(4); entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits runLength += code; updatePointer(4 - bits); } else if (bits == 15) { // EOL code throw new RuntimeException("Error 2"); } else { runLength += code; updatePointer(9 - bits); if (isT == 0) { isWhite = true; } } } else if (code == 200) { // Is a Terminating code current = nextLesserThan8Bits(2); entry = twoBitBlack[current]; code = (entry >>> 5) & 0x07ff; runLength += code; bits = (entry >>> 1) & 0x0f; updatePointer(2 - bits); isWhite = true; } else { // Is a Terminating code runLength += code; updatePointer(4 - bits); isWhite = true; } } return runLength; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
private int findNextLine() { // Set maximum and current bit index into the compressed data. int bitIndexMax = data.length * 8 - 1; int bitIndexMax12 = bitIndexMax - 12; int bitIndex = bytePointer * 8 + bitPointer; // Loop while at least 12 bits are available. while (bitIndex <= bitIndexMax12) { // Get the next 12 bits. int next12Bits = nextNBits(12); bitIndex += 12; // Loop while the 12 bits are not unity, i.e., while the EOL // has not been reached, and there is at least one bit left. while (next12Bits != 1 && bitIndex < bitIndexMax) { next12Bits = ((next12Bits & 0x000007ff) << 1) | (nextLesserThan8Bits(1) & 0x00000001); bitIndex++; } if (next12Bits == 1) { // now positioned just after EOL if (oneD == 1) { // two-dimensional coding if (bitIndex < bitIndexMax) { // check next bit against type of line being sought return nextLesserThan8Bits(1); } } else { return 1; } } } // EOL not found. throw new RuntimeException(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
private int nextNBits(int bitsToGet) { byte b, next, next2next; int l = data.length - 1; int bp = this.bytePointer; if (fillOrder == 1) { b = data[bp]; if (bp == l) { next = 0x00; next2next = 0x00; } else if ((bp + 1) == l) { next = data[bp + 1]; next2next = 0x00; } else { next = data[bp + 1]; next2next = data[bp + 2]; } } else if (fillOrder == 2) { b = flipTable[data[bp] & 0xff]; if (bp == l) { next = 0x00; next2next = 0x00; } else if ((bp + 1) == l) { next = flipTable[data[bp + 1] & 0xff]; next2next = 0x00; } else { next = flipTable[data[bp + 1] & 0xff]; next2next = flipTable[data[bp + 2] & 0xff]; } } else { throw new RuntimeException("Invalid FillOrder"); } int bitsLeft = 8 - bitPointer; int bitsFromNextByte = bitsToGet - bitsLeft; int bitsFromNext2NextByte = 0; if (bitsFromNextByte > 8) { bitsFromNext2NextByte = bitsFromNextByte - 8; bitsFromNextByte = 8; } bytePointer++; int i1 = (b & table1[bitsLeft]) << (bitsToGet - bitsLeft); int i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte); int i3 = 0; if (bitsFromNext2NextByte != 0) { i2 <<= bitsFromNext2NextByte; i3 = (next2next & table2[bitsFromNext2NextByte]) >>> (8 - bitsFromNext2NextByte); i2 |= i3; bytePointer++; bitPointer = bitsFromNext2NextByte; } else { if (bitsFromNextByte == 8) { bitPointer = 0; bytePointer++; } else { bitPointer = bitsFromNextByte; } } int i = i1 | i2; return i; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
private int nextLesserThan8Bits(int bitsToGet) { byte b, next; int l = data.length - 1; int bp = this.bytePointer; if (fillOrder == 1) { b = data[bp]; if (bp == l) { next = 0x00; } else { next = data[bp + 1]; } } else if (fillOrder == 2) { b = flipTable[data[bp] & 0xff]; if (bp == l) { next = 0x00; } else { next = flipTable[data[bp + 1] & 0xff]; } } else { throw new RuntimeException("Invalid FillOrder"); } int bitsLeft = 8 - bitPointer; int bitsFromNextByte = bitsToGet - bitsLeft; int shift = bitsLeft - bitsToGet; int i1, i2; if (shift >= 0) { i1 = (b & table1[bitsLeft]) >>> shift; bitPointer += bitsToGet; if (bitPointer == 8) { bitPointer = 0; bytePointer++; } } else { i1 = (b & table1[bitsLeft]) << (-shift); i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte); i1 |= i2; bytePointer++; bitPointer = bitsFromNextByte; } return i1; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
protected static Image getTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s) { try { int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); int predictor = 1; TIFFLZWDecoder lzwDecoder = null; switch (compression) { case TIFFConstants.COMPRESSION_NONE: case TIFFConstants.COMPRESSION_LZW: case TIFFConstants.COMPRESSION_PACKBITS: case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: case TIFFConstants.COMPRESSION_OJPEG: case TIFFConstants.COMPRESSION_JPEG: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.compression.1.is.not.supported", compression)); } int photometric = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); switch (photometric) { case TIFFConstants.PHOTOMETRIC_MINISWHITE: case TIFFConstants.PHOTOMETRIC_MINISBLACK: case TIFFConstants.PHOTOMETRIC_RGB: case TIFFConstants.PHOTOMETRIC_SEPARATED: case TIFFConstants.PHOTOMETRIC_PALETTE: break; default: if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.photometric.1.is.not.supported", photometric)); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } if (dir.isTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) && dir.getFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("planar.images.are.not.supported")); int extraSamples = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES)) extraSamples = 1; int samplePerPixel = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4 samplePerPixel = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL); int bitsPerSample = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE)) bitsPerSample = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE); switch (bitsPerSample) { case 1: case 2: case 4: case 8: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample)); } Image img = null; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); int fillOrder = 1; boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE) { TIFFField predictorField = dir.getField(TIFFConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.getAsInt(0); if (predictor != 1 && predictor != 2) { throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.value.for.predictor.in.tiff.file")); } if (predictor == 2 && bitsPerSample != 8) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample)); } } } if (compression == TIFFConstants.COMPRESSION_LZW) { lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel); } int rowsLeft = h; ByteArrayOutputStream stream = null; ByteArrayOutputStream mstream = null; DeflaterOutputStream zip = null; DeflaterOutputStream mzip = null; if (extraSamples > 0) { mstream = new ByteArrayOutputStream(); mzip = new DeflaterOutputStream(mstream); } CCITTG4Encoder g4 = null; if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4 = new CCITTG4Encoder(w); } else { stream = new ByteArrayOutputStream(); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) zip = new DeflaterOutputStream(stream); } if (compression == TIFFConstants.COMPRESSION_OJPEG) { // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and // is often missing if ((!dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET))) { throw new IOException(MessageLocalization.getComposedMessage("missing.tag.s.for.ojpeg.compression")); } int jpegOffset = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET); int jpegLength = (int)s.length() - jpegOffset; if (dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT)) { jpegLength = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0]; } byte[] jpeg = new byte[Math.min(jpegLength, (int)s.length() - jpegOffset)]; int posFilePointer = (int)s.getFilePointer(); posFilePointer += jpegOffset; s.seek(posFilePointer); s.readFully(jpeg); img = new Jpeg(jpeg); } else if (compression == TIFFConstants.COMPRESSION_JPEG) { if (size.length > 1) throw new IOException(MessageLocalization.getComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.length)); byte[] jpeg = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(jpeg); // if quantization and/or Huffman tables are stored separately in the tiff, // we need to add them to the jpeg data TIFFField jpegtables = dir.getField(TIFFConstants.TIFFTAG_JPEGTABLES); if (jpegtables != null) { byte[] temp = jpegtables.getAsBytes(); int tableoffset = 0; int tablelength = temp.length; // remove FFD8 from start if (temp[0] == (byte) 0xFF && temp[1] == (byte) 0xD8) { tableoffset = 2; tablelength -= 2; } // remove FFD9 from end if (temp[temp.length-2] == (byte) 0xFF && temp[temp.length-1] == (byte) 0xD9) tablelength -= 2; byte[] tables = new byte[tablelength]; System.arraycopy(temp, tableoffset, tables, 0, tablelength); // TODO insert after JFIF header, instead of at the start byte[] jpegwithtables = new byte[jpeg.length + tables.length]; System.arraycopy(jpeg, 0, jpegwithtables, 0, 2); System.arraycopy(tables, 0, jpegwithtables, 2, tables.length); System.arraycopy(jpeg, 2, jpegwithtables, tables.length+2, jpeg.length-2); jpeg = jpegwithtables; } img = new Jpeg(jpeg); } else { for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); byte outBuf[] = null; if (compression != TIFFConstants.COMPRESSION_NONE) outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height]; if (reverse) TIFFFaxDecoder.reverseBits(im); switch (compression) { case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: inflate(im, outBuf); applyPredictor(outBuf, predictor, w, height, samplePerPixel); break; case TIFFConstants.COMPRESSION_NONE: outBuf = im; break; case TIFFConstants.COMPRESSION_PACKBITS: decodePackbits(im, outBuf); break; case TIFFConstants.COMPRESSION_LZW: lzwDecoder.decode(im, outBuf, height); break; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4.fax4Encode(outBuf, height); } else { if (extraSamples > 0) ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height); else zip.write(outBuf); } rowsLeft -= rowsStrip; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { img = Image.getInstance(w, h, false, Image.CCITTG4, photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.close()); } else { zip.close(); img = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.toByteArray()); img.setDeflated(true); } } img.setDpi(dpiX, dpiY); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) { if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (samplePerPixel - extraSamples == icc_prof.getNumComponents()) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } if (dir.isTagPresent(TIFFConstants.TIFFTAG_COLORMAP)) { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_COLORMAP); char rgb[] = fd.getAsChars(); byte palette[] = new byte[rgb.length]; int gColor = rgb.length / 3; int bColor = gColor * 2; for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)(rgb[k] >>> 8); palette[k * 3 + 1] = (byte)(rgb[k + gColor] >>> 8); palette[k * 3 + 2] = (byte)(rgb[k + bColor] >>> 8); } // Colormap components are supposed to go from 0 to 655535 but, // as usually, some tiff producers just put values from 0 to 255. // Let's check for these broken tiffs. boolean colormapBroken = true; for (int k = 0; k < palette.length; ++k) { if (palette[k] != 0) { colormapBroken = false; break; } } if (colormapBroken) { for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)rgb[k]; palette[k * 3 + 1] = (byte)rgb[k + gColor]; palette[k * 3 + 2] = (byte)rgb[k + bColor]; } } PdfArray indexed = new PdfArray(); indexed.add(PdfName.INDEXED); indexed.add(PdfName.DEVICERGB); indexed.add(new PdfNumber(gColor - 1)); indexed.add(new PdfString(palette)); PdfDictionary additional = new PdfDictionary(); additional.put(PdfName.COLORSPACE, indexed); img.setAdditional(additional); } img.setOriginalType(Image.ORIGINAL_TIFF); } if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE) img.setInverted(true); if (rotation != 0) img.setInitialRotation(rotation); if (extraSamples > 0) { mzip.close(); Image mimg = Image.getInstance(w, h, 1, bitsPerSample, mstream.toByteArray()); mimg.makeMask(); mimg.setDeflated(true); img.setImageMask(mimg); } return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
public void startElement(String tag, Map<String, String> h) { if (topList == null) { if (tag.equals("Bookmark")) { topList = new ArrayList<HashMap<String, Object>>(); return; } else throw new RuntimeException(MessageLocalization.getComposedMessage("root.element.is.not.bookmark.1", tag)); } if (!tag.equals("Title")) throw new RuntimeException(MessageLocalization.getComposedMessage("tag.1.not.allowed", tag)); HashMap<String, Object> attributes = new HashMap<String, Object>(h); attributes.put("Title", ""); attributes.remove("Kids"); attr.push(attributes); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEAN.java
public Rectangle getBarcodeSize() { float width = 0; float height = barHeight; if (font != null) { if (baseline <= 0) height += -baseline + size; else height += baseline - font.getFontDescriptor(BaseFont.DESCENT, size); } switch (codeType) { case EAN13: width = x * (11 + 12 * 7); if (font != null) { width += font.getWidthPoint(code.charAt(0), size); } break; case EAN8: width = x * (11 + 8 * 7); break; case UPCA: width = x * (11 + 12 * 7); if (font != null) { width += font.getWidthPoint(code.charAt(0), size) + font.getWidthPoint(code.charAt(11), size); } break; case UPCE: width = x * (9 + 6 * 7); if (font != null) { width += font.getWidthPoint(code.charAt(0), size) + font.getWidthPoint(code.charAt(7), size); } break; case SUPP2: width = x * (6 + 2 * 7); break; case SUPP5: width = x * (4 + 5 * 7 + 4 * 2); break; default: throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.type")); } return new Rectangle(width, height); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEAN.java
public java.awt.Image createAwtImage(java.awt.Color foreground, java.awt.Color background) { int f = foreground.getRGB(); int g = background.getRGB(); java.awt.Canvas canvas = new java.awt.Canvas(); int width = 0; byte bars[] = null; switch (codeType) { case EAN13: bars = getBarsEAN13(code); width = 11 + 12 * 7; break; case EAN8: bars = getBarsEAN8(code); width = 11 + 8 * 7; break; case UPCA: bars = getBarsEAN13("0" + code); width = 11 + 12 * 7; break; case UPCE: bars = getBarsUPCE(code); width = 9 + 6 * 7; break; case SUPP2: bars = getBarsSupplemental2(code); width = 6 + 2 * 7; break; case SUPP5: bars = getBarsSupplemental5(code); width = 4 + 5 * 7 + 4 * 2; break; default: throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.type")); } boolean print = true; int ptr = 0; int height = (int)barHeight; int pix[] = new int[width * height]; for (int k = 0; k < bars.length; ++k) { int w = bars[k]; int c = g; if (print) c = f; print = !print; for (int j = 0; j < w; ++j) pix[ptr++] = c; } for (int k = width; k < pix.length; k += width) { System.arraycopy(pix, 0, pix, k, width); } java.awt.Image img = canvas.createImage(new java.awt.image.MemoryImageSource(width, height, pix, 0, width)); return img; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSpotColor.java
protected PdfObject getSpotObject(PdfWriter writer) { PdfArray array = new PdfArray(PdfName.SEPARATION); array.add(name); PdfFunction func = null; if (altcs instanceof ExtendedColor) { int type = ((ExtendedColor)altcs).type; switch (type) { case ExtendedColor.TYPE_GRAY: array.add(PdfName.DEVICEGRAY); func = PdfFunction.type2(writer, new float[]{0, 1}, null, new float[]{0}, new float[]{((GrayColor)altcs).getGray()}, 1); break; case ExtendedColor.TYPE_CMYK: array.add(PdfName.DEVICECMYK); CMYKColor cmyk = (CMYKColor)altcs; func = PdfFunction.type2(writer, new float[]{0, 1}, null, new float[]{0, 0, 0, 0}, new float[]{cmyk.getCyan(), cmyk.getMagenta(), cmyk.getYellow(), cmyk.getBlack()}, 1); break; default: throw new RuntimeException(MessageLocalization.getComposedMessage("only.rgb.gray.and.cmyk.are.supported.as.alternative.color.spaces")); } } else { array.add(PdfName.DEVICERGB); func = PdfFunction.type2(writer, new float[]{0, 1}, null, new float[]{1, 1, 1}, new float[]{(float)altcs.getRed() / 255, (float)altcs.getGreen() / 255, (float)altcs.getBlue() / 255}, 1); } array.add(func.getReference()); return array; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
protected ArrayList<float []> convertColumn(final float cLine[]) { if (cLine.length < 4) throw new RuntimeException(MessageLocalization.getComposedMessage("no.valid.column.line.found")); ArrayList<float []> cc = new ArrayList<float []>(); for (int k = 0; k < cLine.length - 2; k += 2) { float x1 = cLine[k]; float y1 = cLine[k + 1]; float x2 = cLine[k + 2]; float y2 = cLine[k + 3]; if (y1 == y2) continue; // x = ay + b float a = (x1 - x2) / (y1 - y2); float b = x1 - a * y1; float r[] = new float[4]; r[0] = Math.min(y1, y2); r[1] = Math.max(y1, y2); r[2] = a; r[3] = b; cc.add(r); maxY = Math.max(maxY, r[1]); minY = Math.min(minY, r[0]); } if (cc.isEmpty()) throw new RuntimeException(MessageLocalization.getComposedMessage("no.valid.column.line.found")); return cc; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public void setRunDirection(final int runDirection) { if (runDirection < PdfWriter.RUN_DIRECTION_DEFAULT || runDirection > PdfWriter.RUN_DIRECTION_RTL) throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.run.direction.1", runDirection)); this.runDirection = runDirection; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setFieldProperty(String field, String name, Object value, int inst[]) { if (writer == null) throw new RuntimeException(MessageLocalization.getComposedMessage("this.acrofields.instance.is.read.only")); try { Item item = fields.get(field); if (item == null) return false; InstHit hit = new InstHit(inst); PdfDictionary merged; PdfString da; if (name.equalsIgnoreCase("textfont")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); PdfDictionary dr = merged.getAsDict(PdfName.DR); if (da != null) { if (dr == null) { dr = new PdfDictionary(); merged.put(PdfName.DR, dr); } Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { BaseFont bf = (BaseFont)value; PdfName psn = PdfAppearance.stdFieldFontNames.get(bf.getPostscriptFontName()); if (psn == null) { psn = new PdfName(bf.getPostscriptFontName()); } PdfDictionary fonts = dr.getAsDict(PdfName.FONT); if (fonts == null) { fonts = new PdfDictionary(); dr.put(PdfName.FONT, fonts); } PdfIndirectReference fref = (PdfIndirectReference)fonts.get(psn); PdfDictionary top = reader.getCatalog().getAsDict(PdfName.ACROFORM); markUsed(top); dr = top.getAsDict(PdfName.DR); if (dr == null) { dr = new PdfDictionary(); top.put(PdfName.DR, dr); } markUsed(dr); PdfDictionary fontsTop = dr.getAsDict(PdfName.FONT); if (fontsTop == null) { fontsTop = new PdfDictionary(); dr.put(PdfName.FONT, fontsTop); } markUsed(fontsTop); PdfIndirectReference frefTop = (PdfIndirectReference)fontsTop.get(psn); if (frefTop != null) { if (fref == null) fonts.put(psn, frefTop); } else if (fref == null) { FontDetails fd; if (bf.getFontType() == BaseFont.FONT_TYPE_DOCUMENT) { fd = new FontDetails(null, ((DocumentFont)bf).getIndirectReference(), bf); } else { bf.setSubset(false); fd = writer.addSimple(bf); localFonts.put(psn.toString().substring(1), bf); } fontsTop.put(psn, fd.getIndirectReference()); fonts.put(psn, fd.getIndirectReference()); } ByteBuffer buf = cb.getInternalBuffer(); buf.append(psn.getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf "); if (dao[DA_COLOR] != null) cb.setColorFill((BaseColor)dao[DA_COLOR]); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("textcolor")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); if (da != null) { Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { ByteBuffer buf = cb.getInternalBuffer(); buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf "); cb.setColorFill((BaseColor)value); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("textsize")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); if (da != null) { Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { ByteBuffer buf = cb.getInternalBuffer(); buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)value).floatValue()).append(" Tf "); if (dao[DA_COLOR] != null) cb.setColorFill((BaseColor)dao[DA_COLOR]); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("bgcolor") || name.equalsIgnoreCase("bordercolor")) { PdfName dname = name.equalsIgnoreCase("bgcolor") ? PdfName.BG : PdfName.BC; for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); PdfDictionary mk = merged.getAsDict(PdfName.MK); if (mk == null) { if (value == null) return true; mk = new PdfDictionary(); item.getMerged(k).put(PdfName.MK, mk); item.getWidget(k).put(PdfName.MK, mk); markUsed(item.getWidget(k)); } else { markUsed( mk ); } if (value == null) mk.remove(dname); else mk.put(dname, PdfFormField.getMKColor((BaseColor)value)); } } } else return false; return true; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setFieldProperty(String field, String name, int value, int inst[]) { if (writer == null) throw new RuntimeException(MessageLocalization.getComposedMessage("this.acrofields.instance.is.read.only")); Item item = fields.get(field); if (item == null) return false; InstHit hit = new InstHit(inst); if (name.equalsIgnoreCase("flags")) { PdfNumber num = new PdfNumber(value); for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { item.getMerged(k).put(PdfName.F, num); item.getWidget(k).put(PdfName.F, num); markUsed(item.getWidget(k)); } } } else if (name.equalsIgnoreCase("setflags")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { PdfNumber num = item.getWidget(k).getAsNumber(PdfName.F); int val = 0; if (num != null) val = num.intValue(); num = new PdfNumber(val | value); item.getMerged(k).put(PdfName.F, num); item.getWidget(k).put(PdfName.F, num); markUsed(item.getWidget(k)); } } } else if (name.equalsIgnoreCase("clrflags")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { PdfDictionary widget = item.getWidget( k ); PdfNumber num = widget.getAsNumber(PdfName.F); int val = 0; if (num != null) val = num.intValue(); num = new PdfNumber(val & ~value); item.getMerged(k).put(PdfName.F, num); widget.put(PdfName.F, num); markUsed(widget); } } } else if (name.equalsIgnoreCase("fflags")) { PdfNumber num = new PdfNumber(value); for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { item.getMerged(k).put(PdfName.FF, num); item.getValue(k).put(PdfName.FF, num); markUsed(item.getValue(k)); } } } else if (name.equalsIgnoreCase("setfflags")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { PdfDictionary valDict = item.getValue( k ); PdfNumber num = valDict.getAsNumber( PdfName.FF ); int val = 0; if (num != null) val = num.intValue(); num = new PdfNumber(val | value); item.getMerged(k).put(PdfName.FF, num); valDict.put(PdfName.FF, num); markUsed(valDict); } } } else if (name.equalsIgnoreCase("clrfflags")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { PdfDictionary valDict = item.getValue( k ); PdfNumber num = valDict.getAsNumber(PdfName.FF); int val = 0; if (num != null) val = num.intValue(); num = new PdfNumber(val & ~value); item.getMerged(k).put(PdfName.FF, num); valDict.put(PdfName.FF, num); markUsed(valDict); } } } else return false; return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
public void endElement(String tag) { if (tag.equals("Destination")) { if (xmlLast == null && xmlNames != null) return; else throw new RuntimeException(MessageLocalization.getComposedMessage("destination.end.tag.out.of.place")); } if (!tag.equals("Name")) throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.end.tag.1", tag)); if (xmlLast == null || xmlNames == null) throw new RuntimeException(MessageLocalization.getComposedMessage("name.end.tag.out.of.place")); if (!xmlLast.containsKey("Page")) throw new RuntimeException(MessageLocalization.getComposedMessage("page.attribute.missing")); xmlNames.put(unEscapeBinaryString(xmlLast.get("Name")), xmlLast.get("Page")); xmlLast = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
public void startElement(String tag, Map<String, String> h) { if (xmlNames == null) { if (tag.equals("Destination")) { xmlNames = new HashMap<String, String>(); return; } else throw new RuntimeException(MessageLocalization.getComposedMessage("root.element.is.not.destination")); } if (!tag.equals("Name")) throw new RuntimeException(MessageLocalization.getComposedMessage("tag.1.not.allowed", tag)); if (xmlLast != null) throw new RuntimeException(MessageLocalization.getComposedMessage("nested.tags.are.not.allowed")); xmlLast = new HashMap<String, String>(h); xmlLast.put("Name", ""); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
public void flateCompress(int compressionLevel) { if (!Document.compress) return; // check if the flateCompress-method has already been if (compressed) { return; } this.compressionLevel = compressionLevel; if (inputStream != null) { compressed = true; return; } // check if a filter already exists PdfObject filter = PdfReader.getPdfObject(get(PdfName.FILTER)); if (filter != null) { if (filter.isName()) { if (PdfName.FLATEDECODE.equals(filter)) return; } else if (filter.isArray()) { if (((PdfArray) filter).contains(PdfName.FLATEDECODE)) return; } else { throw new RuntimeException(MessageLocalization.getComposedMessage("stream.could.not.be.compressed.filter.is.not.a.name.or.array")); } } try { // compress ByteArrayOutputStream stream = new ByteArrayOutputStream(); Deflater deflater = new Deflater(compressionLevel); DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater); if (streamBytes != null) streamBytes.writeTo(zip); else zip.write(bytes); zip.close(); deflater.end(); // update the object streamBytes = stream; bytes = null; put(PdfName.LENGTH, new PdfNumber(streamBytes.size())); if (filter == null) { put(PdfName.FILTER, PdfName.FLATEDECODE); } else { PdfArray filters = new PdfArray(filter); filters.add(PdfName.FLATEDECODE); put(PdfName.FILTER, filters); } compressed = true; } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
void setLinearMode(PdfIndirectReference topParent) { if (parents.size() > 1) throw new RuntimeException(MessageLocalization.getComposedMessage("linear.page.mode.can.only.be.called.with.a.single.parent")); if (topParent != null) { this.topParent = topParent; parents.clear(); parents.add(topParent); } leafSize = 10000000; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAction.java
static PdfArray buildArray(Object names[]) { PdfArray array = new PdfArray(); for (int k = 0; k < names.length; ++k) { Object obj = names[k]; if (obj instanceof String) array.add(new PdfString((String)obj)); else if (obj instanceof PdfAnnotation) array.add(((PdfAnnotation)obj).getIndirectReference()); else throw new RuntimeException(MessageLocalization.getComposedMessage("the.array.must.contain.string.or.pdfannotation")); } return array; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfContentByte getDirectContent() { if (!open) throw new RuntimeException(MessageLocalization.getComposedMessage("the.document.is.not.open")); return directContent; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfContentByte getDirectContentUnder() { if (!open) throw new RuntimeException(MessageLocalization.getComposedMessage("the.document.is.not.open")); return directContentUnder; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Override public void close() { if (open) { if (currentPageNumber - 1 != pageReferences.size()) throw new RuntimeException("The page " + pageReferences.size() + " was requested but the document has only " + (currentPageNumber - 1) + " pages."); pdf.close(); try { addSharedObjectsToBody(); for (PdfOCG layer : documentOCG) { addToBody(layer.getPdfObject(), layer.getRef()); } // add the root to the body PdfIndirectReference rootRef = root.writePageTree(); // make the catalog-object and add it to the body PdfDictionary catalog = getCatalog(rootRef); // [C9] if there is XMP data to add: add it if (xmpMetadata != null) { PdfStream xmp = new PdfStream(xmpMetadata); 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); } catalog.put(PdfName.METADATA, body.add(xmp).getIndirectReference()); } // [C10] make pdfx conformant if (isPdfX()) { completeInfoDictionary(getInfo()); completeExtraCatalog(getExtraCatalog()); } // [C11] Output Intents if (extraCatalog != null) { catalog.mergeDifferent(extraCatalog); } writeOutlines(catalog, false); // add the Catalog to the body PdfIndirectObject indirectCatalog = addToBody(catalog, false); // add the info-object to the body PdfIndirectObject infoObj = addToBody(getInfo(), false); // [F1] encryption PdfIndirectReference encryption = null; PdfObject fileID = null; body.flushObjStm(); if (crypto != null) { PdfIndirectObject encryptionObject = addToBody(crypto.getEncryptionDictionary(), false); encryption = encryptionObject.getIndirectReference(); fileID = crypto.getFileID(); } else fileID = PdfEncryption.createInfoId(PdfEncryption.createDocumentId()); // write the cross-reference table of the body body.writeCrossReferenceTable(os, indirectCatalog.getIndirectReference(), infoObj.getIndirectReference(), encryption, fileID, prevxref); // make the trailer // [F2] full compression 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(), indirectCatalog.getIndirectReference(), infoObj.getIndirectReference(), encryption, fileID, prevxref); trailer.toPdf(this, os); } super.close(); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setRunDirection(final int runDirection) { if (runDirection < RUN_DIRECTION_NO_BIDI || runDirection > RUN_DIRECTION_RTL) throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.run.direction.1", runDirection)); this.runDirection = runDirection; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
ColorDetails addSimplePatternColorspace(final BaseColor color) { int type = ExtendedColor.getType(color); if (type == ExtendedColor.TYPE_PATTERN || type == ExtendedColor.TYPE_SHADING) throw new RuntimeException(MessageLocalization.getComposedMessage("an.uncolored.tile.pattern.can.not.have.another.pattern.or.shading.as.color")); try { switch (type) { case ExtendedColor.TYPE_RGB: if (patternColorspaceRGB == null) { patternColorspaceRGB = new ColorDetails(getColorspaceName(), body.getPdfIndirectReference(), null); PdfArray array = new PdfArray(PdfName.PATTERN); array.add(PdfName.DEVICERGB); addToBody(array, patternColorspaceRGB.getIndirectReference()); } return patternColorspaceRGB; case ExtendedColor.TYPE_CMYK: if (patternColorspaceCMYK == null) { patternColorspaceCMYK = new ColorDetails(getColorspaceName(), body.getPdfIndirectReference(), null); PdfArray array = new PdfArray(PdfName.PATTERN); array.add(PdfName.DEVICECMYK); addToBody(array, patternColorspaceCMYK.getIndirectReference()); } return patternColorspaceCMYK; case ExtendedColor.TYPE_GRAY: if (patternColorspaceGRAY == null) { patternColorspaceGRAY = new ColorDetails(getColorspaceName(), body.getPdfIndirectReference(), null); PdfArray array = new PdfArray(PdfName.PATTERN); array.add(PdfName.DEVICEGRAY); addToBody(array, patternColorspaceGRAY.getIndirectReference()); } return patternColorspaceGRAY; case ExtendedColor.TYPE_SEPARATION: { ColorDetails details = addSimple(((SpotColor)color).getPdfSpotColor()); ColorDetails patternDetails = documentSpotPatterns.get(details); if (patternDetails == null) { patternDetails = new ColorDetails(getColorspaceName(), body.getPdfIndirectReference(), null); PdfArray array = new PdfArray(PdfName.PATTERN); array.add(details.getIndirectReference()); addToBody(array, patternDetails.getIndirectReference()); documentSpotPatterns.put(details, patternDetails); } return patternDetails; } default: throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.color.type")); } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImportedPage.java
void throwError() { throw new RuntimeException(MessageLocalization.getComposedMessage("content.can.not.be.added.to.a.pdfimportedpage")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
public void setRunDirection(int runDirection) { if (runDirection < PdfWriter.RUN_DIRECTION_DEFAULT || runDirection > PdfWriter.RUN_DIRECTION_RTL) throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.run.direction.1", runDirection)); this.runDirection = runDirection; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void insertPage(int pageNumber, Rectangle mediabox) { Rectangle media = new Rectangle(mediabox); int rotation = media.getRotation() % 360; PdfDictionary page = new PdfDictionary(PdfName.PAGE); PdfDictionary resources = new PdfDictionary(); PdfArray procset = new PdfArray(); procset.add(PdfName.PDF); procset.add(PdfName.TEXT); procset.add(PdfName.IMAGEB); procset.add(PdfName.IMAGEC); procset.add(PdfName.IMAGEI); resources.put(PdfName.PROCSET, procset); page.put(PdfName.RESOURCES, resources); page.put(PdfName.ROTATE, new PdfNumber(rotation)); page.put(PdfName.MEDIABOX, new PdfRectangle(media, rotation)); PRIndirectReference pref = reader.addPdfObject(page); PdfDictionary parent; PRIndirectReference parentRef; if (pageNumber > reader.getNumberOfPages()) { PdfDictionary lastPage = reader.getPageNRelease(reader.getNumberOfPages()); parentRef = (PRIndirectReference)lastPage.get(PdfName.PARENT); parentRef = new PRIndirectReference(reader, parentRef.getNumber()); parent = (PdfDictionary)PdfReader.getPdfObject(parentRef); PdfArray kids = (PdfArray)PdfReader.getPdfObject(parent.get(PdfName.KIDS), parent); kids.add(pref); markUsed(kids); reader.pageRefs.insertPage(pageNumber, pref); } else { if (pageNumber < 1) pageNumber = 1; PdfDictionary firstPage = reader.getPageN(pageNumber); PRIndirectReference firstPageRef = reader.getPageOrigRef(pageNumber); reader.releasePage(pageNumber); parentRef = (PRIndirectReference)firstPage.get(PdfName.PARENT); parentRef = new PRIndirectReference(reader, parentRef.getNumber()); parent = (PdfDictionary)PdfReader.getPdfObject(parentRef); PdfArray kids = (PdfArray)PdfReader.getPdfObject(parent.get(PdfName.KIDS), parent); int len = kids.size(); int num = firstPageRef.getNumber(); for (int k = 0; k < len; ++k) { PRIndirectReference cur = (PRIndirectReference)kids.getPdfObject(k); if (num == cur.getNumber()) { kids.add(k, pref); break; } } if (len == kids.size()) throw new RuntimeException(MessageLocalization.getComposedMessage("internal.inconsistence")); markUsed(kids); reader.pageRefs.insertPage(pageNumber, pref); correctAcroFieldPages(pageNumber); } page.put(PdfName.PARENT, parentRef); while (parent != null) { markUsed(parent); PdfNumber count = (PdfNumber)PdfReader.getPdfObjectRelease(parent.get(PdfName.COUNT)); parent.put(PdfName.COUNT, new PdfNumber(count.intValue() + 1)); parent = parent.getAsDict(PdfName.PARENT); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void addAnnotation(PdfAnnotation annot) { throw new RuntimeException(MessageLocalization.getComposedMessage("unsupported.in.this.context.use.pdfstamper.addannotation")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfShadingPattern.java
public void setMatrix(float matrix[]) { if (matrix.length != 6) throw new RuntimeException(MessageLocalization.getComposedMessage("the.matrix.size.must.be.6")); this.matrix = matrix; }
// 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/LZWDecoder.java
public void decode(byte data[], OutputStream uncompData) { if(data[0] == (byte)0x00 && data[1] == (byte)0x01) { throw new RuntimeException(MessageLocalization.getComposedMessage("lzw.flavour.not.supported")); } initializeStringTable(); this.data = data; this.uncompData = uncompData; // Initialize pointers bytePointer = 0; bitPointer = 0; nextData = 0; nextBits = 0; int code, oldCode = 0; byte string[]; while ((code = getNextCode()) != 257) { if (code == 256) { initializeStringTable(); code = getNextCode(); if (code == 257) { break; } writeString(stringTable[code]); oldCode = code; } else { if (code < tableIndex) { string = stringTable[code]; writeString(string); addStringToTable(stringTable[oldCode], string[0]); oldCode = code; } else { string = stringTable[oldCode]; string = composeString(string, string[0]); writeString(string); addStringToTable(string); oldCode = code; } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] decodePredictor(final byte in[], final PdfObject dicPar) { if (dicPar == null || !dicPar.isDictionary()) return in; PdfDictionary dic = (PdfDictionary)dicPar; PdfObject obj = getPdfObject(dic.get(PdfName.PREDICTOR)); if (obj == null || !obj.isNumber()) return in; int predictor = ((PdfNumber)obj).intValue(); if (predictor < 10 && predictor != 2) return in; int width = 1; obj = getPdfObject(dic.get(PdfName.COLUMNS)); if (obj != null && obj.isNumber()) width = ((PdfNumber)obj).intValue(); int colors = 1; obj = getPdfObject(dic.get(PdfName.COLORS)); if (obj != null && obj.isNumber()) colors = ((PdfNumber)obj).intValue(); int bpc = 8; obj = getPdfObject(dic.get(PdfName.BITSPERCOMPONENT)); if (obj != null && obj.isNumber()) bpc = ((PdfNumber)obj).intValue(); DataInputStream dataStream = new DataInputStream(new ByteArrayInputStream(in)); ByteArrayOutputStream fout = new ByteArrayOutputStream(in.length); int bytesPerPixel = colors * bpc / 8; int bytesPerRow = (colors*width*bpc + 7)/8; byte[] curr = new byte[bytesPerRow]; byte[] prior = new byte[bytesPerRow]; if (predictor == 2) { if (bpc == 8) { int numRows = in.length / bytesPerRow; for (int row = 0; row < numRows; row++) { int rowStart = row * bytesPerRow; for (int col = 0 + bytesPerPixel; col < bytesPerRow; col++) { in[rowStart + col] = (byte)(in[rowStart + col] + in[rowStart + col - bytesPerPixel]); } } } return in; } // Decode the (sub)image row-by-row while (true) { // Read the filter type byte and a row of data int filter = 0; try { filter = dataStream.read(); if (filter < 0) { return fout.toByteArray(); } dataStream.readFully(curr, 0, bytesPerRow); } catch (Exception e) { return fout.toByteArray(); } switch (filter) { case 0: //PNG_FILTER_NONE break; case 1: //PNG_FILTER_SUB for (int i = bytesPerPixel; i < bytesPerRow; i++) { curr[i] += curr[i - bytesPerPixel]; } break; case 2: //PNG_FILTER_UP for (int i = 0; i < bytesPerRow; i++) { curr[i] += prior[i]; } break; case 3: //PNG_FILTER_AVERAGE for (int i = 0; i < bytesPerPixel; i++) { curr[i] += prior[i] / 2; } for (int i = bytesPerPixel; i < bytesPerRow; i++) { curr[i] += ((curr[i - bytesPerPixel] & 0xff) + (prior[i] & 0xff))/2; } break; case 4: //PNG_FILTER_PAETH for (int i = 0; i < bytesPerPixel; i++) { curr[i] += prior[i]; } for (int i = bytesPerPixel; i < bytesPerRow; i++) { int a = curr[i - bytesPerPixel] & 0xff; int b = prior[i] & 0xff; int c = prior[i - bytesPerPixel] & 0xff; int p = a + b - c; int pa = Math.abs(p - a); int pb = Math.abs(p - b); int pc = Math.abs(p - c); int ret; if (pa <= pb && pa <= pc) { ret = a; } else if (pb <= pc) { ret = b; } else { ret = c; } curr[i] += (byte)ret; } break; default: // Error -- unknown filter type throw new RuntimeException(MessageLocalization.getComposedMessage("png.filter.unknown")); } try { fout.write(curr); } catch (IOException ioe) { // Never happens } // Swap curr and prior byte[] tmp = prior; prior = curr; curr = tmp; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] ASCIIHexDecode(final byte in[]) { ByteArrayOutputStream out = new ByteArrayOutputStream(); boolean first = true; int n1 = 0; for (int k = 0; k < in.length; ++k) { int ch = in[k] & 0xff; if (ch == '>') break; if (PRTokeniser.isWhitespace(ch)) continue; int n = PRTokeniser.getHex(ch); if (n == -1) throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.character.in.asciihexdecode")); if (first) n1 = n; else out.write((byte)((n1 << 4) + n)); first = !first; } if (!first) out.write((byte)(n1 << 4)); return out.toByteArray(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] ASCII85Decode(final byte in[]) { ByteArrayOutputStream out = new ByteArrayOutputStream(); int state = 0; int chn[] = new int[5]; for (int k = 0; k < in.length; ++k) { int ch = in[k] & 0xff; if (ch == '~') break; if (PRTokeniser.isWhitespace(ch)) continue; if (ch == 'z' && state == 0) { out.write(0); out.write(0); out.write(0); out.write(0); continue; } if (ch < '!' || ch > 'u') throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.character.in.ascii85decode")); chn[state] = ch - '!'; ++state; if (state == 5) { state = 0; int r = 0; for (int j = 0; j < 5; ++j) r = r * 85 + chn[j]; out.write((byte)(r >> 24)); out.write((byte)(r >> 16)); out.write((byte)(r >> 8)); out.write((byte)r); } } int r = 0; // We'll ignore the next two lines for the sake of perpetuating broken PDFs // if (state == 1) // throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.length.in.ascii85decode")); if (state == 2) { r = chn[0] * 85 * 85 * 85 * 85 + chn[1] * 85 * 85 * 85 + 85 * 85 * 85 + 85 * 85 + 85; out.write((byte)(r >> 24)); } else if (state == 3) { r = chn[0] * 85 * 85 * 85 * 85 + chn[1] * 85 * 85 * 85 + chn[2] * 85 * 85 + 85 * 85 + 85; out.write((byte)(r >> 24)); out.write((byte)(r >> 16)); } else if (state == 4) { r = chn[0] * 85 * 85 * 85 * 85 + chn[1] * 85 * 85 * 85 + chn[2] * 85 * 85 + chn[3] * 85 + 85; out.write((byte)(r >> 24)); out.write((byte)(r >> 16)); out.write((byte)(r >> 8)); } return out.toByteArray(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitMatrix.java
public int getDimension() { if (width != height) { throw new RuntimeException("Can't call getDimension() on a non-square matrix"); } return width; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/QRCode.java
public int at(int x, int y) { // The value must be zero or one. int value = matrix.get(x, y); if (!(value == 0 || value == 1)) { // this is really like an assert... not sure what better exception to use? throw new RuntimeException("Bad value"); } return value; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void add(final PdfContentByte other) { if (other.writer != null && writer != other.writer) throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.writers.are.you.mixing.two.documents")); content.append(other.content); markedContentSize += other.markedContentSize; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public PdfPatternPainter createPattern(final float width, final float height, final float xstep, final float ystep) { checkWriter(); if ( xstep == 0.0f || ystep == 0.0f ) throw new RuntimeException(MessageLocalization.getComposedMessage("xstep.or.ystep.can.not.be.zero")); PdfPatternPainter painter = new PdfPatternPainter(writer); painter.setWidth(width); painter.setHeight(height); painter.setXStep(xstep); painter.setYStep(ystep); writer.addSimplePattern(painter); return painter; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public PdfPatternPainter createPattern(final float width, final float height, final float xstep, final float ystep, final BaseColor color) { checkWriter(); if ( xstep == 0.0f || ystep == 0.0f ) throw new RuntimeException(MessageLocalization.getComposedMessage("xstep.or.ystep.can.not.be.zero")); PdfPatternPainter painter = new PdfPatternPainter(writer, color); painter.setWidth(width); painter.setHeight(height); painter.setXStep(xstep); painter.setYStep(ystep); writer.addSimplePattern(painter); return painter; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
void outputColorNumbers(final BaseColor color, final float tint) { PdfWriter.checkPdfIsoConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, color); int type = ExtendedColor.getType(color); switch (type) { case ExtendedColor.TYPE_RGB: content.append((float)color.getRed() / 0xFF); content.append(' '); content.append((float)color.getGreen() / 0xFF); content.append(' '); content.append((float)color.getBlue() / 0xFF); break; case ExtendedColor.TYPE_GRAY: content.append(((GrayColor)color).getGray()); break; case ExtendedColor.TYPE_CMYK: { CMYKColor cmyk = (CMYKColor)color; content.append(cmyk.getCyan()).append(' ').append(cmyk.getMagenta()); content.append(' ').append(cmyk.getYellow()).append(' ').append(cmyk.getBlack()); break; } case ExtendedColor.TYPE_SEPARATION: content.append(tint); break; default: throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.color.type")); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void setPatternFill(final PdfPatternPainter p, final BaseColor color, final float tint) { checkWriter(); if (!p.isStencil()) throw new RuntimeException(MessageLocalization.getComposedMessage("an.uncolored.pattern.was.expected")); PageResources prs = getPageResources(); PdfName name = writer.addSimplePattern(p); name = prs.addPattern(name, p.getIndirectReference()); ColorDetails csDetail = writer.addSimplePatternColorspace(color); PdfName cName = prs.addColor(csDetail.getColorName(), csDetail.getIndirectReference()); saveColor(new UncoloredPattern(p, color, tint), true); content.append(cName.getBytes()).append(" cs").append_i(separator); outputColorNumbers(color, tint); content.append(' ').append(name.getBytes()).append(" scn").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void setPatternStroke(final PdfPatternPainter p, final BaseColor color, final float tint) { checkWriter(); if (!p.isStencil()) throw new RuntimeException(MessageLocalization.getComposedMessage("an.uncolored.pattern.was.expected")); PageResources prs = getPageResources(); PdfName name = writer.addSimplePattern(p); name = prs.addPattern(name, p.getIndirectReference()); ColorDetails csDetail = writer.addSimplePatternColorspace(color); PdfName cName = prs.addColor(csDetail.getColorName(), csDetail.getIndirectReference()); saveColor(new UncoloredPattern(p, color, tint), false); content.append(cName.getBytes()).append(" CS").append_i(separator); outputColorNumbers(color, tint); content.append(' ').append(name.getBytes()).append(" SCN").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
void checkNoPattern(final PdfTemplate t) { if (t.getType() == PdfTemplate.TYPE_PATTERN) throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.use.of.a.pattern.a.template.was.expected")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public void close() { if (close) { return; } try { if (isTagged(writer)) { flushFloatingElements(); flushLines(); writer.getDirectContent().closeMCBlock(this); writer.flushTaggedObjects(); } boolean wasImage = imageWait != null; newPage(); if (imageWait != null || wasImage) newPage(); if (annotationsImp.hasUnusedAnnotations()) throw new RuntimeException(MessageLocalization.getComposedMessage("not.all.annotations.could.be.added.to.the.document.the.document.doesn.t.have.enough.pages")); PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) pageEvent.onCloseDocument(writer, this); super.close(); writer.addLocalDestinations(localDestinations); calculateOutlineCount(); writeOutlines(); } catch(Exception e) { throw ExceptionConverter.convertException(e); } writer.close(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public boolean newPage() { try { flushFloatingElements(); } catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } lastElementType = -1; if (isPageEmpty()) { setNewPageSizeAndMargins(); return false; } if (!open || close) { throw new RuntimeException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) pageEvent.onEndPage(writer, this); //Added to inform any listeners that we are moving to a new page (added by David Freels) super.newPage(); // the following 2 lines were added by Pelikan Stephan indentation.imageIndentLeft = 0; indentation.imageIndentRight = 0; try { // we flush the arraylist with recently written lines flushLines(); // we prepare the elements of the page dictionary // [U1] page size and rotation int rotation = pageSize.getRotation(); // [C10] if (writer.isPdfIso()) { if (thisBoxSize.containsKey("art") && thisBoxSize.containsKey("trim")) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("only.one.of.artbox.or.trimbox.can.exist.in.the.page")); if (!thisBoxSize.containsKey("art") && !thisBoxSize.containsKey("trim")) { if (thisBoxSize.containsKey("crop")) thisBoxSize.put("trim", thisBoxSize.get("crop")); else thisBoxSize.put("trim", new PdfRectangle(pageSize, pageSize.getRotation())); } } // [M1] pageResources.addDefaultColorDiff(writer.getDefaultColorspace()); if (writer.isRgbTransparencyBlending()) { PdfDictionary dcs = new PdfDictionary(); dcs.put(PdfName.CS, PdfName.DEVICERGB); pageResources.addDefaultColorDiff(dcs); } PdfDictionary resources = pageResources.getResources(); // we create the page dictionary PdfPage page = new PdfPage(new PdfRectangle(pageSize, rotation), thisBoxSize, resources, rotation); if (isTagged(writer)) { page.put(PdfName.TABS, PdfName.S); } else { page.put(PdfName.TABS, writer.getTabs()); } page.putAll(writer.getPageDictEntries()); writer.resetPageDictEntries(); // we complete the page dictionary // [U3] page actions: additional actions if (pageAA != null) { page.put(PdfName.AA, writer.addToBody(pageAA).getIndirectReference()); pageAA = null; } // [C5] and [C8] we add the annotations if (annotationsImp.hasUnusedAnnotations()) { PdfArray array = annotationsImp.rotateAnnotations(writer, pageSize); if (array.size() != 0) page.put(PdfName.ANNOTS, array); } // [F12] we add tag info if (isTagged(writer)) page.put(PdfName.STRUCTPARENTS, new PdfNumber(writer.getCurrentPageNumber() - 1)); if (text.size() > textEmptySize || isTagged(writer)) text.endText(); else text = null; ArrayList<IAccessibleElement> mcBlocks = null; if (isTagged(writer)) { mcBlocks = writer.getDirectContent().saveMCBlocks(); } writer.add(page, new PdfContents(writer.getDirectContentUnder(), graphics, !isTagged(writer) ? text : null, writer.getDirectContent(), pageSize)); // we initialize the new page initPage(); if (isTagged(writer)) { writer.getDirectContentUnder().restoreMCBlocks(mcBlocks); } } catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } catch (IOException ioe) { throw new ExceptionConverter(ioe); } return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addJavaScript(final PdfAction js) { if (js.get(PdfName.JS) == null) throw new RuntimeException(MessageLocalization.getComposedMessage("only.javascript.actions.are.allowed")); try { documentLevelJS.put(SIXTEEN_DIGITS.format(jsCounter++), writer.addToBody(js).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addJavaScript(final String name, final PdfAction js) { if (js.get(PdfName.JS) == null) throw new RuntimeException(MessageLocalization.getComposedMessage("only.javascript.actions.are.allowed")); try { documentLevelJS.put(name, writer.addToBody(js).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfdfReader.java
public void startElement(String tag, Map<String, String> h) { if ( !foundRoot ) { if (!tag.equals("xfdf")) throw new RuntimeException(MessageLocalization.getComposedMessage("root.element.is.not.xfdf.1", tag)); else foundRoot = true; } if ( tag.equals("xfdf") ){ } else if ( tag.equals("f") ) { fileSpec = h.get( "href" ); } else if ( tag.equals("fields") ) { fields = new HashMap<String, String>(); // init it! listFields = new HashMap<String, List<String>>(); } else if ( tag.equals("field") ) { String fName = h.get( "name" ); fieldNames.push( fName ); } else if ( tag.equals("value") ) { fieldValues.push( "" ); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPatternPainter.java
void checkNoColor() { if (stencil) throw new RuntimeException(MessageLocalization.getComposedMessage("colors.are.not.allowed.in.uncolored.tile.patterns")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
public static PdfArray getMKColor(BaseColor color) { PdfArray array = new PdfArray(); int type = ExtendedColor.getType(color); switch (type) { case ExtendedColor.TYPE_GRAY: { array.add(new PdfNumber(((GrayColor)color).getGray())); break; } case ExtendedColor.TYPE_CMYK: { CMYKColor cmyk = (CMYKColor)color; array.add(new PdfNumber(cmyk.getCyan())); array.add(new PdfNumber(cmyk.getMagenta())); array.add(new PdfNumber(cmyk.getYellow())); array.add(new PdfNumber(cmyk.getBlack())); break; } case ExtendedColor.TYPE_SEPARATION: case ExtendedColor.TYPE_PATTERN: case ExtendedColor.TYPE_SHADING: throw new RuntimeException(MessageLocalization.getComposedMessage("separations.patterns.and.shadings.are.not.allowed.in.mk.dictionary")); default: array.add(new PdfNumber(color.getRed() / 255f)); array.add(new PdfNumber(color.getGreen() / 255f)); array.add(new PdfNumber(color.getBlue() / 255f)); } return array; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapByteCid.java
private void encodeSequence(byte seqs[], char cid) { int size = seqs.length - 1; int nextPlane = 0; for (int idx = 0; idx < size; ++idx) { char plane[] = planes.get(nextPlane); int one = seqs[idx] & 0xff; char c = plane[one]; if (c != 0 && (c & 0x8000) == 0) throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.mapping")); if (c == 0) { planes.add(new char[256]); c = (char)(planes.size() - 1 | 0x8000); plane[one] = c; } nextPlane = c & 0x7fff; } char plane[] = planes.get(nextPlane); int one = seqs[size] & 0xff; char c = plane[one]; if ((c & 0x8000) != 0) throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.mapping")); plane[one] = cid; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapParserEx.java
private static void encodeSequence(int size, byte seqs[], char cid, ArrayList<char[]> planes) { --size; int nextPlane = 0; for (int idx = 0; idx < size; ++idx) { char plane[] = planes.get(nextPlane); int one = seqs[idx] & 0xff; char c = plane[one]; if (c != 0 && (c & 0x8000) == 0) throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.mapping")); if (c == 0) { planes.add(new char[256]); c = (char)(planes.size() - 1 | 0x8000); plane[one] = c; } nextPlane = c & 0x7fff; } char plane[] = planes.get(nextPlane); int one = seqs[size] & 0xff; char c = plane[one]; if ((c & 0x8000) != 0) throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.mapping")); plane[one] = cid; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public float writeSelectedRows(int colStart, int colEnd, int rowStart, int rowEnd, final float xPos, float yPos, final PdfContentByte[] canvases, final boolean reusable) { if (totalWidth <= 0) throw new RuntimeException(MessageLocalization.getComposedMessage("the.table.width.must.be.greater.than.zero")); int totalRows = rows.size(); if (rowStart < 0) rowStart = 0; if (rowEnd < 0) rowEnd = totalRows; else rowEnd = Math.min(rowEnd, totalRows); if (rowStart >= rowEnd) return yPos; int totalCols = getNumberOfColumns(); if (colStart < 0) colStart = 0; else colStart = Math.min(colStart, totalCols); if (colEnd < 0) colEnd = totalCols; else colEnd = Math.min(colEnd, totalCols); LOGGER.info(String.format("Writing row %s to %s; column %s to %s", rowStart, rowEnd, colStart, colEnd)); float yPosStart = yPos; PdfPTableBody currentBlock = null; for (int k = rowStart; k < rowEnd; ++k) { PdfPRow row = rows.get(k); if (getHeader().rows != null && getHeader().rows.contains(row) && currentBlock == null) { currentBlock = openTableBlock(getHeader(), canvases[TEXTCANVAS]); } else if (getBody().rows != null && getBody().rows.contains(row) && currentBlock == null) { currentBlock = openTableBlock(getBody(), canvases[TEXTCANVAS]); } else if (getFooter().rows != null && getFooter().rows.contains(row) && currentBlock == null) { currentBlock = openTableBlock(getFooter(), canvases[TEXTCANVAS]); } if (row != null) { row.writeCells(colStart, colEnd, xPos, yPos, canvases, reusable); yPos -= row.getMaxHeights(); } if (getHeader().rows != null && getHeader().rows.contains(row) && (k == rowEnd - 1 || !getHeader().rows.contains(rows.get(k + 1)))) { currentBlock = closeTableBlock(getHeader(), canvases[TEXTCANVAS]); } else if (getBody().rows != null && getBody().rows.contains(row) && (k == rowEnd - 1 || !getBody().rows.contains(rows.get(k + 1)))) { currentBlock = closeTableBlock(getBody(), canvases[TEXTCANVAS]); } else if (getFooter().rows != null && getFooter().rows.contains(row) && (k == rowEnd - 1 || !getFooter().rows.contains(rows.get(k + 1)))) { currentBlock = closeTableBlock(getFooter(), canvases[TEXTCANVAS]); } } if (tableEvent != null && colStart == 0 && colEnd == totalCols) { float heights[] = new float[rowEnd - rowStart + 1]; heights[0] = yPosStart; for (int k = rowStart; k < rowEnd; ++k) { PdfPRow row = rows.get(k); float hr = 0; if (row != null) hr = row.getMaxHeights(); heights[k - rowStart + 1] = heights[k - rowStart] - hr; } tableEvent.tableLayout(this, getEventWidths(xPos, rowStart, rowEnd, headersInEvent), heights, headersInEvent ? headerRows : 0, rowStart, canvases); } return yPos; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setRunDirection(final int runDirection) { switch (runDirection) { case PdfWriter.RUN_DIRECTION_DEFAULT: case PdfWriter.RUN_DIRECTION_NO_BIDI: case PdfWriter.RUN_DIRECTION_LTR: case PdfWriter.RUN_DIRECTION_RTL: this.runDirection = runDirection; break; default: throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.run.direction.1", runDirection)); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
public static String getRawText(String text, boolean ucc) { String out = ""; int tLen = text.length(); if (tLen == 0) { out += START_B; if (ucc) out += FNC1_INDEX; return out; } int c = 0; for (int k = 0; k < tLen; ++k) { c = text.charAt(k); if (c > 127 && c != FNC1) throw new RuntimeException(MessageLocalization.getComposedMessage("there.are.illegal.characters.for.barcode.128.in.1", text)); } c = text.charAt(0); char currentCode = START_B; int index = 0; if (isNextDigits(text, index, 2)) { currentCode = START_C; out += currentCode; if (ucc) out += FNC1_INDEX; String out2 = getPackedRawDigits(text, index, 2); index += out2.charAt(0); out += out2.substring(1); } else if (c < ' ') { currentCode = START_A; out += currentCode; if (ucc) out += FNC1_INDEX; out += (char)(c + 64); ++index; } else { out += currentCode; if (ucc) out += FNC1_INDEX; if (c == FNC1) out += FNC1_INDEX; else out += (char)(c - ' '); ++index; } while (index < tLen) { switch (currentCode) { case START_A: { if (isNextDigits(text, index, 4)) { currentCode = START_C; out += CODE_AB_TO_C; String out2 = getPackedRawDigits(text, index, 4); index += out2.charAt(0); out += out2.substring(1); } else { c = text.charAt(index++); if (c == FNC1) out += FNC1_INDEX; else if (c > '_') { currentCode = START_B; out += CODE_AC_TO_B; out += (char)(c - ' '); } else if (c < ' ') out += (char)(c + 64); else out += (char)(c - ' '); } } break; case START_B: { if (isNextDigits(text, index, 4)) { currentCode = START_C; out += CODE_AB_TO_C; String out2 = getPackedRawDigits(text, index, 4); index += out2.charAt(0); out += out2.substring(1); } else { c = text.charAt(index++); if (c == FNC1) out += FNC1_INDEX; else if (c < ' ') { currentCode = START_A; out += CODE_BC_TO_A; out += (char)(c + 64); } else { out += (char)(c - ' '); } } } break; case START_C: { if (isNextDigits(text, index, 2)) { String out2 = getPackedRawDigits(text, index, 2); index += out2.charAt(0); out += out2.substring(1); } else { c = text.charAt(index++); if (c == FNC1) out += FNC1_INDEX; else if (c < ' ') { currentCode = START_A; out += CODE_BC_TO_A; out += (char)(c + 64); } else { currentCode = START_B; out += CODE_AC_TO_B; out += (char)(c - ' '); } } } break; } } return out; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
public static Rectangle getRectangle(String name) { name = name.trim().toUpperCase(); int pos = name.indexOf(' '); if (pos == -1) { try { Field field = PageSize.class.getDeclaredField(name.toUpperCase()); return (Rectangle) field.get(null); } catch (Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name)); } } else { try { String width = name.substring(0, pos); String height = name.substring(pos + 1); return new Rectangle(Float.parseFloat(width), Float.parseFloat(height)); } catch(Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage())); } } }
5
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (Exception eofe) { throw new RuntimeException("No reference line present."); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new RuntimeException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfNumber.java
catch (NumberFormatException nfe){ throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.number.2", content, nfe.toString())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch (Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch(Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage())); }
0
(Domain) DocumentException 91
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public void makeMask() throws DocumentException { if (!isMaskCandidate()) throw new DocumentException(MessageLocalization.getComposedMessage("this.image.can.not.be.an.image.mask")); mask = true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public void setImageMask(final Image mask) throws DocumentException { if (this.mask) throw new DocumentException(MessageLocalization.getComposedMessage("an.image.mask.cannot.contain.another.image.mask")); if (!mask.mask) throw new DocumentException(MessageLocalization.getComposedMessage("the.image.mask.is.not.a.mask.did.you.do.makemask")); imageMask = mask; smask = mask.bpc > 1 && mask.bpc <= 8; }
// 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/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 public PdfStream getFullFontStream() throws DocumentException { if (builtinFont || !embedded) return null; RandomAccessFileOrArray rf = null; try { String filePfb = fileName.substring(0, fileName.length() - 3) + "pfb"; if (pfb == null) rf = new RandomAccessFileOrArray(filePfb, true, Document.plainRandomAccess); else rf = new RandomAccessFileOrArray(pfb); int fileLength = (int)rf.length(); byte st[] = new byte[fileLength - 18]; int lengths[] = new int[3]; int bytePtr = 0; for (int k = 0; k < 3; ++k) { if (rf.read() != 0x80) throw new DocumentException(MessageLocalization.getComposedMessage("start.marker.missing.in.1", filePfb)); if (rf.read() != PFB_TYPES[k]) throw new DocumentException(MessageLocalization.getComposedMessage("incorrect.segment.type.in.1", filePfb)); int size = rf.read(); size += rf.read() << 8; size += rf.read() << 16; size += rf.read() << 24; lengths[k] = size; while (size != 0) { int got = rf.read(st, bytePtr, size); if (got < 0) throw new DocumentException(MessageLocalization.getComposedMessage("premature.end.in.1", filePfb)); bytePtr += got; size -= got; } } return new StreamFont(st, lengths, compressionLevel); } catch (Exception e) { throw new DocumentException(e); } finally { if (rf != null) { try { rf.close(); } catch (Exception e) { // empty on purpose } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
protected int goComposite(final boolean simulate) throws DocumentException { PdfDocument pdf = null; if (canvas != null) pdf = canvas.pdf; if (!rectangularMode) throw new DocumentException(MessageLocalization.getComposedMessage("irregular.columns.are.not.supported.in.composite.mode")); linesWritten = 0; descender = 0; boolean firstPass = true; main_loop: while (true) { if (compositeElements.isEmpty()) return NO_MORE_TEXT; Element element = compositeElements.getFirst(); if (element.type() == Element.PARAGRAPH) { Paragraph para = (Paragraph)element; int status = 0; for (int keep = 0; keep < 2; ++keep) { float lastY = yLine; boolean createHere = false; if (compositeColumn == null) { compositeColumn = new ColumnText(canvas); compositeColumn.setAlignment(para.getAlignment()); compositeColumn.setIndent(para.getIndentationLeft() + para.getFirstLineIndent(), false); compositeColumn.setExtraParagraphSpace(para.getExtraParagraphSpace()); compositeColumn.setFollowingIndent(para.getIndentationLeft()); compositeColumn.setRightIndent(para.getIndentationRight()); compositeColumn.setLeading(para.getLeading(), para.getMultipliedLeading()); compositeColumn.setRunDirection(runDirection); compositeColumn.setArabicOptions(arabicOptions); compositeColumn.setSpaceCharRatio(spaceCharRatio); compositeColumn.addText(para); if (!(firstPass && adjustFirstLine)) { yLine -= para.getSpacingBefore(); } createHere = true; } compositeColumn.setUseAscender((firstPass || descender == 0) && adjustFirstLine ? useAscender : false); compositeColumn.leftX = leftX; compositeColumn.rightX = rightX; compositeColumn.yLine = yLine; compositeColumn.rectangularWidth = rectangularWidth; compositeColumn.rectangularMode = rectangularMode; compositeColumn.minY = minY; compositeColumn.maxY = maxY; boolean keepCandidate = para.getKeepTogether() && createHere && !(firstPass && adjustFirstLine); boolean s = simulate || keepCandidate && keep == 0; if (isTagged(canvas) && !s) { canvas.openMCBlock(para); } status = compositeColumn.go(s); if (isTagged(canvas) && !s) { canvas.closeMCBlock(para); } lastX = compositeColumn.getLastX(); updateFilledWidth(compositeColumn.filledWidth); if ((status & NO_MORE_TEXT) == 0 && keepCandidate) { compositeColumn = null; yLine = lastY; return NO_MORE_COLUMN; } if (simulate || !keepCandidate) break; if (keep == 0) { compositeColumn = null; yLine = lastY; } } firstPass = false; if (compositeColumn.getLinesWritten() > 0) { yLine = compositeColumn.yLine; linesWritten += compositeColumn.linesWritten; descender = compositeColumn.descender; } currentLeading = compositeColumn.currentLeading; if ((status & NO_MORE_TEXT) != 0) { compositeColumn = null; compositeElements.removeFirst(); yLine -= para.getSpacingAfter(); } if ((status & NO_MORE_COLUMN) != 0) { return NO_MORE_COLUMN; } } else if (element.type() == Element.LIST) { com.itextpdf.text.List list = (com.itextpdf.text.List)element; ArrayList<Element> items = list.getItems(); ListItem item = null; float listIndentation = list.getIndentationLeft(); int count = 0; Stack<Object[]> stack = new Stack<Object[]>(); for (int k = 0; k < items.size(); ++k) { Object obj = items.get(k); if (obj instanceof ListItem) { if (count == listIdx) { item = (ListItem)obj; break; } else ++count; } else if (obj instanceof com.itextpdf.text.List) { stack.push(new Object[]{list, Integer.valueOf(k), new Float(listIndentation)}); list = (com.itextpdf.text.List)obj; items = list.getItems(); listIndentation += list.getIndentationLeft(); k = -1; continue; } if (k == items.size() - 1) { if (!stack.isEmpty()) { Object objs[] = stack.pop(); list = (com.itextpdf.text.List)objs[0]; items = list.getItems(); k = ((Integer)objs[1]).intValue(); listIndentation = ((Float)objs[2]).floatValue(); } } } int status = 0; for (int keep = 0; keep < 2; ++keep) { float lastY = yLine; boolean createHere = false; if (compositeColumn == null) { if (item == null) { listIdx = 0; compositeElements.removeFirst(); continue main_loop; } compositeColumn = new ColumnText(canvas); compositeColumn.setUseAscender((firstPass || descender == 0) && adjustFirstLine ? useAscender : false); compositeColumn.setAlignment(item.getAlignment()); compositeColumn.setIndent(item.getIndentationLeft() + listIndentation + item.getFirstLineIndent(), false); compositeColumn.setExtraParagraphSpace(item.getExtraParagraphSpace()); compositeColumn.setFollowingIndent(compositeColumn.getIndent()); compositeColumn.setRightIndent(item.getIndentationRight() + list.getIndentationRight()); compositeColumn.setLeading(item.getLeading(), item.getMultipliedLeading()); compositeColumn.setRunDirection(runDirection); compositeColumn.setArabicOptions(arabicOptions); compositeColumn.setSpaceCharRatio(spaceCharRatio); compositeColumn.addText(item); if (!(firstPass && adjustFirstLine)) { yLine -= item.getSpacingBefore(); } createHere = true; } compositeColumn.leftX = leftX; compositeColumn.rightX = rightX; compositeColumn.yLine = yLine; compositeColumn.rectangularWidth = rectangularWidth; compositeColumn.rectangularMode = rectangularMode; compositeColumn.minY = minY; compositeColumn.maxY = maxY; boolean keepCandidate = item.getKeepTogether() && createHere && !(firstPass && adjustFirstLine); boolean s = simulate || keepCandidate && keep == 0; if (isTagged(canvas) && !s) { item.getListLabel().setIndentation(listIndentation); if (list.getFirstItem() == item || (compositeColumn != null && compositeColumn.bidiLine != null)) canvas.openMCBlock(list); canvas.openMCBlock(item); } status = compositeColumn.go(simulate || keepCandidate && keep == 0, item); if (isTagged(canvas) && !s) { canvas.closeMCBlock(item.getListBody()); canvas.closeMCBlock(item); if ((list.getLastItem() == item && (status & NO_MORE_TEXT) != 0) || (status & NO_MORE_COLUMN) != 0) canvas.closeMCBlock(list); } lastX = compositeColumn.getLastX(); updateFilledWidth(compositeColumn.filledWidth); if ((status & NO_MORE_TEXT) == 0 && keepCandidate) { compositeColumn = null; yLine = lastY; return NO_MORE_COLUMN; } if (simulate || !keepCandidate) break; if (keep == 0) { compositeColumn = null; yLine = lastY; } } firstPass = false; yLine = compositeColumn.yLine; linesWritten += compositeColumn.linesWritten; descender = compositeColumn.descender; currentLeading = compositeColumn.currentLeading; if (!isTagged(canvas)) { if (!Float.isNaN(compositeColumn.firstLineY) && !compositeColumn.firstLineYDone) { if (!simulate) { showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(item.getListSymbol()), compositeColumn.leftX + listIndentation, compositeColumn.firstLineY, 0); } compositeColumn.firstLineYDone = true; } } if ((status & NO_MORE_TEXT) != 0) { compositeColumn = null; ++listIdx; yLine -= item.getSpacingAfter(); } if ((status & NO_MORE_COLUMN) != 0) return NO_MORE_COLUMN; } else if (element.type() == Element.PTABLE) { // INITIALISATIONS // get the PdfPTable element PdfPTable table = (PdfPTable)element; // tables without a body are dismissed if (table.size() <= table.getHeaderRows()) { compositeElements.removeFirst(); continue; } // Y-offset float yTemp = yLine; yTemp += descender; if (rowIdx == 0 && adjustFirstLine) yTemp -= table.spacingBefore(); // if there's no space left, ask for new column if (yTemp < minY || yTemp > maxY) return NO_MORE_COLUMN; // mark start of table float yLineWrite = yTemp; float x1 = leftX; currentLeading = 0; // get the width of the table float tableWidth; if (table.isLockedWidth()) { tableWidth = table.getTotalWidth(); updateFilledWidth(tableWidth); } else { tableWidth = rectangularWidth * table.getWidthPercentage() / 100f; table.setTotalWidth(tableWidth); } // HEADERS / FOOTERS // how many header rows are real header rows; how many are footer rows? table.normalizeHeadersFooters(); int headerRows = table.getHeaderRows(); int footerRows = table.getFooterRows(); int realHeaderRows = headerRows - footerRows; float headerHeight = table.getHeaderHeight(); float footerHeight = table.getFooterHeight(); // do we need to skip the header? boolean skipHeader = table.isSkipFirstHeader() && rowIdx <= realHeaderRows && (table.isComplete() || rowIdx != realHeaderRows); // if not, we wan't to be able to add more than just a header and a footer if (!skipHeader) { yTemp -= headerHeight; if (yTemp < minY || yTemp > maxY) { return NO_MORE_COLUMN; } } // MEASURE NECESSARY SPACE // how many real rows (not header or footer rows) fit on a page? int k = 0; if (rowIdx < headerRows) { rowIdx = headerRows; } // if the table isn't complete, we need to be able to add a footer if (!table.isComplete()) yTemp -= footerHeight; // k will be the first row that doesn't fit for (k = rowIdx; k < table.size(); ++k) { float rowHeight = table.getRowHeight(k); if (yTemp - rowHeight <= minY) break; yTemp -= rowHeight; } LOGGER.info("Want to split at row " + k); int kTemp = k; while (kTemp > rowIdx && kTemp < table.size() && table.getRow(kTemp).isMayNotBreak()) { kTemp--; } if ((kTemp > rowIdx && kTemp < k) || (kTemp == 0 && table.getRow(0).isMayNotBreak() && table.isLoopCheck())) { yTemp = minY; k = kTemp; table.setLoopCheck(false); } LOGGER.info("Will split at row " + k); // only for incomplete tables: if (!table.isComplete()) yTemp += footerHeight; // IF ROWS MAY NOT BE SPLIT if (!table.isSplitRows()) { splittedRow = -1; if (k == rowIdx) { // drop the whole table if (k == table.size()) { compositeElements.removeFirst(); continue; } // or drop the row else { table.getRows().remove(k); return NO_MORE_COLUMN; } } } // IF ROWS SHOULD NOT BE SPLIT else if (table.isSplitLate() && !table.hasRowspan(k) && rowIdx < k) { splittedRow = -1; } // SPLIT ROWS (IF WANTED AND NECESSARY) else if (k < table.size()) { // we calculate the remaining vertical space float h = yTemp - minY; // we create a new row with the remaining content PdfPRow newRow = table.getRow(k).splitRow(table, k, h); // if the row isn't null add it as an extra row if (newRow == null) { LOGGER.info("Didn't split row!"); splittedRow = -1; if (rowIdx == k) return NO_MORE_COLUMN; } else { // if the row hasn't been split before, we duplicate (part of) the table if (k != splittedRow) { splittedRow = k + 1; table = new PdfPTable(table); compositeElements.set(0, table); ArrayList<PdfPRow> rows = table.getRows(); for (int i = headerRows; i < rowIdx; ++i) rows.set(i, null); } yTemp = minY; table.getRows().add(++k, newRow); LOGGER.info("Inserting row at position " + k); } } // We're no longer in the first pass firstPass = false; // if not in simulation mode, draw the table if (!simulate) { // set the alignment switch (table.getHorizontalAlignment()) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: x1 += rectangularWidth - tableWidth; break; default: x1 += (rectangularWidth - tableWidth) / 2f; } // copy the rows that fit on the page in a new table nt PdfPTable nt = PdfPTable.shallowCopy(table); ArrayList<PdfPRow> sub = nt.getRows(); // first we add the real header rows (if necessary) if (!skipHeader && realHeaderRows > 0) { ArrayList<PdfPRow> rows = table.getRows(0, realHeaderRows); if (isTagged(canvas)) nt.getHeader().rows = rows; sub.addAll(rows); } else nt.setHeaderRows(footerRows); // then we add the real content { ArrayList<PdfPRow> rows = table.getRows(rowIdx, k); if (isTagged(canvas)) { nt.getBody().rows = rows; } sub.addAll(rows); } // do we need to show a footer? boolean showFooter = !table.isSkipLastFooter(); boolean newPageFollows = false; if (k < table.size()) { nt.setComplete(true); showFooter = true; newPageFollows = true; } // we add the footer rows if necessary (not for incomplete tables) if (footerRows > 0 && nt.isComplete() && showFooter) { ArrayList<PdfPRow> rows = table.getRows(realHeaderRows, realHeaderRows + footerRows); if (isTagged(canvas)) { nt.getFooter().rows = rows; } sub.addAll(rows); } else { footerRows = 0; } // we need a correction if the last row needs to be extended float rowHeight = 0; int lastIdx = sub.size() - 1 - footerRows; PdfPRow last = sub.get(lastIdx); if (table.isExtendLastRow(newPageFollows)) { rowHeight = last.getMaxHeights(); last.setMaxHeights(yTemp - minY + rowHeight); yTemp = minY; } // newPageFollows indicates that this table is being split if (newPageFollows) { PdfPTableEvent tableEvent = table.getTableEvent(); if (tableEvent instanceof PdfPTableEventSplit) { ((PdfPTableEventSplit)tableEvent).splitTable(table); } } // now we render the rows of the new table if (canvases != null) { if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].openMCBlock(table); } nt.writeSelectedRows(0, -1, 0, -1, x1, yLineWrite, canvases, false); if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].closeMCBlock(table); } } else { if (isTagged(canvas)) { canvas.openMCBlock(table); } nt.writeSelectedRows(0, -1, 0, -1, x1, yLineWrite, canvas, false); if (isTagged(canvas)) { canvas.closeMCBlock(table); } } // if the row was split, we copy the content of the last row // that was consumed into the first row shown on the next page if (splittedRow == k && k < table.size()) { PdfPRow splitted = table.getRows().get(k); splitted.copyRowContent(nt, lastIdx); } // reset the row height of the last row if (table.isExtendLastRow(newPageFollows)) { last.setMaxHeights(rowHeight); } } // in simulation mode, we need to take extendLastRow into account else if (table.isExtendLastRow() && minY > PdfPRow.BOTTOM_LIMIT) { yTemp = minY; } yLine = yTemp; descender = 0; currentLeading = 0; if (!(skipHeader || table.isComplete())) yLine += footerHeight; while (k < table.size()) { if (table.getRowHeight(k) > 0 || table.hasRowspan(k)) { break; } k++; } if (k >= table.size()) { // Use up space no more than left if(yLine - table.spacingAfter() < minY) { yLine = minY; } else { yLine -= table.spacingAfter(); } compositeElements.removeFirst(); splittedRow = -1; rowIdx = 0; } else { if (splittedRow != -1) { ArrayList<PdfPRow> rows = table.getRows(); for (int i = rowIdx; i < k; ++i) rows.set(i, null); } rowIdx = k; return NO_MORE_COLUMN; } } else if (element.type() == Element.YMARK) { if (!simulate) { DrawInterface zh = (DrawInterface)element; zh.draw(canvas, leftX, minY, rightX, maxY, yLine); } compositeElements.removeFirst(); } else if (element.type() == Element.DIV) { ArrayList<Element> floatingElements = new ArrayList<Element>(); do { floatingElements.add(element); compositeElements.removeFirst(); element = !compositeElements.isEmpty() ? compositeElements.getFirst() : null; } while (element != null && element.type() == Element.DIV); FloatLayout fl = new FloatLayout(floatingElements, useAscender); fl.setSimpleColumn(leftX, minY, rightX, yLine); int status = fl.layout(canvas, simulate); //firstPass = false; yLine = fl.getYLine(); descender = 0; if ((status & NO_MORE_TEXT) == 0) { compositeElements.addAll(floatingElements); return status; } } else compositeElements.removeFirst(); } }
// 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
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/PdfPages.java
int reorderPages(int order[]) throws DocumentException { if (order == null) return pages.size(); if (parents.size() > 1) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.a.single.parent.in.the.page.tree.call.pdfwriter.setlinearmode.after.open")); if (order.length != pages.size()) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.an.array.with.the.same.size.as.the.number.of.pages")); int max = pages.size(); boolean temp[] = new boolean[max]; for (int k = 0; k < max; ++k) { int p = order[k]; if (p < 1 || p > max) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.pages.between.1.and.1.found.2", String.valueOf(max), String.valueOf(p))); if (temp[p - 1]) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.no.page.repetition.page.1.is.repeated", p)); temp[p - 1] = true; } PdfIndirectReference copy[] = pages.toArray(new PdfIndirectReference[pages.size()]); for (int k = 0; k < max; ++k) { pages.set(k, copy[order[k] - 1]); } return max; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setInitialLeading(final float leading) throws DocumentException { if (open) throw new DocumentException(MessageLocalization.getComposedMessage("you.can.t.set.the.initial.leading.if.the.document.is.already.open")); pdf.setLeading(leading); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setAdditionalAction(final PdfName actionType, final PdfAction action) throws DocumentException { if (!(actionType.equals(DOCUMENT_CLOSE) || actionType.equals(WILL_SAVE) || actionType.equals(DID_SAVE) || actionType.equals(WILL_PRINT) || actionType.equals(DID_PRINT))) { throw new DocumentException(MessageLocalization.getComposedMessage("invalid.additional.action.type.1", actionType.toString())); } pdf.addAdditionalAction(actionType, action); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final int encryptionType) throws DocumentException { if (pdf.isOpen()) throw new DocumentException(MessageLocalization.getComposedMessage("encryption.can.only.be.added.before.opening.the.document")); crypto = new PdfEncryption(); crypto.setCryptoMode(encryptionType, 0); crypto.setupAllKeys(userPassword, ownerPassword, permissions); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setEncryption(final Certificate[] certs, final int[] permissions, final int encryptionType) throws DocumentException { if (pdf.isOpen()) throw new DocumentException(MessageLocalization.getComposedMessage("encryption.can.only.be.added.before.opening.the.document")); crypto = new PdfEncryption(); if (certs != null) { for (int i=0; i < certs.length; i++) { crypto.addRecipient(certs[i], permissions[i]); } } crypto.setCryptoMode(encryptionType, 0); crypto.getEncryptionDictionary(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setPageAction(final PdfName actionType, final PdfAction action) throws DocumentException { if (!actionType.equals(PAGE_OPEN) && !actionType.equals(PAGE_CLOSE)) throw new DocumentException(MessageLocalization.getComposedMessage("invalid.page.additional.action.type.1", actionType.toString())); pdf.setPageAction(actionType, action); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setUserunit(final float userunit) throws DocumentException { if (userunit < 1f || userunit > 75000f) throw new DocumentException(MessageLocalization.getComposedMessage("userunit.should.be.a.value.between.1.and.75000")); addPageDictEntry(PdfName.USERUNIT, new PdfNumber(userunit)); setAtLeastPdfVersion(VERSION_1_6); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfName addDirectImageSimple(final Image image, final PdfIndirectReference fixedRef) throws PdfException, DocumentException { PdfName name; // if the images is already added, just retrieve the name if (images.containsKey(image.getMySerialId())) { name = images.get(image.getMySerialId()); } // if it's a new image, add it to the document else { if (image.isImgTemplate()) { name = new PdfName("img" + images.size()); if(image instanceof ImgWMF){ try { ImgWMF wmf = (ImgWMF)image; wmf.readWMF(PdfTemplate.createTemplate(this, 0, 0)); } catch (Exception e) { throw new DocumentException(e); } } } else { PdfIndirectReference dref = image.getDirectReference(); if (dref != null) { PdfName rname = new PdfName("img" + images.size()); images.put(image.getMySerialId(), rname); imageDictionary.put(rname, dref); return rname; } Image maskImage = image.getImageMask(); PdfIndirectReference maskRef = null; if (maskImage != null) { PdfName mname = images.get(maskImage.getMySerialId()); maskRef = getImageReference(mname); } PdfImage i = new PdfImage(image, "img" + images.size(), maskRef); if (image instanceof ImgJBIG2) { byte[] globals = ((ImgJBIG2) image).getGlobalBytes(); if (globals != null) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.put(PdfName.JBIG2GLOBALS, getReferenceJBIG2Globals(globals)); i.put(PdfName.DECODEPARMS, decodeparms); } } if (image.hasICCProfile()) { PdfICCBased icc = new PdfICCBased(image.getICCProfile(), image.getCompressionLevel()); PdfIndirectReference iccRef = add(icc); PdfArray iccArray = new PdfArray(); iccArray.add(PdfName.ICCBASED); iccArray.add(iccRef); PdfArray colorspace = i.getAsArray(PdfName.COLORSPACE); if (colorspace != null) { if (colorspace.size() > 1 && PdfName.INDEXED.equals(colorspace.getPdfObject(0))) colorspace.set(1, iccArray); else i.put(PdfName.COLORSPACE, iccArray); } else i.put(PdfName.COLORSPACE, iccArray); } add(i, fixedRef); name = i.name(); } images.put(image.getMySerialId(), name); } return name; }
// 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 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/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/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/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/PdfContentByte.java
public void addImage(final Image image, final boolean inlineImage) throws DocumentException { if (!image.hasAbsoluteY()) throw new DocumentException(MessageLocalization.getComposedMessage("the.image.must.have.absolute.positioning")); float matrix[] = image.matrix(); matrix[Image.CX] = image.getAbsoluteX() - matrix[Image.CX]; matrix[Image.CY] = image.getAbsoluteY() - matrix[Image.CY]; addImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], inlineImage); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final float a, final float b, final float c, final float d, final float e, final float f, final boolean inlineImage) throws DocumentException { try { if (image.getLayer() != null) beginLayer(image.getLayer()); if (inText && isTagged()) { endText(); } if (writer != null && image.isImgTemplate()) { writer.addDirectImageSimple(image); PdfTemplate template = image.getTemplateData(); float w = template.getWidth(); float h = template.getHeight(); addTemplate(template, a / w, b / w, c / h, d / h, e, f); } else { content.append("q "); content.append(a).append(' '); content.append(b).append(' '); content.append(c).append(' '); content.append(d).append(' '); content.append(e).append(' '); content.append(f).append(" cm"); if (inlineImage) { content.append("\nBI\n"); PdfImage pimage = new PdfImage(image, "", null); if (image instanceof ImgJBIG2) { byte[] globals = ((ImgJBIG2)image).getGlobalBytes(); if (globals != null) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.put(PdfName.JBIG2GLOBALS, writer.getReferenceJBIG2Globals(globals)); pimage.put(PdfName.DECODEPARMS, decodeparms); } } for (Object element : pimage.getKeys()) { PdfName key = (PdfName)element; PdfObject value = pimage.get(key); String s = abrev.get(key); if (s == null) continue; content.append(s); boolean check = true; if (key.equals(PdfName.COLORSPACE) && value.isArray()) { PdfArray ar = (PdfArray)value; if (ar.size() == 4 && PdfName.INDEXED.equals(ar.getAsName(0)) && ar.getPdfObject(1).isName() && ar.getPdfObject(2).isNumber() && ar.getPdfObject(3).isString() ) { check = false; } } if (check && key.equals(PdfName.COLORSPACE) && !value.isName()) { PdfName cs = writer.getColorspaceName(); PageResources prs = getPageResources(); prs.addColor(cs, writer.addToBody(value).getIndirectReference()); value = cs; } value.toPdf(null, content); content.append('\n'); } content.append("ID\n"); pimage.writeContent(content); content.append("\nEI\nQ").append_i(separator); } else { PdfName name; PageResources prs = getPageResources(); Image maskImage = image.getImageMask(); if (maskImage != null) { name = writer.addDirectImageSimple(maskImage); prs.addXObject(name, writer.getImageReference(name)); } name = writer.addDirectImageSimple(image); name = prs.addXObject(name, writer.getImageReference(name)); content.append(' ').append(name.getBytes()).append(" Do Q").append_i(separator); } } if (image.hasBorders()) { saveState(); float w = image.getWidth(); float h = image.getHeight(); concatCTM(a / w, b / w, c / h, d / h, e, f); rectangle(image); restoreState(); } if (image.getLayer() != null) endLayer(); Annotation annot = image.getAnnotation(); if (annot == null) return; float[] r = new float[unitRect.length]; for (int k = 0; k < unitRect.length; k += 2) { r[k] = a * unitRect[k] + c * unitRect[k + 1] + e; r[k + 1] = b * unitRect[k] + d * unitRect[k + 1] + f; } float llx = r[0]; float lly = r[1]; float urx = llx; float ury = lly; for (int k = 2; k < r.length; k += 2) { llx = Math.min(llx, r[k]); lly = Math.min(lly, r[k + 1]); urx = Math.max(urx, r[k]); ury = Math.max(ury, r[k + 1]); } annot = new Annotation(annot); annot.setDimensions(llx, lly, urx, ury); PdfAnnotation an = PdfAnnotationsImp.convertAnnotation(writer, annot, new Rectangle(llx, lly, urx, ury)); if (an == null) return; addAnnotation(an); } catch (Exception ee) { throw new DocumentException(ee); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
public void addWriter(final PdfWriter writer) throws DocumentException { if (this.writer == null) { this.writer = writer; annotationsImp = new PdfAnnotationsImp(writer); return; } throw new DocumentException(MessageLocalization.getComposedMessage("you.can.only.add.a.writer.to.a.pdfdocument.once")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public boolean add(final Element element) throws DocumentException { if (writer != null && writer.isPaused()) { return false; } try { if (element.type() != Element.DIV) { flushFloatingElements(); } // TODO refactor this uber long switch to State/Strategy or something ... switch(element.type()) { // Information (headers) case Element.HEADER: info.addkey(((Meta)element).getName(), ((Meta)element).getContent()); break; case Element.TITLE: info.addTitle(((Meta)element).getContent()); break; case Element.SUBJECT: info.addSubject(((Meta)element).getContent()); break; case Element.KEYWORDS: info.addKeywords(((Meta)element).getContent()); break; case Element.AUTHOR: info.addAuthor(((Meta)element).getContent()); break; case Element.CREATOR: info.addCreator(((Meta)element).getContent()); break; case Element.LANGUAGE: setLanguage(((Meta)element).getContent()); break; case Element.PRODUCER: // you can not change the name of the producer info.addProducer(); break; case Element.CREATIONDATE: // you can not set the creation date, only reset it info.addCreationDate(); break; // content (text) case Element.CHUNK: { // if there isn't a current line available, we make one if (line == null) { carriageReturn(); } // we cast the element to a chunk PdfChunk chunk = new PdfChunk((Chunk) element, anchorAction); // we try to add the chunk to the line, until we succeed { PdfChunk overflow; while ((overflow = line.add(chunk)) != null) { carriageReturn(); boolean newlineSplit = chunk.isNewlineSplit(); chunk = overflow; if (!newlineSplit) chunk.trimFirstSpace(); } } pageEmpty = false; if (chunk.isAttribute(Chunk.NEWPAGE)) { newPage(); } break; } case Element.ANCHOR: { leadingCount++; Anchor anchor = (Anchor) element; String url = anchor.getReference(); leading = anchor.getLeading(); if (url != null) { anchorAction = new PdfAction(url); } // we process the element element.process(this); anchorAction = null; leadingCount--; break; } case Element.ANNOTATION: { if (line == null) { carriageReturn(); } Annotation annot = (Annotation) element; Rectangle rect = new Rectangle(0, 0); if (line != null) rect = new Rectangle(annot.llx(indentRight() - line.widthLeft()), annot.ury(indentTop() - currentHeight - 20), annot.urx(indentRight() - line.widthLeft() + 20), annot.lly(indentTop() - currentHeight)); PdfAnnotation an = PdfAnnotationsImp.convertAnnotation(writer, annot, rect); annotationsImp.addPlainAnnotation(an); pageEmpty = false; break; } case Element.PHRASE: { leadingCount++; // we cast the element to a phrase and set the leading of the document leading = ((Phrase) element).getTotalLeading(); // we process the element element.process(this); leadingCount--; break; } case Element.PARAGRAPH: { leadingCount++; // we cast the element to a paragraph Paragraph paragraph = (Paragraph) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(paragraph); } addSpacing(paragraph.getSpacingBefore(), leading, paragraph.getFont()); // we adjust the parameters of the document alignment = paragraph.getAlignment(); leading = paragraph.getTotalLeading(); carriageReturn(); // we don't want to make orphans/widows if (currentHeight + line.height() + leading > indentTop() - indentBottom()) { newPage(); } indentation.indentLeft += paragraph.getIndentationLeft(); indentation.indentRight += paragraph.getIndentationRight(); carriageReturn(); PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null && !isSectionTitle) pageEvent.onParagraph(writer, this, indentTop() - currentHeight); // if a paragraph has to be kept together, we wrap it in a table object if (paragraph.getKeepTogether()) { carriageReturn(); PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100f); PdfPCell cell = new PdfPCell(); cell.addElement(paragraph); cell.setBorder(Rectangle.NO_BORDER); cell.setPadding(0); table.addCell(cell); indentation.indentLeft -= paragraph.getIndentationLeft(); indentation.indentRight -= paragraph.getIndentationRight(); this.add(table); indentation.indentLeft += paragraph.getIndentationLeft(); indentation.indentRight += paragraph.getIndentationRight(); } else { line.setExtraIndent(paragraph.getFirstLineIndent()); element.process(this); carriageReturn(); addSpacing(paragraph.getSpacingAfter(), paragraph.getTotalLeading(), paragraph.getFont()); } if (pageEvent != null && !isSectionTitle) pageEvent.onParagraphEnd(writer, this, indentTop() - currentHeight); alignment = Element.ALIGN_LEFT; indentation.indentLeft -= paragraph.getIndentationLeft(); indentation.indentRight -= paragraph.getIndentationRight(); carriageReturn(); leadingCount--; if (isTagged(writer)) { flushLines(); text.closeMCBlock(paragraph); } break; } case Element.SECTION: case Element.CHAPTER: { // Chapters and Sections only differ in their constructor // so we cast both to a Section Section section = (Section) element; PdfPageEvent pageEvent = writer.getPageEvent(); boolean hasTitle = section.isNotAddedYet() && section.getTitle() != null; // if the section is a chapter, we begin a new page if (section.isTriggerNewPage()) { newPage(); } if (hasTitle) { float fith = indentTop() - currentHeight; int rotation = pageSize.getRotation(); if (rotation == 90 || rotation == 180) fith = pageSize.getHeight() - fith; PdfDestination destination = new PdfDestination(PdfDestination.FITH, fith); while (currentOutline.level() >= section.getDepth()) { currentOutline = currentOutline.parent(); } PdfOutline outline = new PdfOutline(currentOutline, destination, section.getBookmarkTitle(), section.isBookmarkOpen()); currentOutline = outline; } // some values are set carriageReturn(); indentation.sectionIndentLeft += section.getIndentationLeft(); indentation.sectionIndentRight += section.getIndentationRight(); if (section.isNotAddedYet() && pageEvent != null) if (element.type() == Element.CHAPTER) pageEvent.onChapter(writer, this, indentTop() - currentHeight, section.getTitle()); else pageEvent.onSection(writer, this, indentTop() - currentHeight, section.getDepth(), section.getTitle()); // the title of the section (if any has to be printed) if (hasTitle) { isSectionTitle = true; add(section.getTitle()); isSectionTitle = false; } indentation.sectionIndentLeft += section.getIndentation(); // we process the section element.process(this); flushLines(); // some parameters are set back to normal again indentation.sectionIndentLeft -= section.getIndentationLeft() + section.getIndentation(); indentation.sectionIndentRight -= section.getIndentationRight(); if (section.isComplete() && pageEvent != null) if (element.type() == Element.CHAPTER) pageEvent.onChapterEnd(writer, this, indentTop() - currentHeight); else pageEvent.onSectionEnd(writer, this, indentTop() - currentHeight); break; } case Element.LIST: { // we cast the element to a List List list = (List) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(list); } if (list.isAlignindent()) { list.normalizeIndentation(); } // we adjust the document indentation.listIndentLeft += list.getIndentationLeft(); indentation.indentRight += list.getIndentationRight(); // we process the items in the list element.process(this); // some parameters are set back to normal again indentation.listIndentLeft -= list.getIndentationLeft(); indentation.indentRight -= list.getIndentationRight(); carriageReturn(); if (isTagged(writer)) { flushLines(); text.closeMCBlock(list); } break; } case Element.LISTITEM: { leadingCount++; // we cast the element to a ListItem ListItem listItem = (ListItem) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(listItem); } addSpacing(listItem.getSpacingBefore(), leading, listItem.getFont()); // we adjust the document alignment = listItem.getAlignment(); indentation.listIndentLeft += listItem.getIndentationLeft(); indentation.indentRight += listItem.getIndentationRight(); leading = listItem.getTotalLeading(); carriageReturn(); // we prepare the current line to be able to show us the listsymbol line.setListItem(listItem); // we process the item element.process(this); addSpacing(listItem.getSpacingAfter(), listItem.getTotalLeading(), listItem.getFont()); // if the last line is justified, it should be aligned to the left if (line.hasToBeJustified()) { line.resetAlignment(); } // some parameters are set back to normal again carriageReturn(); indentation.listIndentLeft -= listItem.getIndentationLeft(); indentation.indentRight -= listItem.getIndentationRight(); leadingCount--; if (isTagged(writer)) { flushLines(); text.closeMCBlock(listItem.getListBody()); text.closeMCBlock(listItem); } break; } case Element.RECTANGLE: { Rectangle rectangle = (Rectangle) element; graphics.rectangle(rectangle); pageEmpty = false; break; } case Element.PTABLE: { PdfPTable ptable = (PdfPTable)element; if (ptable.size() <= ptable.getHeaderRows()) break; //nothing to do // before every table, we add a new line and flush all lines ensureNewLine(); flushLines(); addPTable(ptable); pageEmpty = false; newLine(); break; } case Element.JPEG: case Element.JPEG2000: case Element.JBIG2: case Element.IMGRAW: case Element.IMGTEMPLATE: { //carriageReturn(); suggestion by Marc Campforts add((Image) element); break; } case Element.YMARK: { DrawInterface zh = (DrawInterface)element; zh.draw(graphics, indentLeft(), indentBottom(), indentRight(), indentTop(), indentTop() - currentHeight - (leadingCount > 0 ? leading : 0)); pageEmpty = false; break; } case Element.MARKED: { MarkedObject mo; if (element instanceof MarkedSection) { mo = ((MarkedSection)element).getTitle(); if (mo != null) { mo.process(this); } } mo = (MarkedObject)element; mo.process(this); break; } case Element.WRITABLE_DIRECT: if (null != writer) { ((WriterOperation)element).write(writer, this); } break; case Element.DIV: ensureNewLine(); flushLines(); addDiv((PdfDiv)element); pageEmpty = false; //newLine(); break; default: return false; } lastElementType = element.type(); return true; } catch(Exception e) { throw new DocumentException(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addPTable(final PdfPTable ptable) throws DocumentException { ColumnText ct = new ColumnText(isTagged(writer) ? text : writer.getDirectContent()); // if the table prefers to be on a single page, and it wouldn't //fit on the current page, start a new page. if (ptable.getKeepTogether() && !fitsPage(ptable, 0f) && currentHeight > 0) { newPage(); } if (currentHeight == 0) { ct.setAdjustFirstLine(false); } ct.addElement(ptable); boolean he = ptable.isHeadersInEvent(); ptable.setHeadersInEvent(true); int loop = 0; while (true) { ct.setSimpleColumn(indentLeft(), indentBottom(), indentRight(), indentTop() - currentHeight); int status = ct.go(); if ((status & ColumnText.NO_MORE_TEXT) != 0) { if (isTagged(writer)) { text.setTextMatrix(indentLeft(), ct.getYLine()); } else { text.moveText(0, ct.getYLine() - indentTop() + currentHeight); } currentHeight = indentTop() - ct.getYLine(); break; } if (indentTop() - currentHeight == ct.getYLine()) ++loop; else loop = 0; if (loop == 3) { throw new DocumentException(MessageLocalization.getComposedMessage("infinite.table.loop")); } newPage(); if (isTagged(writer)) { ct.setCanvas(text); } } ptable.setHeadersInEvent(he); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type3Glyph.java
public void addImage(Image image, float a, float b, float c, float d, float e, float f, boolean inlineImage) throws DocumentException { if (!colorized && (!image.isMask() || !(image.getBpc() == 1 || image.getBpc() > 0xff))) throw new DocumentException(MessageLocalization.getComposedMessage("not.colorized.typed3.fonts.only.accept.mask.images")); super.addImage(image, a, b, c, d, e, f, inlineImage); }
// 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/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/PdfCopyFormsImp.java
public void copyDocumentFields(PdfReader reader) throws DocumentException { if (!reader.isOpenedWithFullPermissions()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password")); 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()); fields.add(reader.getAcroFields()); updateCalculationOrder(reader); }
// 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 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/CJKFont.java
private void loadCMaps() throws DocumentException { try { fontDesc = allFonts.get(fontName); hMetrics = (IntHashtable)fontDesc.get("W"); vMetrics = (IntHashtable)fontDesc.get("W2"); String registry = (String)fontDesc.get("Registry"); uniMap = ""; for (String name : registryNames.get(registry + "_Uni")) { uniMap = name; if (name.endsWith("V") && vertical) break; if (!name.endsWith("V") && !vertical) break; } if (cidDirect) { cidUni = CMapCache.getCachedCMapCidUni(uniMap); } else { uniCid = CMapCache.getCachedCMapUniCid(uniMap); cidByte = CMapCache.getCachedCMapCidByte(CMap); } } catch (Exception ex) { throw new DocumentException(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setWidths(final float relativeWidths[]) throws DocumentException { if (relativeWidths.length != getNumberOfColumns()) throw new DocumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); this.relativeWidths = new float[relativeWidths.length]; System.arraycopy(relativeWidths, 0, this.relativeWidths, 0, relativeWidths.length); absoluteWidths = new float[relativeWidths.length]; totalHeight = 0; calculateWidths(); calculateHeights(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setTotalWidth(final float columnWidth[]) throws DocumentException { if (columnWidth.length != getNumberOfColumns()) throw new DocumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); totalWidth = 0; for (int k = 0; k < columnWidth.length; ++k) totalWidth += columnWidth[k]; setWidths(columnWidth); }
// 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 setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final boolean strength128Bits) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(userPassword, ownerPassword, permissions, strength128Bits ? PdfWriter.STANDARD_ENCRYPTION_128 : PdfWriter.STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final int encryptionType) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(userPassword, ownerPassword, permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final Certificate[] certs, final int[] permissions, final int encryptionType) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(certs, permissions, encryptionType); }
// 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/Document.java
public boolean add(Element element) throws DocumentException { if (close) { throw new DocumentException(MessageLocalization.getComposedMessage("the.document.has.been.closed.you.can.t.add.any.elements")); } if (!open && element.isContent()) { throw new DocumentException(MessageLocalization.getComposedMessage("the.document.is.not.open.yet.you.can.only.add.meta.information")); } boolean success = false; if (element instanceof ChapterAutoNumber) { chapternumber = ((ChapterAutoNumber)element).setAutomaticNumber(chapternumber); } for (DocListener listener : listeners) { success |= listener.add(element); } if (element instanceof LargeElement) { LargeElement e = (LargeElement)element; if (!e.isComplete()) e.flushContent(); } return success; }
7
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception ee) { throw new DocumentException(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new DocumentException(ex); }
212
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public void makeMask() throws DocumentException { if (!isMaskCandidate()) throw new DocumentException(MessageLocalization.getComposedMessage("this.image.can.not.be.an.image.mask")); mask = true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public void setImageMask(final Image mask) throws DocumentException { if (this.mask) throw new DocumentException(MessageLocalization.getComposedMessage("an.image.mask.cannot.contain.another.image.mask")); if (!mask.mask) throw new DocumentException(MessageLocalization.getComposedMessage("the.image.mask.is.not.a.mask.did.you.do.makemask")); imageMask = mask; smask = mask.bpc > 1 && mask.bpc <= 8; }
// 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/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/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/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/PdfCopyFields.java
public void setEncryption(byte userPassword[], byte ownerPassword[], int permissions, boolean strength128Bits) throws DocumentException { fc.setEncryption(userPassword, ownerPassword, permissions, strength128Bits ? PdfWriter.STANDARD_ENCRYPTION_128 : PdfWriter.STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFields.java
public void setEncryption(boolean strength, String userPassword, String ownerPassword, int permissions) throws DocumentException { setEncryption(DocWriter.getISOBytes(userPassword), DocWriter.getISOBytes(ownerPassword), permissions, strength); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFields.java
public void setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType) throws DocumentException { fc.setEncryption(userPassword, ownerPassword, permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFields.java
public void setEncryption(Certificate[] certs, int[] permissions, int encryptionType) throws DocumentException { fc.setEncryption(certs, permissions, encryptionType); }
// 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 public PdfStream getFullFontStream() throws DocumentException { if (builtinFont || !embedded) return null; RandomAccessFileOrArray rf = null; try { String filePfb = fileName.substring(0, fileName.length() - 3) + "pfb"; if (pfb == null) rf = new RandomAccessFileOrArray(filePfb, true, Document.plainRandomAccess); else rf = new RandomAccessFileOrArray(pfb); int fileLength = (int)rf.length(); byte st[] = new byte[fileLength - 18]; int lengths[] = new int[3]; int bytePtr = 0; for (int k = 0; k < 3; ++k) { if (rf.read() != 0x80) throw new DocumentException(MessageLocalization.getComposedMessage("start.marker.missing.in.1", filePfb)); if (rf.read() != PFB_TYPES[k]) throw new DocumentException(MessageLocalization.getComposedMessage("incorrect.segment.type.in.1", filePfb)); int size = rf.read(); size += rf.read() << 8; size += rf.read() << 16; size += rf.read() << 24; lengths[k] = size; while (size != 0) { int got = rf.read(st, bytePtr, size); if (got < 0) throw new DocumentException(MessageLocalization.getComposedMessage("premature.end.in.1", filePfb)); bytePtr += got; size -= got; } } return new StreamFont(st, lengths, compressionLevel); } catch (Exception e) { throw new DocumentException(e); } finally { if (rf != null) { try { rf.close(); } catch (Exception e) { // empty on purpose } } } }
// 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/ColumnText.java
public int go() throws DocumentException { return go(false); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public int go(final boolean simulate) throws DocumentException { return go(simulate, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public int go(final boolean simulate, final IAccessibleElement elementToGo) throws DocumentException { if (composite) return goComposite(simulate); ListBody lBody = null; if (isTagged(canvas) && elementToGo instanceof ListItem) { lBody = ((ListItem)elementToGo).getListBody(); } addWaitingPhrase(); if (bidiLine == null) return NO_MORE_TEXT; descender = 0; linesWritten = 0; lastX = 0; boolean dirty = false; float ratio = spaceCharRatio; Object currentValues[] = new Object[2]; PdfFont currentFont = null; Float lastBaseFactor = new Float(0); currentValues[1] = lastBaseFactor; PdfDocument pdf = null; PdfContentByte graphics = null; PdfContentByte text = null; firstLineY = Float.NaN; int localRunDirection = PdfWriter.RUN_DIRECTION_NO_BIDI; if (runDirection != PdfWriter.RUN_DIRECTION_DEFAULT) localRunDirection = runDirection; if (canvas != null) { graphics = canvas; pdf = canvas.getPdfDocument(); if (!isTagged(canvas)) text = canvas.getDuplicate(); else text = canvas; } else if (!simulate) throw new NullPointerException(MessageLocalization.getComposedMessage("columntext.go.with.simulate.eq.eq.false.and.text.eq.eq.null")); if (!simulate) { if (ratio == GLOBAL_SPACE_CHAR_RATIO) ratio = text.getPdfWriter().getSpaceCharRatio(); else if (ratio < 0.001f) ratio = 0.001f; } if (!rectangularMode) { float max = 0; for (PdfChunk c : bidiLine.chunks) { max = Math.max(max, c.font.size()); } currentLeading = fixedLeading + max * multipliedLeading; } float firstIndent = 0; PdfLine line; float x1; int status = 0; while(true) { firstIndent = lastWasNewline ? indent : followingIndent; // if (rectangularMode) { if (rectangularWidth <= firstIndent + rightIndent) { status = NO_MORE_COLUMN; if (bidiLine.isEmpty()) status |= NO_MORE_TEXT; break; } if (bidiLine.isEmpty()) { status = NO_MORE_TEXT; break; } line = bidiLine.processLine(leftX, rectangularWidth - firstIndent - rightIndent, alignment, localRunDirection, arabicOptions, minY, yLine, descender); if (line == null) { status = NO_MORE_TEXT; break; } float[] maxSize = line.getMaxSize(fixedLeading, multipliedLeading); if (isUseAscender() && Float.isNaN(firstLineY)) currentLeading = line.getAscender(); else currentLeading = Math.max(maxSize[0], maxSize[1] - descender); if (yLine > maxY || yLine - currentLeading < minY ) { status = NO_MORE_COLUMN; bidiLine.restore(); break; } yLine -= currentLeading; if (!simulate && !dirty) { text.beginText(); dirty = true; } if (Float.isNaN(firstLineY)) firstLineY = yLine; updateFilledWidth(rectangularWidth - line.widthLeft()); x1 = leftX; } else { float yTemp = yLine - currentLeading; float xx[] = findLimitsTwoLines(); if (xx == null) { status = NO_MORE_COLUMN; if (bidiLine.isEmpty()) status |= NO_MORE_TEXT; yLine = yTemp; break; } if (bidiLine.isEmpty()) { status = NO_MORE_TEXT; yLine = yTemp; break; } x1 = Math.max(xx[0], xx[2]); float x2 = Math.min(xx[1], xx[3]); if (x2 - x1 <= firstIndent + rightIndent) continue; if (!simulate && !dirty) { text.beginText(); dirty = true; } line = bidiLine.processLine(x1, x2 - x1 - firstIndent - rightIndent, alignment, localRunDirection, arabicOptions, minY, yLine, descender); if (line == null) { status = NO_MORE_TEXT; yLine = yTemp; break; } } if (isTagged(canvas) && elementToGo instanceof ListItem) { if (!Float.isNaN(firstLineY) && !firstLineYDone) { if (!simulate) { ListLabel lbl = ((ListItem)elementToGo).getListLabel(); canvas.openMCBlock(lbl); Chunk symbol = new Chunk(((ListItem)elementToGo).getListSymbol()); if (!lbl.getTagLabelContent()) { symbol.setRole(null); } ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(symbol), leftX + lbl.getIndentation(), firstLineY, 0); canvas.closeMCBlock(lbl); } firstLineYDone = true; } } if (!simulate) { if (lBody != null) { canvas.openMCBlock(lBody); lBody = null; } currentValues[0] = currentFont; text.setTextMatrix(x1 + (line.isRTL() ? rightIndent : firstIndent) + line.indentLeft(), yLine); lastX = pdf.writeLineToContent(line, text, graphics, currentValues, ratio); currentFont = (PdfFont)currentValues[0]; } lastWasNewline = repeatFirstLineIndent && line.isNewlineSplit(); yLine -= line.isNewlineSplit() ? extraParagraphSpace : 0; ++linesWritten; descender = line.getDescender(); } if (dirty) { text.endText(); if (canvas != text) canvas.add(text); } return status; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
protected int goComposite(final boolean simulate) throws DocumentException { PdfDocument pdf = null; if (canvas != null) pdf = canvas.pdf; if (!rectangularMode) throw new DocumentException(MessageLocalization.getComposedMessage("irregular.columns.are.not.supported.in.composite.mode")); linesWritten = 0; descender = 0; boolean firstPass = true; main_loop: while (true) { if (compositeElements.isEmpty()) return NO_MORE_TEXT; Element element = compositeElements.getFirst(); if (element.type() == Element.PARAGRAPH) { Paragraph para = (Paragraph)element; int status = 0; for (int keep = 0; keep < 2; ++keep) { float lastY = yLine; boolean createHere = false; if (compositeColumn == null) { compositeColumn = new ColumnText(canvas); compositeColumn.setAlignment(para.getAlignment()); compositeColumn.setIndent(para.getIndentationLeft() + para.getFirstLineIndent(), false); compositeColumn.setExtraParagraphSpace(para.getExtraParagraphSpace()); compositeColumn.setFollowingIndent(para.getIndentationLeft()); compositeColumn.setRightIndent(para.getIndentationRight()); compositeColumn.setLeading(para.getLeading(), para.getMultipliedLeading()); compositeColumn.setRunDirection(runDirection); compositeColumn.setArabicOptions(arabicOptions); compositeColumn.setSpaceCharRatio(spaceCharRatio); compositeColumn.addText(para); if (!(firstPass && adjustFirstLine)) { yLine -= para.getSpacingBefore(); } createHere = true; } compositeColumn.setUseAscender((firstPass || descender == 0) && adjustFirstLine ? useAscender : false); compositeColumn.leftX = leftX; compositeColumn.rightX = rightX; compositeColumn.yLine = yLine; compositeColumn.rectangularWidth = rectangularWidth; compositeColumn.rectangularMode = rectangularMode; compositeColumn.minY = minY; compositeColumn.maxY = maxY; boolean keepCandidate = para.getKeepTogether() && createHere && !(firstPass && adjustFirstLine); boolean s = simulate || keepCandidate && keep == 0; if (isTagged(canvas) && !s) { canvas.openMCBlock(para); } status = compositeColumn.go(s); if (isTagged(canvas) && !s) { canvas.closeMCBlock(para); } lastX = compositeColumn.getLastX(); updateFilledWidth(compositeColumn.filledWidth); if ((status & NO_MORE_TEXT) == 0 && keepCandidate) { compositeColumn = null; yLine = lastY; return NO_MORE_COLUMN; } if (simulate || !keepCandidate) break; if (keep == 0) { compositeColumn = null; yLine = lastY; } } firstPass = false; if (compositeColumn.getLinesWritten() > 0) { yLine = compositeColumn.yLine; linesWritten += compositeColumn.linesWritten; descender = compositeColumn.descender; } currentLeading = compositeColumn.currentLeading; if ((status & NO_MORE_TEXT) != 0) { compositeColumn = null; compositeElements.removeFirst(); yLine -= para.getSpacingAfter(); } if ((status & NO_MORE_COLUMN) != 0) { return NO_MORE_COLUMN; } } else if (element.type() == Element.LIST) { com.itextpdf.text.List list = (com.itextpdf.text.List)element; ArrayList<Element> items = list.getItems(); ListItem item = null; float listIndentation = list.getIndentationLeft(); int count = 0; Stack<Object[]> stack = new Stack<Object[]>(); for (int k = 0; k < items.size(); ++k) { Object obj = items.get(k); if (obj instanceof ListItem) { if (count == listIdx) { item = (ListItem)obj; break; } else ++count; } else if (obj instanceof com.itextpdf.text.List) { stack.push(new Object[]{list, Integer.valueOf(k), new Float(listIndentation)}); list = (com.itextpdf.text.List)obj; items = list.getItems(); listIndentation += list.getIndentationLeft(); k = -1; continue; } if (k == items.size() - 1) { if (!stack.isEmpty()) { Object objs[] = stack.pop(); list = (com.itextpdf.text.List)objs[0]; items = list.getItems(); k = ((Integer)objs[1]).intValue(); listIndentation = ((Float)objs[2]).floatValue(); } } } int status = 0; for (int keep = 0; keep < 2; ++keep) { float lastY = yLine; boolean createHere = false; if (compositeColumn == null) { if (item == null) { listIdx = 0; compositeElements.removeFirst(); continue main_loop; } compositeColumn = new ColumnText(canvas); compositeColumn.setUseAscender((firstPass || descender == 0) && adjustFirstLine ? useAscender : false); compositeColumn.setAlignment(item.getAlignment()); compositeColumn.setIndent(item.getIndentationLeft() + listIndentation + item.getFirstLineIndent(), false); compositeColumn.setExtraParagraphSpace(item.getExtraParagraphSpace()); compositeColumn.setFollowingIndent(compositeColumn.getIndent()); compositeColumn.setRightIndent(item.getIndentationRight() + list.getIndentationRight()); compositeColumn.setLeading(item.getLeading(), item.getMultipliedLeading()); compositeColumn.setRunDirection(runDirection); compositeColumn.setArabicOptions(arabicOptions); compositeColumn.setSpaceCharRatio(spaceCharRatio); compositeColumn.addText(item); if (!(firstPass && adjustFirstLine)) { yLine -= item.getSpacingBefore(); } createHere = true; } compositeColumn.leftX = leftX; compositeColumn.rightX = rightX; compositeColumn.yLine = yLine; compositeColumn.rectangularWidth = rectangularWidth; compositeColumn.rectangularMode = rectangularMode; compositeColumn.minY = minY; compositeColumn.maxY = maxY; boolean keepCandidate = item.getKeepTogether() && createHere && !(firstPass && adjustFirstLine); boolean s = simulate || keepCandidate && keep == 0; if (isTagged(canvas) && !s) { item.getListLabel().setIndentation(listIndentation); if (list.getFirstItem() == item || (compositeColumn != null && compositeColumn.bidiLine != null)) canvas.openMCBlock(list); canvas.openMCBlock(item); } status = compositeColumn.go(simulate || keepCandidate && keep == 0, item); if (isTagged(canvas) && !s) { canvas.closeMCBlock(item.getListBody()); canvas.closeMCBlock(item); if ((list.getLastItem() == item && (status & NO_MORE_TEXT) != 0) || (status & NO_MORE_COLUMN) != 0) canvas.closeMCBlock(list); } lastX = compositeColumn.getLastX(); updateFilledWidth(compositeColumn.filledWidth); if ((status & NO_MORE_TEXT) == 0 && keepCandidate) { compositeColumn = null; yLine = lastY; return NO_MORE_COLUMN; } if (simulate || !keepCandidate) break; if (keep == 0) { compositeColumn = null; yLine = lastY; } } firstPass = false; yLine = compositeColumn.yLine; linesWritten += compositeColumn.linesWritten; descender = compositeColumn.descender; currentLeading = compositeColumn.currentLeading; if (!isTagged(canvas)) { if (!Float.isNaN(compositeColumn.firstLineY) && !compositeColumn.firstLineYDone) { if (!simulate) { showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(item.getListSymbol()), compositeColumn.leftX + listIndentation, compositeColumn.firstLineY, 0); } compositeColumn.firstLineYDone = true; } } if ((status & NO_MORE_TEXT) != 0) { compositeColumn = null; ++listIdx; yLine -= item.getSpacingAfter(); } if ((status & NO_MORE_COLUMN) != 0) return NO_MORE_COLUMN; } else if (element.type() == Element.PTABLE) { // INITIALISATIONS // get the PdfPTable element PdfPTable table = (PdfPTable)element; // tables without a body are dismissed if (table.size() <= table.getHeaderRows()) { compositeElements.removeFirst(); continue; } // Y-offset float yTemp = yLine; yTemp += descender; if (rowIdx == 0 && adjustFirstLine) yTemp -= table.spacingBefore(); // if there's no space left, ask for new column if (yTemp < minY || yTemp > maxY) return NO_MORE_COLUMN; // mark start of table float yLineWrite = yTemp; float x1 = leftX; currentLeading = 0; // get the width of the table float tableWidth; if (table.isLockedWidth()) { tableWidth = table.getTotalWidth(); updateFilledWidth(tableWidth); } else { tableWidth = rectangularWidth * table.getWidthPercentage() / 100f; table.setTotalWidth(tableWidth); } // HEADERS / FOOTERS // how many header rows are real header rows; how many are footer rows? table.normalizeHeadersFooters(); int headerRows = table.getHeaderRows(); int footerRows = table.getFooterRows(); int realHeaderRows = headerRows - footerRows; float headerHeight = table.getHeaderHeight(); float footerHeight = table.getFooterHeight(); // do we need to skip the header? boolean skipHeader = table.isSkipFirstHeader() && rowIdx <= realHeaderRows && (table.isComplete() || rowIdx != realHeaderRows); // if not, we wan't to be able to add more than just a header and a footer if (!skipHeader) { yTemp -= headerHeight; if (yTemp < minY || yTemp > maxY) { return NO_MORE_COLUMN; } } // MEASURE NECESSARY SPACE // how many real rows (not header or footer rows) fit on a page? int k = 0; if (rowIdx < headerRows) { rowIdx = headerRows; } // if the table isn't complete, we need to be able to add a footer if (!table.isComplete()) yTemp -= footerHeight; // k will be the first row that doesn't fit for (k = rowIdx; k < table.size(); ++k) { float rowHeight = table.getRowHeight(k); if (yTemp - rowHeight <= minY) break; yTemp -= rowHeight; } LOGGER.info("Want to split at row " + k); int kTemp = k; while (kTemp > rowIdx && kTemp < table.size() && table.getRow(kTemp).isMayNotBreak()) { kTemp--; } if ((kTemp > rowIdx && kTemp < k) || (kTemp == 0 && table.getRow(0).isMayNotBreak() && table.isLoopCheck())) { yTemp = minY; k = kTemp; table.setLoopCheck(false); } LOGGER.info("Will split at row " + k); // only for incomplete tables: if (!table.isComplete()) yTemp += footerHeight; // IF ROWS MAY NOT BE SPLIT if (!table.isSplitRows()) { splittedRow = -1; if (k == rowIdx) { // drop the whole table if (k == table.size()) { compositeElements.removeFirst(); continue; } // or drop the row else { table.getRows().remove(k); return NO_MORE_COLUMN; } } } // IF ROWS SHOULD NOT BE SPLIT else if (table.isSplitLate() && !table.hasRowspan(k) && rowIdx < k) { splittedRow = -1; } // SPLIT ROWS (IF WANTED AND NECESSARY) else if (k < table.size()) { // we calculate the remaining vertical space float h = yTemp - minY; // we create a new row with the remaining content PdfPRow newRow = table.getRow(k).splitRow(table, k, h); // if the row isn't null add it as an extra row if (newRow == null) { LOGGER.info("Didn't split row!"); splittedRow = -1; if (rowIdx == k) return NO_MORE_COLUMN; } else { // if the row hasn't been split before, we duplicate (part of) the table if (k != splittedRow) { splittedRow = k + 1; table = new PdfPTable(table); compositeElements.set(0, table); ArrayList<PdfPRow> rows = table.getRows(); for (int i = headerRows; i < rowIdx; ++i) rows.set(i, null); } yTemp = minY; table.getRows().add(++k, newRow); LOGGER.info("Inserting row at position " + k); } } // We're no longer in the first pass firstPass = false; // if not in simulation mode, draw the table if (!simulate) { // set the alignment switch (table.getHorizontalAlignment()) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: x1 += rectangularWidth - tableWidth; break; default: x1 += (rectangularWidth - tableWidth) / 2f; } // copy the rows that fit on the page in a new table nt PdfPTable nt = PdfPTable.shallowCopy(table); ArrayList<PdfPRow> sub = nt.getRows(); // first we add the real header rows (if necessary) if (!skipHeader && realHeaderRows > 0) { ArrayList<PdfPRow> rows = table.getRows(0, realHeaderRows); if (isTagged(canvas)) nt.getHeader().rows = rows; sub.addAll(rows); } else nt.setHeaderRows(footerRows); // then we add the real content { ArrayList<PdfPRow> rows = table.getRows(rowIdx, k); if (isTagged(canvas)) { nt.getBody().rows = rows; } sub.addAll(rows); } // do we need to show a footer? boolean showFooter = !table.isSkipLastFooter(); boolean newPageFollows = false; if (k < table.size()) { nt.setComplete(true); showFooter = true; newPageFollows = true; } // we add the footer rows if necessary (not for incomplete tables) if (footerRows > 0 && nt.isComplete() && showFooter) { ArrayList<PdfPRow> rows = table.getRows(realHeaderRows, realHeaderRows + footerRows); if (isTagged(canvas)) { nt.getFooter().rows = rows; } sub.addAll(rows); } else { footerRows = 0; } // we need a correction if the last row needs to be extended float rowHeight = 0; int lastIdx = sub.size() - 1 - footerRows; PdfPRow last = sub.get(lastIdx); if (table.isExtendLastRow(newPageFollows)) { rowHeight = last.getMaxHeights(); last.setMaxHeights(yTemp - minY + rowHeight); yTemp = minY; } // newPageFollows indicates that this table is being split if (newPageFollows) { PdfPTableEvent tableEvent = table.getTableEvent(); if (tableEvent instanceof PdfPTableEventSplit) { ((PdfPTableEventSplit)tableEvent).splitTable(table); } } // now we render the rows of the new table if (canvases != null) { if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].openMCBlock(table); } nt.writeSelectedRows(0, -1, 0, -1, x1, yLineWrite, canvases, false); if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].closeMCBlock(table); } } else { if (isTagged(canvas)) { canvas.openMCBlock(table); } nt.writeSelectedRows(0, -1, 0, -1, x1, yLineWrite, canvas, false); if (isTagged(canvas)) { canvas.closeMCBlock(table); } } // if the row was split, we copy the content of the last row // that was consumed into the first row shown on the next page if (splittedRow == k && k < table.size()) { PdfPRow splitted = table.getRows().get(k); splitted.copyRowContent(nt, lastIdx); } // reset the row height of the last row if (table.isExtendLastRow(newPageFollows)) { last.setMaxHeights(rowHeight); } } // in simulation mode, we need to take extendLastRow into account else if (table.isExtendLastRow() && minY > PdfPRow.BOTTOM_LIMIT) { yTemp = minY; } yLine = yTemp; descender = 0; currentLeading = 0; if (!(skipHeader || table.isComplete())) yLine += footerHeight; while (k < table.size()) { if (table.getRowHeight(k) > 0 || table.hasRowspan(k)) { break; } k++; } if (k >= table.size()) { // Use up space no more than left if(yLine - table.spacingAfter() < minY) { yLine = minY; } else { yLine -= table.spacingAfter(); } compositeElements.removeFirst(); splittedRow = -1; rowIdx = 0; } else { if (splittedRow != -1) { ArrayList<PdfPRow> rows = table.getRows(); for (int i = rowIdx; i < k; ++i) rows.set(i, null); } rowIdx = k; return NO_MORE_COLUMN; } } else if (element.type() == Element.YMARK) { if (!simulate) { DrawInterface zh = (DrawInterface)element; zh.draw(canvas, leftX, minY, rightX, maxY, yLine); } compositeElements.removeFirst(); } else if (element.type() == Element.DIV) { ArrayList<Element> floatingElements = new ArrayList<Element>(); do { floatingElements.add(element); compositeElements.removeFirst(); element = !compositeElements.isEmpty() ? compositeElements.getFirst() : null; } while (element != null && element.type() == Element.DIV); FloatLayout fl = new FloatLayout(floatingElements, useAscender); fl.setSimpleColumn(leftX, minY, rightX, yLine); int status = fl.layout(canvas, simulate); //firstPass = false; yLine = fl.getYLine(); descender = 0; if ((status & NO_MORE_TEXT) == 0) { compositeElements.addAll(floatingElements); return status; } } else compositeElements.removeFirst(); } }
// 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/PdfPages.java
int reorderPages(int order[]) throws DocumentException { if (order == null) return pages.size(); if (parents.size() > 1) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.a.single.parent.in.the.page.tree.call.pdfwriter.setlinearmode.after.open")); if (order.length != pages.size()) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.an.array.with.the.same.size.as.the.number.of.pages")); int max = pages.size(); boolean temp[] = new boolean[max]; for (int k = 0; k < max; ++k) { int p = order[k]; if (p < 1 || p > max) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.pages.between.1.and.1.found.2", String.valueOf(max), String.valueOf(p))); if (temp[p - 1]) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.no.page.repetition.page.1.is.repeated", p)); temp[p - 1] = true; } PdfIndirectReference copy[] = pages.toArray(new PdfIndirectReference[pages.size()]); for (int k = 0; k < max; ++k) { pages.set(k, copy[order[k] - 1]); } return max; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public static PdfWriter getInstance(final Document document, final OutputStream os) throws DocumentException { PdfDocument pdf = new PdfDocument(); document.addDocListener(pdf); PdfWriter writer = new PdfWriter(pdf, os); pdf.addWriter(writer); return writer; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public static PdfWriter getInstance(final Document document, final OutputStream os, final DocListener listener) throws DocumentException { PdfDocument pdf = new PdfDocument(); pdf.addDocListener(listener); document.addDocListener(pdf); PdfWriter writer = new PdfWriter(pdf, os); pdf.addWriter(writer); return writer; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setInitialLeading(final float leading) throws DocumentException { if (open) throw new DocumentException(MessageLocalization.getComposedMessage("you.can.t.set.the.initial.leading.if.the.document.is.already.open")); pdf.setLeading(leading); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public int reorderPages(final int order[]) throws DocumentException { return root.reorderPages(order); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setAdditionalAction(final PdfName actionType, final PdfAction action) throws DocumentException { if (!(actionType.equals(DOCUMENT_CLOSE) || actionType.equals(WILL_SAVE) || actionType.equals(DID_SAVE) || actionType.equals(WILL_PRINT) || actionType.equals(DID_PRINT))) { throw new DocumentException(MessageLocalization.getComposedMessage("invalid.additional.action.type.1", actionType.toString())); } pdf.addAdditionalAction(actionType, action); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final int encryptionType) throws DocumentException { if (pdf.isOpen()) throw new DocumentException(MessageLocalization.getComposedMessage("encryption.can.only.be.added.before.opening.the.document")); crypto = new PdfEncryption(); crypto.setCryptoMode(encryptionType, 0); crypto.setupAllKeys(userPassword, ownerPassword, permissions); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setEncryption(final Certificate[] certs, final int[] permissions, final int encryptionType) throws DocumentException { if (pdf.isOpen()) throw new DocumentException(MessageLocalization.getComposedMessage("encryption.can.only.be.added.before.opening.the.document")); crypto = new PdfEncryption(); if (certs != null) { for (int i=0; i < certs.length; i++) { crypto.addRecipient(certs[i], permissions[i]); } } crypto.setCryptoMode(encryptionType, 0); crypto.getEncryptionDictionary(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Deprecated public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final boolean strength128Bits) throws DocumentException { setEncryption(userPassword, ownerPassword, permissions, strength128Bits ? STANDARD_ENCRYPTION_128 : STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Deprecated public void setEncryption(final boolean strength, final String userPassword, final String ownerPassword, final int permissions) throws DocumentException { setEncryption(getISOBytes(userPassword), getISOBytes(ownerPassword), permissions, strength ? STANDARD_ENCRYPTION_128 : STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Deprecated public void setEncryption(final int encryptionType, final String userPassword, final String ownerPassword, final int permissions) throws DocumentException { setEncryption(getISOBytes(userPassword), getISOBytes(ownerPassword), permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setPageAction(final PdfName actionType, final PdfAction action) throws DocumentException { if (!actionType.equals(PAGE_OPEN) && !actionType.equals(PAGE_CLOSE)) throw new DocumentException(MessageLocalization.getComposedMessage("invalid.page.additional.action.type.1", actionType.toString())); pdf.setPageAction(actionType, action); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setThumbnail(final Image image) throws PdfException, DocumentException { pdf.setThumbnail(image); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setUserunit(final float userunit) throws DocumentException { if (userunit < 1f || userunit > 75000f) throw new DocumentException(MessageLocalization.getComposedMessage("userunit.should.be.a.value.between.1.and.75000")); addPageDictEntry(PdfName.USERUNIT, new PdfNumber(userunit)); setAtLeastPdfVersion(VERSION_1_6); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void clearTextWrap() throws DocumentException { pdf.clearTextWrap(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfName addDirectImageSimple(final Image image) throws PdfException, DocumentException { return addDirectImageSimple(image, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfName addDirectImageSimple(final Image image, final PdfIndirectReference fixedRef) throws PdfException, DocumentException { PdfName name; // if the images is already added, just retrieve the name if (images.containsKey(image.getMySerialId())) { name = images.get(image.getMySerialId()); } // if it's a new image, add it to the document else { if (image.isImgTemplate()) { name = new PdfName("img" + images.size()); if(image instanceof ImgWMF){ try { ImgWMF wmf = (ImgWMF)image; wmf.readWMF(PdfTemplate.createTemplate(this, 0, 0)); } catch (Exception e) { throw new DocumentException(e); } } } else { PdfIndirectReference dref = image.getDirectReference(); if (dref != null) { PdfName rname = new PdfName("img" + images.size()); images.put(image.getMySerialId(), rname); imageDictionary.put(rname, dref); return rname; } Image maskImage = image.getImageMask(); PdfIndirectReference maskRef = null; if (maskImage != null) { PdfName mname = images.get(maskImage.getMySerialId()); maskRef = getImageReference(mname); } PdfImage i = new PdfImage(image, "img" + images.size(), maskRef); if (image instanceof ImgJBIG2) { byte[] globals = ((ImgJBIG2) image).getGlobalBytes(); if (globals != null) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.put(PdfName.JBIG2GLOBALS, getReferenceJBIG2Globals(globals)); i.put(PdfName.DECODEPARMS, decodeparms); } } if (image.hasICCProfile()) { PdfICCBased icc = new PdfICCBased(image.getICCProfile(), image.getCompressionLevel()); PdfIndirectReference iccRef = add(icc); PdfArray iccArray = new PdfArray(); iccArray.add(PdfName.ICCBASED); iccArray.add(iccRef); PdfArray colorspace = i.getAsArray(PdfName.COLORSPACE); if (colorspace != null) { if (colorspace.size() > 1 && PdfName.INDEXED.equals(colorspace.getPdfObject(0))) colorspace.set(1, iccArray); else i.put(PdfName.COLORSPACE, iccArray); } else i.put(PdfName.COLORSPACE, iccArray); } add(i, fixedRef); name = i.name(); } images.put(image.getMySerialId(), name); } return name; }
// 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/PdfCopyForms.java
public void copyDocumentFields(PdfReader reader) throws DocumentException{ fc.copyDocumentFields(reader); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyForms.java
public void setEncryption(byte userPassword[], byte ownerPassword[], int permissions, boolean strength128Bits) throws DocumentException { fc.setEncryption(userPassword, ownerPassword, permissions, strength128Bits ? PdfWriter.STANDARD_ENCRYPTION_128 : PdfWriter.STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyForms.java
public void setEncryption(boolean strength, String userPassword, String ownerPassword, int permissions) throws DocumentException { setEncryption(DocWriter.getISOBytes(userPassword), DocWriter.getISOBytes(ownerPassword), permissions, strength); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyForms.java
public void setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType) throws DocumentException { fc.setEncryption(userPassword, ownerPassword, permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyForms.java
public void setEncryption(Certificate[] certs, int[] permissions, int encryptionType) throws DocumentException { fc.setEncryption(certs, permissions, encryptionType); }
// 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 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
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
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 void addImage(Image image, float a, float b, float c, float d, float e, float f) throws DocumentException { throwError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
public PdfTemplate getAppearance() throws DocumentException { if (isInvisible()) { PdfTemplate t = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(0, 0)); writer.addDirectTemplateSimple(t, null); return t; } if (app[0] == null) { PdfTemplate t = app[0] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n0")); t.setLiteral("% DSBlank\n"); } if (app[1] == null && !acro6Layers) { PdfTemplate t = app[1] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n1")); t.setLiteral(questionMark); } if (app[2] == null) { String text; if (layer2Text == null) { StringBuilder buf = new StringBuilder(); buf.append("Digitally signed by "); String name = null; X500Name x500name = CertificateInfo.getSubjectFields((X509Certificate)signCertificate); if (x500name != null) { name = x500name.getField("CN"); if (name == null) name = x500name.getField("E"); } if (name == null) name = ""; buf.append(name).append('\n'); SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); buf.append("Date: ").append(sd.format(signDate.getTime())); if (reason != null) buf.append('\n').append("Reason: ").append(reason); if (location != null) buf.append('\n').append("Location: ").append(location); text = buf.toString(); } else text = layer2Text; PdfTemplate t = app[2] = new PdfTemplate(writer); t.setBoundingBox(rect); writer.addDirectTemplateSimple(t, new PdfName("n2")); if (image != null) { if (imageScale == 0) { t.addImage(image, rect.getWidth(), 0, 0, rect.getHeight(), 0, 0); } else { float usableScale = imageScale; if (imageScale < 0) usableScale = Math.min(rect.getWidth() / image.getWidth(), rect.getHeight() / image.getHeight()); float w = image.getWidth() * usableScale; float h = image.getHeight() * usableScale; float x = (rect.getWidth() - w) / 2; float y = (rect.getHeight() - h) / 2; t.addImage(image, w, 0, 0, h, x, y); } } Font font; if (layer2Font == null) font = new Font(); else font = new Font(layer2Font); float size = font.getSize(); Rectangle dataRect = null; Rectangle signatureRect = null; if (renderingMode == RenderingMode.NAME_AND_DESCRIPTION || renderingMode == RenderingMode.GRAPHIC_AND_DESCRIPTION && this.signatureGraphic != null) { // origin is the bottom-left signatureRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() / 2 - MARGIN, rect.getHeight() - MARGIN); dataRect = new Rectangle( rect.getWidth() / 2 + MARGIN / 2, MARGIN, rect.getWidth() - MARGIN / 2, rect.getHeight() - MARGIN); if (rect.getHeight() > rect.getWidth()) { signatureRect = new Rectangle( MARGIN, rect.getHeight() / 2, rect.getWidth() - MARGIN, rect.getHeight()); dataRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, rect.getHeight() / 2 - MARGIN); } } else if (renderingMode == RenderingMode.GRAPHIC) { if (signatureGraphic == null) { throw new IllegalStateException(MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.only")); } signatureRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, // take all space available rect.getHeight() - MARGIN); } else { dataRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, rect.getHeight() * (1 - TOP_SECTION) - MARGIN); } switch (renderingMode) { case NAME_AND_DESCRIPTION: String signedBy = CertificateInfo.getSubjectFields((X509Certificate)signCertificate).getField("CN"); if (signedBy == null) signedBy = CertificateInfo.getSubjectFields((X509Certificate)signCertificate).getField("E"); if (signedBy == null) signedBy = ""; Rectangle sr2 = new Rectangle(signatureRect.getWidth() - MARGIN, signatureRect.getHeight() - MARGIN ); float signedSize = ColumnText.fitText(font, signedBy, sr2, -1, runDirection); ColumnText ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(new Phrase(signedBy, font), signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), signedSize, Element.ALIGN_LEFT); ct2.go(); break; case GRAPHIC_AND_DESCRIPTION: if (signatureGraphic == null) { throw new IllegalStateException(MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.and.description")); } ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), 0, Element.ALIGN_RIGHT); Image im = Image.getInstance(signatureGraphic); im.scaleToFit(signatureRect.getWidth(), signatureRect.getHeight()); Paragraph p = new Paragraph(); // must calculate the point to draw from to make image appear in middle of column float x = 0; // experimentation found this magic number to counteract Adobe's signature graphic, which // offsets the y co-ordinate by 15 units float y = -im.getScaledHeight() + 15; x = x + (signatureRect.getWidth() - im.getScaledWidth()) / 2; y = y - (signatureRect.getHeight() - im.getScaledHeight()) / 2; p.add(new Chunk(im, x + (signatureRect.getWidth() - im.getScaledWidth()) / 2, y, false)); ct2.addElement(p); ct2.go(); break; case GRAPHIC: ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), 0, Element.ALIGN_RIGHT); im = Image.getInstance(signatureGraphic); im.scaleToFit(signatureRect.getWidth(), signatureRect.getHeight()); p = new Paragraph(signatureRect.getHeight()); // must calculate the point to draw from to make image appear in middle of column x = (signatureRect.getWidth() - im.getScaledWidth()) / 2; y = (signatureRect.getHeight() - im.getScaledHeight()) / 2; p.add(new Chunk(im, x, y, false)); ct2.addElement(p); ct2.go(); break; default: } if(renderingMode != RenderingMode.GRAPHIC) { if (size <= 0) { Rectangle sr = new Rectangle(dataRect.getWidth(), dataRect.getHeight()); size = ColumnText.fitText(font, text, sr, 12, runDirection); } ColumnText ct = new ColumnText(t); ct.setRunDirection(runDirection); ct.setSimpleColumn(new Phrase(text, font), dataRect.getLeft(), dataRect.getBottom(), dataRect.getRight(), dataRect.getTop(), size, Element.ALIGN_LEFT); ct.go(); } } if (app[3] == null && !acro6Layers) { PdfTemplate t = app[3] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n3")); t.setLiteral("% DSBlank\n"); } if (app[4] == null && !acro6Layers) { PdfTemplate t = app[4] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(0, rect.getHeight() * (1 - TOP_SECTION), rect.getRight(), rect.getTop())); writer.addDirectTemplateSimple(t, new PdfName("n4")); Font font; if (layer2Font == null) font = new Font(); else font = new Font(layer2Font); //float size = font.getSize(); String text = "Signature Not Verified"; if (layer4Text != null) text = layer4Text; Rectangle sr = new Rectangle(rect.getWidth() - 2 * MARGIN, rect.getHeight() * TOP_SECTION - 2 * MARGIN); float size = ColumnText.fitText(font, text, sr, 15, runDirection); ColumnText ct = new ColumnText(t); ct.setRunDirection(runDirection); ct.setSimpleColumn(new Phrase(text, font), MARGIN, 0, rect.getWidth() - MARGIN, rect.getHeight() - MARGIN, size, Element.ALIGN_LEFT); ct.go(); } int rotation = writer.reader.getPageRotation(page); Rectangle rotated = new Rectangle(rect); int n = rotation; while (n > 0) { rotated = rotated.rotate(); n -= 90; } if (frm == null) { frm = new PdfTemplate(writer); frm.setBoundingBox(rotated); writer.addDirectTemplateSimple(frm, new PdfName("FRM")); float scale = Math.min(rect.getWidth(), rect.getHeight()) * 0.9f; float x = (rect.getWidth() - scale) / 2; float y = (rect.getHeight() - scale) / 2; scale /= 100; if (rotation == 90) frm.concatCTM(0, 1, -1, 0, rect.getHeight(), 0); else if (rotation == 180) frm.concatCTM(-1, 0, 0, -1, rect.getWidth(), rect.getHeight()); else if (rotation == 270) frm.concatCTM(0, -1, 1, 0, 0, rect.getWidth()); frm.addTemplate(app[0], 0, 0); if (!acro6Layers) frm.addTemplate(app[1], scale, 0, 0, scale, x, y); frm.addTemplate(app[2], 0, 0); if (!acro6Layers) { frm.addTemplate(app[3], scale, 0, 0, scale, x, y); frm.addTemplate(app[4], 0, 0); } } PdfTemplate napp = new PdfTemplate(writer); napp.setBoundingBox(rotated); writer.addDirectTemplateSimple(napp, null); napp.addTemplate(frm, 0, 0); return napp; }
// 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
void setThumbnail(Image image, int page) throws PdfException, DocumentException { PdfIndirectReference thumb = getImageReference(addDirectImageSimple(image)); reader.resetReleasePage(); PdfDictionary dic = reader.getPageN(page); dic.put(PdfName.THUMB, thumb); reader.resetReleasePage(); }
// 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/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/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/PdfContentByte.java
public void addImage(final Image image) throws DocumentException { addImage(image, false); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final boolean inlineImage) throws DocumentException { if (!image.hasAbsoluteY()) throw new DocumentException(MessageLocalization.getComposedMessage("the.image.must.have.absolute.positioning")); float matrix[] = image.matrix(); matrix[Image.CX] = image.getAbsoluteX() - matrix[Image.CX]; matrix[Image.CY] = image.getAbsoluteY() - matrix[Image.CY]; addImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], inlineImage); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final float a, final float b, final float c, final float d, final float e, final float f) throws DocumentException { addImage(image, a, b, c, d, e, f, false); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final AffineTransform transform) throws DocumentException { double matrix[] = new double[6]; transform.getMatrix(matrix); addImage( image, (float)matrix[0], (float)matrix[1], (float)matrix[2], (float)matrix[3], (float)matrix[4],(float) matrix[5], false ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final float a, final float b, final float c, final float d, final float e, final float f, final boolean inlineImage) throws DocumentException { try { if (image.getLayer() != null) beginLayer(image.getLayer()); if (inText && isTagged()) { endText(); } if (writer != null && image.isImgTemplate()) { writer.addDirectImageSimple(image); PdfTemplate template = image.getTemplateData(); float w = template.getWidth(); float h = template.getHeight(); addTemplate(template, a / w, b / w, c / h, d / h, e, f); } else { content.append("q "); content.append(a).append(' '); content.append(b).append(' '); content.append(c).append(' '); content.append(d).append(' '); content.append(e).append(' '); content.append(f).append(" cm"); if (inlineImage) { content.append("\nBI\n"); PdfImage pimage = new PdfImage(image, "", null); if (image instanceof ImgJBIG2) { byte[] globals = ((ImgJBIG2)image).getGlobalBytes(); if (globals != null) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.put(PdfName.JBIG2GLOBALS, writer.getReferenceJBIG2Globals(globals)); pimage.put(PdfName.DECODEPARMS, decodeparms); } } for (Object element : pimage.getKeys()) { PdfName key = (PdfName)element; PdfObject value = pimage.get(key); String s = abrev.get(key); if (s == null) continue; content.append(s); boolean check = true; if (key.equals(PdfName.COLORSPACE) && value.isArray()) { PdfArray ar = (PdfArray)value; if (ar.size() == 4 && PdfName.INDEXED.equals(ar.getAsName(0)) && ar.getPdfObject(1).isName() && ar.getPdfObject(2).isNumber() && ar.getPdfObject(3).isString() ) { check = false; } } if (check && key.equals(PdfName.COLORSPACE) && !value.isName()) { PdfName cs = writer.getColorspaceName(); PageResources prs = getPageResources(); prs.addColor(cs, writer.addToBody(value).getIndirectReference()); value = cs; } value.toPdf(null, content); content.append('\n'); } content.append("ID\n"); pimage.writeContent(content); content.append("\nEI\nQ").append_i(separator); } else { PdfName name; PageResources prs = getPageResources(); Image maskImage = image.getImageMask(); if (maskImage != null) { name = writer.addDirectImageSimple(maskImage); prs.addXObject(name, writer.getImageReference(name)); } name = writer.addDirectImageSimple(image); name = prs.addXObject(name, writer.getImageReference(name)); content.append(' ').append(name.getBytes()).append(" Do Q").append_i(separator); } } if (image.hasBorders()) { saveState(); float w = image.getWidth(); float h = image.getHeight(); concatCTM(a / w, b / w, c / h, d / h, e, f); rectangle(image); restoreState(); } if (image.getLayer() != null) endLayer(); Annotation annot = image.getAnnotation(); if (annot == null) return; float[] r = new float[unitRect.length]; for (int k = 0; k < unitRect.length; k += 2) { r[k] = a * unitRect[k] + c * unitRect[k + 1] + e; r[k + 1] = b * unitRect[k] + d * unitRect[k + 1] + f; } float llx = r[0]; float lly = r[1]; float urx = llx; float ury = lly; for (int k = 2; k < r.length; k += 2) { llx = Math.min(llx, r[k]); lly = Math.min(lly, r[k + 1]); urx = Math.max(urx, r[k]); ury = Math.max(ury, r[k + 1]); } annot = new Annotation(annot); annot.setDimensions(llx, lly, urx, ury); PdfAnnotation an = PdfAnnotationsImp.convertAnnotation(writer, annot, new Rectangle(llx, lly, urx, ury)); if (an == null) return; addAnnotation(an); } catch (Exception ee) { throw new DocumentException(ee); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final java.awt.geom.AffineTransform transform) throws DocumentException { double matrix[] = new double[6]; transform.getMatrix(matrix); addImage(image, new AffineTransform(matrix)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
public void addWriter(final PdfWriter writer) throws DocumentException { if (this.writer == null) { this.writer = writer; annotationsImp = new PdfAnnotationsImp(writer); return; } throw new DocumentException(MessageLocalization.getComposedMessage("you.can.only.add.a.writer.to.a.pdfdocument.once")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public boolean add(final Element element) throws DocumentException { if (writer != null && writer.isPaused()) { return false; } try { if (element.type() != Element.DIV) { flushFloatingElements(); } // TODO refactor this uber long switch to State/Strategy or something ... switch(element.type()) { // Information (headers) case Element.HEADER: info.addkey(((Meta)element).getName(), ((Meta)element).getContent()); break; case Element.TITLE: info.addTitle(((Meta)element).getContent()); break; case Element.SUBJECT: info.addSubject(((Meta)element).getContent()); break; case Element.KEYWORDS: info.addKeywords(((Meta)element).getContent()); break; case Element.AUTHOR: info.addAuthor(((Meta)element).getContent()); break; case Element.CREATOR: info.addCreator(((Meta)element).getContent()); break; case Element.LANGUAGE: setLanguage(((Meta)element).getContent()); break; case Element.PRODUCER: // you can not change the name of the producer info.addProducer(); break; case Element.CREATIONDATE: // you can not set the creation date, only reset it info.addCreationDate(); break; // content (text) case Element.CHUNK: { // if there isn't a current line available, we make one if (line == null) { carriageReturn(); } // we cast the element to a chunk PdfChunk chunk = new PdfChunk((Chunk) element, anchorAction); // we try to add the chunk to the line, until we succeed { PdfChunk overflow; while ((overflow = line.add(chunk)) != null) { carriageReturn(); boolean newlineSplit = chunk.isNewlineSplit(); chunk = overflow; if (!newlineSplit) chunk.trimFirstSpace(); } } pageEmpty = false; if (chunk.isAttribute(Chunk.NEWPAGE)) { newPage(); } break; } case Element.ANCHOR: { leadingCount++; Anchor anchor = (Anchor) element; String url = anchor.getReference(); leading = anchor.getLeading(); if (url != null) { anchorAction = new PdfAction(url); } // we process the element element.process(this); anchorAction = null; leadingCount--; break; } case Element.ANNOTATION: { if (line == null) { carriageReturn(); } Annotation annot = (Annotation) element; Rectangle rect = new Rectangle(0, 0); if (line != null) rect = new Rectangle(annot.llx(indentRight() - line.widthLeft()), annot.ury(indentTop() - currentHeight - 20), annot.urx(indentRight() - line.widthLeft() + 20), annot.lly(indentTop() - currentHeight)); PdfAnnotation an = PdfAnnotationsImp.convertAnnotation(writer, annot, rect); annotationsImp.addPlainAnnotation(an); pageEmpty = false; break; } case Element.PHRASE: { leadingCount++; // we cast the element to a phrase and set the leading of the document leading = ((Phrase) element).getTotalLeading(); // we process the element element.process(this); leadingCount--; break; } case Element.PARAGRAPH: { leadingCount++; // we cast the element to a paragraph Paragraph paragraph = (Paragraph) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(paragraph); } addSpacing(paragraph.getSpacingBefore(), leading, paragraph.getFont()); // we adjust the parameters of the document alignment = paragraph.getAlignment(); leading = paragraph.getTotalLeading(); carriageReturn(); // we don't want to make orphans/widows if (currentHeight + line.height() + leading > indentTop() - indentBottom()) { newPage(); } indentation.indentLeft += paragraph.getIndentationLeft(); indentation.indentRight += paragraph.getIndentationRight(); carriageReturn(); PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null && !isSectionTitle) pageEvent.onParagraph(writer, this, indentTop() - currentHeight); // if a paragraph has to be kept together, we wrap it in a table object if (paragraph.getKeepTogether()) { carriageReturn(); PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100f); PdfPCell cell = new PdfPCell(); cell.addElement(paragraph); cell.setBorder(Rectangle.NO_BORDER); cell.setPadding(0); table.addCell(cell); indentation.indentLeft -= paragraph.getIndentationLeft(); indentation.indentRight -= paragraph.getIndentationRight(); this.add(table); indentation.indentLeft += paragraph.getIndentationLeft(); indentation.indentRight += paragraph.getIndentationRight(); } else { line.setExtraIndent(paragraph.getFirstLineIndent()); element.process(this); carriageReturn(); addSpacing(paragraph.getSpacingAfter(), paragraph.getTotalLeading(), paragraph.getFont()); } if (pageEvent != null && !isSectionTitle) pageEvent.onParagraphEnd(writer, this, indentTop() - currentHeight); alignment = Element.ALIGN_LEFT; indentation.indentLeft -= paragraph.getIndentationLeft(); indentation.indentRight -= paragraph.getIndentationRight(); carriageReturn(); leadingCount--; if (isTagged(writer)) { flushLines(); text.closeMCBlock(paragraph); } break; } case Element.SECTION: case Element.CHAPTER: { // Chapters and Sections only differ in their constructor // so we cast both to a Section Section section = (Section) element; PdfPageEvent pageEvent = writer.getPageEvent(); boolean hasTitle = section.isNotAddedYet() && section.getTitle() != null; // if the section is a chapter, we begin a new page if (section.isTriggerNewPage()) { newPage(); } if (hasTitle) { float fith = indentTop() - currentHeight; int rotation = pageSize.getRotation(); if (rotation == 90 || rotation == 180) fith = pageSize.getHeight() - fith; PdfDestination destination = new PdfDestination(PdfDestination.FITH, fith); while (currentOutline.level() >= section.getDepth()) { currentOutline = currentOutline.parent(); } PdfOutline outline = new PdfOutline(currentOutline, destination, section.getBookmarkTitle(), section.isBookmarkOpen()); currentOutline = outline; } // some values are set carriageReturn(); indentation.sectionIndentLeft += section.getIndentationLeft(); indentation.sectionIndentRight += section.getIndentationRight(); if (section.isNotAddedYet() && pageEvent != null) if (element.type() == Element.CHAPTER) pageEvent.onChapter(writer, this, indentTop() - currentHeight, section.getTitle()); else pageEvent.onSection(writer, this, indentTop() - currentHeight, section.getDepth(), section.getTitle()); // the title of the section (if any has to be printed) if (hasTitle) { isSectionTitle = true; add(section.getTitle()); isSectionTitle = false; } indentation.sectionIndentLeft += section.getIndentation(); // we process the section element.process(this); flushLines(); // some parameters are set back to normal again indentation.sectionIndentLeft -= section.getIndentationLeft() + section.getIndentation(); indentation.sectionIndentRight -= section.getIndentationRight(); if (section.isComplete() && pageEvent != null) if (element.type() == Element.CHAPTER) pageEvent.onChapterEnd(writer, this, indentTop() - currentHeight); else pageEvent.onSectionEnd(writer, this, indentTop() - currentHeight); break; } case Element.LIST: { // we cast the element to a List List list = (List) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(list); } if (list.isAlignindent()) { list.normalizeIndentation(); } // we adjust the document indentation.listIndentLeft += list.getIndentationLeft(); indentation.indentRight += list.getIndentationRight(); // we process the items in the list element.process(this); // some parameters are set back to normal again indentation.listIndentLeft -= list.getIndentationLeft(); indentation.indentRight -= list.getIndentationRight(); carriageReturn(); if (isTagged(writer)) { flushLines(); text.closeMCBlock(list); } break; } case Element.LISTITEM: { leadingCount++; // we cast the element to a ListItem ListItem listItem = (ListItem) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(listItem); } addSpacing(listItem.getSpacingBefore(), leading, listItem.getFont()); // we adjust the document alignment = listItem.getAlignment(); indentation.listIndentLeft += listItem.getIndentationLeft(); indentation.indentRight += listItem.getIndentationRight(); leading = listItem.getTotalLeading(); carriageReturn(); // we prepare the current line to be able to show us the listsymbol line.setListItem(listItem); // we process the item element.process(this); addSpacing(listItem.getSpacingAfter(), listItem.getTotalLeading(), listItem.getFont()); // if the last line is justified, it should be aligned to the left if (line.hasToBeJustified()) { line.resetAlignment(); } // some parameters are set back to normal again carriageReturn(); indentation.listIndentLeft -= listItem.getIndentationLeft(); indentation.indentRight -= listItem.getIndentationRight(); leadingCount--; if (isTagged(writer)) { flushLines(); text.closeMCBlock(listItem.getListBody()); text.closeMCBlock(listItem); } break; } case Element.RECTANGLE: { Rectangle rectangle = (Rectangle) element; graphics.rectangle(rectangle); pageEmpty = false; break; } case Element.PTABLE: { PdfPTable ptable = (PdfPTable)element; if (ptable.size() <= ptable.getHeaderRows()) break; //nothing to do // before every table, we add a new line and flush all lines ensureNewLine(); flushLines(); addPTable(ptable); pageEmpty = false; newLine(); break; } case Element.JPEG: case Element.JPEG2000: case Element.JBIG2: case Element.IMGRAW: case Element.IMGTEMPLATE: { //carriageReturn(); suggestion by Marc Campforts add((Image) element); break; } case Element.YMARK: { DrawInterface zh = (DrawInterface)element; zh.draw(graphics, indentLeft(), indentBottom(), indentRight(), indentTop(), indentTop() - currentHeight - (leadingCount > 0 ? leading : 0)); pageEmpty = false; break; } case Element.MARKED: { MarkedObject mo; if (element instanceof MarkedSection) { mo = ((MarkedSection)element).getTitle(); if (mo != null) { mo.process(this); } } mo = (MarkedObject)element; mo.process(this); break; } case Element.WRITABLE_DIRECT: if (null != writer) { ((WriterOperation)element).write(writer, this); } break; case Element.DIV: ensureNewLine(); flushLines(); addDiv((PdfDiv)element); pageEmpty = false; //newLine(); break; default: return false; } lastElementType = element.type(); return true; } catch(Exception e) { throw new DocumentException(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void initPage() throws DocumentException { // the pagenumber is incremented pageN++; // initialization of some page objects annotationsImp.resetAnnotations(); pageResources = new PageResources(); writer.resetContent(); if (isTagged(writer)) { graphics = writer.getDirectContentUnder().getDuplicate(); writer.getDirectContent().duplicatedFrom = graphics; } else { graphics = new PdfContentByte(writer); } markPoint = 0; setNewPageSizeAndMargins(); imageEnd = -1; indentation.imageIndentRight = 0; indentation.imageIndentLeft = 0; indentation.indentBottom = 0; indentation.indentTop = 0; currentHeight = 0; // backgroundcolors, etc... thisBoxSize = new HashMap<String, PdfRectangle>(boxSize); if (pageSize.getBackgroundColor() != null || pageSize.hasBorders() || pageSize.getBorderColor() != null) { add(pageSize); } float oldleading = leading; int oldAlignment = alignment; pageEmpty = true; // if there is an image waiting to be drawn, draw it try { if (imageWait != null) { add(imageWait); imageWait = null; } } catch(Exception e) { throw new ExceptionConverter(e); } leading = oldleading; alignment = oldAlignment; carriageReturn(); PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) { if (firstPageEvent) { pageEvent.onOpenDocument(writer, this); } pageEvent.onStartPage(writer, this); } firstPageEvent = false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void newLine() throws DocumentException { lastElementType = -1; carriageReturn(); if (lines != null && !lines.isEmpty()) { lines.add(line); currentHeight += line.height(); } line = new PdfLine(indentLeft(), indentRight(), alignment, leading); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected float flushLines() throws DocumentException { // checks if the ArrayList with the lines is not null if (lines == null) { return 0; } // checks if a new Line has to be made. if (line != null && line.size() > 0) { lines.add(line); line = new PdfLine(indentLeft(), indentRight(), alignment, leading); } // checks if the ArrayList with the lines is empty if (lines.isEmpty()) { return 0; } // initialization of some parameters Object currentValues[] = new Object[2]; PdfFont currentFont = null; float displacement = 0; Float lastBaseFactor = new Float(0); currentValues[1] = lastBaseFactor; // looping over all the lines for (PdfLine l: lines) { float moveTextX = l.indentLeft() - indentLeft() + indentation.indentLeft + indentation.listIndentLeft + indentation.sectionIndentLeft; text.moveText(moveTextX, -l.height()); // is the line preceded by a symbol? if (l.listSymbol() != null) { ListLabel lbl = null; Chunk symbol = l.listSymbol(); if (isTagged(writer)) { lbl = l.listItem().getListLabel(); graphics.openMCBlock(lbl); symbol = new Chunk(symbol); if (!lbl.getTagLabelContent()) symbol.setRole(null); } ColumnText.showTextAligned(graphics, Element.ALIGN_LEFT, new Phrase(symbol), text.getXTLM() - l.listIndent(), text.getYTLM(), 0); if (lbl != null) { graphics.closeMCBlock(lbl); } } currentValues[0] = currentFont; if (isTagged(writer) && l.listItem() != null) { text.openMCBlock(l.listItem().getListBody()); } writeLineToContent(l, text, graphics, currentValues, writer.getSpaceCharRatio()); currentFont = (PdfFont)currentValues[0]; displacement += l.height(); text.moveText(-moveTextX, 0); } lines = new ArrayList<PdfLine>(); return displacement; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
float writeLineToContent(final PdfLine line, final PdfContentByte text, final PdfContentByte graphics, final Object currentValues[], final float ratio) throws DocumentException { PdfFont currentFont = (PdfFont)currentValues[0]; float lastBaseFactor = ((Float)currentValues[1]).floatValue(); PdfChunk chunk; int numberOfSpaces; int lineLen; boolean isJustified; float hangingCorrection = 0; float hScale = 1; float lastHScale = Float.NaN; float baseWordSpacing = 0; float baseCharacterSpacing = 0; float glueWidth = 0; float lastX = text.getXTLM() + line.getOriginalWidth(); numberOfSpaces = line.numberOfSpaces(); lineLen = line.getLineLengthUtf32(); // does the line need to be justified? isJustified = line.hasToBeJustified() && (numberOfSpaces != 0 || lineLen > 1); int separatorCount = line.getSeparatorCount(); if (separatorCount > 0) { glueWidth = line.widthLeft() / separatorCount; } else if (isJustified && separatorCount == 0) { if (line.isNewlineSplit() && line.widthLeft() >= lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1)) { if (line.isRTL()) { text.moveText(line.widthLeft() - lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1), 0); } baseWordSpacing = ratio * lastBaseFactor; baseCharacterSpacing = lastBaseFactor; } else { float width = line.widthLeft(); PdfChunk last = line.getChunk(line.size() - 1); if (last != null) { String s = last.toString(); char c; if (s.length() > 0 && hangingPunctuation.indexOf((c = s.charAt(s.length() - 1))) >= 0) { float oldWidth = width; width += last.font().width(c) * 0.4f; hangingCorrection = width - oldWidth; } } float baseFactor = width / (ratio * numberOfSpaces + lineLen - 1); baseWordSpacing = ratio * baseFactor; baseCharacterSpacing = baseFactor; lastBaseFactor = baseFactor; } } else if (line.alignment == Element.ALIGN_LEFT || line.alignment == Element.ALIGN_UNDEFINED) { lastX -= line.widthLeft(); } int lastChunkStroke = line.getLastStrokeChunk(); int chunkStrokeIdx = 0; float xMarker = text.getXTLM(); float baseXMarker = xMarker; float yMarker = text.getYTLM(); boolean adjustMatrix = false; float tabPosition = 0; // looping over all the chunks in 1 line for (Iterator<PdfChunk> j = line.iterator(); j.hasNext(); ) { chunk = j.next(); if (isTagged(writer) && chunk.accessibleElement != null) { text.openMCBlock(chunk.accessibleElement); } BaseColor color = chunk.color(); float fontSize = chunk.font().size(); float ascender = chunk.font().getFont().getFontDescriptor(BaseFont.ASCENT, fontSize); float descender = chunk.font().getFont().getFontDescriptor(BaseFont.DESCENT, fontSize); hScale = 1; if (chunkStrokeIdx <= lastChunkStroke) { float width; if (isJustified) { width = chunk.getWidthCorrected(baseCharacterSpacing, baseWordSpacing); } else { width = chunk.width(); } if (chunk.isStroked()) { PdfChunk nextChunk = line.getChunk(chunkStrokeIdx + 1); if (chunk.isSeparator()) { width = glueWidth; Object[] sep = (Object[])chunk.getAttribute(Chunk.SEPARATOR); DrawInterface di = (DrawInterface)sep[0]; Boolean vertical = (Boolean)sep[1]; if (vertical.booleanValue()) { di.draw(graphics, baseXMarker, yMarker + descender, baseXMarker + line.getOriginalWidth(), ascender - descender, yMarker); } else { di.draw(graphics, xMarker, yMarker + descender, xMarker + width, ascender - descender, yMarker); } } if (chunk.isTab()) { Object[] tab = (Object[])chunk.getAttribute(Chunk.TAB); DrawInterface di = (DrawInterface)tab[0]; tabPosition = ((Float)tab[1]).floatValue() + ((Float)tab[3]).floatValue(); if (tabPosition > xMarker) { di.draw(graphics, xMarker, yMarker + descender, tabPosition, ascender - descender, yMarker); } float tmp = xMarker; xMarker = tabPosition; tabPosition = tmp; } if (chunk.isAttribute(Chunk.BACKGROUND)) { boolean inText = graphics.getInText(); if (inText && isTagged(writer)) { graphics.endText(); } float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.BACKGROUND)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Object bgr[] = (Object[])chunk.getAttribute(Chunk.BACKGROUND); graphics.setColorFill((BaseColor)bgr[0]); float extra[] = (float[])bgr[1]; graphics.rectangle(xMarker - extra[0], yMarker + descender - extra[1] + chunk.getTextRise(), width - subtract + extra[0] + extra[2], ascender - descender + extra[1] + extra[3]); graphics.fill(); graphics.setGrayFill(0); if (inText && isTagged(writer)) { graphics.beginText(true); } } if (chunk.isAttribute(Chunk.UNDERLINE)) { boolean inText = graphics.getInText(); if (inText && isTagged(writer)) { graphics.endText(); } float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.UNDERLINE)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Object unders[][] = (Object[][])chunk.getAttribute(Chunk.UNDERLINE); BaseColor scolor = null; for (int k = 0; k < unders.length; ++k) { Object obj[] = unders[k]; scolor = (BaseColor)obj[0]; float ps[] = (float[])obj[1]; if (scolor == null) scolor = color; if (scolor != null) graphics.setColorStroke(scolor); graphics.setLineWidth(ps[0] + fontSize * ps[1]); float shift = ps[2] + fontSize * ps[3]; int cap2 = (int)ps[4]; if (cap2 != 0) graphics.setLineCap(cap2); graphics.moveTo(xMarker, yMarker + shift); graphics.lineTo(xMarker + width - subtract, yMarker + shift); graphics.stroke(); if (scolor != null) graphics.resetGrayStroke(); if (cap2 != 0) graphics.setLineCap(0); } graphics.setLineWidth(1); if (inText && isTagged(writer)) { graphics.beginText(true); } } if (chunk.isAttribute(Chunk.ACTION)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.ACTION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; PdfAnnotation annot = null; if (chunk.isImage()) { annot = new PdfAnnotation(writer, xMarker, yMarker + chunk.getImageOffsetY(), xMarker + width - subtract, yMarker + chunk.getImageHeight() + chunk.getImageOffsetY(), (PdfAction)chunk.getAttribute(Chunk.ACTION)); } else { annot = new PdfAnnotation(writer, xMarker, yMarker + descender + chunk.getTextRise(), xMarker + width - subtract, yMarker + ascender + chunk.getTextRise(), (PdfAction)chunk.getAttribute(Chunk.ACTION)); } text.addAnnotation(annot); if (isTagged(writer) && chunk.accessibleElement != null) { PdfStructureElement strucElem = structElements.get(chunk.accessibleElement.getId()); if (strucElem != null) { PdfArray kArray = strucElem.getAsArray(PdfName.K); if (kArray == null) { kArray = new PdfArray(); PdfObject k = strucElem.get(PdfName.K); if (k != null) { kArray.add(k); } strucElem.put(PdfName.K, kArray); } PdfDictionary dict = new PdfDictionary(); dict.put(PdfName.TYPE, PdfName.OBJR); dict.put(PdfName.OBJ, annot.getIndirectReference()); kArray.add(dict); } } } if (chunk.isAttribute(Chunk.REMOTEGOTO)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.REMOTEGOTO)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Object obj[] = (Object[])chunk.getAttribute(Chunk.REMOTEGOTO); String filename = (String)obj[0]; if (obj[1] instanceof String) remoteGoto(filename, (String)obj[1], xMarker, yMarker + descender + chunk.getTextRise(), xMarker + width - subtract, yMarker + ascender + chunk.getTextRise()); else remoteGoto(filename, ((Integer)obj[1]).intValue(), xMarker, yMarker + descender + chunk.getTextRise(), xMarker + width - subtract, yMarker + ascender + chunk.getTextRise()); } if (chunk.isAttribute(Chunk.LOCALGOTO)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.LOCALGOTO)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; localGoto((String)chunk.getAttribute(Chunk.LOCALGOTO), xMarker, yMarker, xMarker + width - subtract, yMarker + fontSize); } if (chunk.isAttribute(Chunk.LOCALDESTINATION)) { /*float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.LOCALDESTINATION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection;*/ localDestination((String)chunk.getAttribute(Chunk.LOCALDESTINATION), new PdfDestination(PdfDestination.XYZ, xMarker, yMarker + fontSize, 0)); } if (chunk.isAttribute(Chunk.GENERICTAG)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.GENERICTAG)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Rectangle rect = new Rectangle(xMarker, yMarker, xMarker + width - subtract, yMarker + fontSize); PdfPageEvent pev = writer.getPageEvent(); if (pev != null) pev.onGenericTag(writer, this, rect, (String)chunk.getAttribute(Chunk.GENERICTAG)); } if (chunk.isAttribute(Chunk.PDFANNOTATION)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.PDFANNOTATION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; PdfAnnotation annot = PdfFormField.shallowDuplicate((PdfAnnotation)chunk.getAttribute(Chunk.PDFANNOTATION)); annot.put(PdfName.RECT, new PdfRectangle(xMarker, yMarker + descender, xMarker + width - subtract, yMarker + ascender)); text.addAnnotation(annot); } float params[] = (float[])chunk.getAttribute(Chunk.SKEW); Float hs = (Float)chunk.getAttribute(Chunk.HSCALE); if (params != null || hs != null) { float b = 0, c = 0; if (params != null) { b = params[0]; c = params[1]; } if (hs != null) hScale = hs.floatValue(); text.setTextMatrix(hScale, b, c, 1, xMarker, yMarker); } if (chunk.isAttribute(Chunk.CHAR_SPACING)) { Float cs = (Float) chunk.getAttribute(Chunk.CHAR_SPACING); text.setCharacterSpacing(cs.floatValue()); } if (chunk.isImage()) { Image image = chunk.getImage(); float matrix[] = image.matrix(chunk.getImageScalePercentage()); matrix[Image.CX] = xMarker + chunk.getImageOffsetX() - matrix[Image.CX]; matrix[Image.CY] = yMarker + chunk.getImageOffsetY() - matrix[Image.CY]; graphics.addImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); text.moveText(xMarker + lastBaseFactor + chunk.getImageWidth() - text.getXTLM(), 0); } } if (!chunk.isTabSpace()) xMarker += width; ++chunkStrokeIdx; } if (chunk.font().compareTo(currentFont) != 0) { currentFont = chunk.font(); text.setFontAndSize(currentFont.getFont(), currentFont.size()); } float rise = 0; Object textRender[] = (Object[])chunk.getAttribute(Chunk.TEXTRENDERMODE); int tr = 0; float strokeWidth = 1; BaseColor strokeColor = null; Float fr = (Float)chunk.getAttribute(Chunk.SUBSUPSCRIPT); if (textRender != null) { tr = ((Integer)textRender[0]).intValue() & 3; if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL) text.setTextRenderingMode(tr); if (tr == PdfContentByte.TEXT_RENDER_MODE_STROKE || tr == PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE) { strokeWidth = ((Float)textRender[1]).floatValue(); if (strokeWidth != 1) text.setLineWidth(strokeWidth); strokeColor = (BaseColor)textRender[2]; if (strokeColor == null) strokeColor = color; if (strokeColor != null) text.setColorStroke(strokeColor); } } if (fr != null) rise = fr.floatValue(); if (color != null) text.setColorFill(color); if (rise != 0) text.setTextRise(rise); if (chunk.isImage()) { adjustMatrix = true; } else if (chunk.isHorizontalSeparator()) { PdfTextArray array = new PdfTextArray(); array.add(-glueWidth * 1000f / chunk.font.size() / hScale); text.showText(array); } else if (chunk.isTab()) { PdfTextArray array = new PdfTextArray(); array.add((tabPosition - xMarker) * 1000f / chunk.font.size() / hScale); text.showText(array); } else if (chunk.isTabSpace()) { Float module = (Float)chunk.getAttribute(Chunk.TABSPACE); float increment = module - ((xMarker - text.getXTLM()) % module); xMarker += increment; PdfTextArray array = new PdfTextArray(); array.add(-(increment * 1000f / chunk.font.size() / hScale)); text.showText(array); } // If it is a CJK chunk or Unicode TTF we will have to simulate the // space adjustment. else if (isJustified && numberOfSpaces > 0 && chunk.isSpecialEncoding()) { if (hScale != lastHScale) { lastHScale = hScale; text.setWordSpacing(baseWordSpacing / hScale); text.setCharacterSpacing(baseCharacterSpacing / hScale + text.getCharacterSpacing()); } String s = chunk.toString(); int idx = s.indexOf(' '); if (idx < 0) text.showText(s); else { float spaceCorrection = - baseWordSpacing * 1000f / chunk.font.size() / hScale; PdfTextArray textArray = new PdfTextArray(s.substring(0, idx)); int lastIdx = idx; while ((idx = s.indexOf(' ', lastIdx + 1)) >= 0) { textArray.add(spaceCorrection); textArray.add(s.substring(lastIdx, idx)); lastIdx = idx; } textArray.add(spaceCorrection); textArray.add(s.substring(lastIdx)); text.showText(textArray); } } else { if (isJustified && hScale != lastHScale) { lastHScale = hScale; text.setWordSpacing(baseWordSpacing / hScale); text.setCharacterSpacing(baseCharacterSpacing / hScale + text.getCharacterSpacing()); } text.showText(chunk.toString()); } if (rise != 0) text.setTextRise(0); if (color != null) text.resetRGBColorFill(); if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL) text.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL); if (strokeColor != null) text.resetRGBColorStroke(); if (strokeWidth != 1) text.setLineWidth(1); if (chunk.isAttribute(Chunk.SKEW) || chunk.isAttribute(Chunk.HSCALE)) { adjustMatrix = true; text.setTextMatrix(xMarker, yMarker); } if (chunk.isAttribute(Chunk.CHAR_SPACING)) { text.setCharacterSpacing(baseCharacterSpacing); } if (isTagged(writer) && chunk.accessibleElement != null) { text.closeMCBlock(chunk.accessibleElement); } } if (isJustified) { text.setWordSpacing(0); text.setCharacterSpacing(0); if (line.isNewlineSplit()) lastBaseFactor = 0; } if (adjustMatrix) text.moveText(baseXMarker - text.getXTLM(), 0); currentValues[0] = currentFont; currentValues[1] = new Float(lastBaseFactor); return lastX; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void setThumbnail(final Image image) throws PdfException, DocumentException { writer.addPageDictEntry(PdfName.THUMB, writer.getImageReference(writer.addDirectImageSimple(image))); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void add(final Image image) throws PdfException, DocumentException { if (image.hasAbsoluteY()) { graphics.addImage(image); pageEmpty = false; return; } // if there isn't enough room for the image on this page, save it for the next page if (currentHeight != 0 && indentTop() - currentHeight - image.getScaledHeight() < indentBottom()) { if (!strictImageSequence && imageWait == null) { imageWait = image; return; } newPage(); if (currentHeight != 0 && indentTop() - currentHeight - image.getScaledHeight() < indentBottom()) { imageWait = image; return; } } pageEmpty = false; // avoid endless loops if (image == imageWait) imageWait = null; boolean textwrap = (image.getAlignment() & Image.TEXTWRAP) == Image.TEXTWRAP && !((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE); boolean underlying = (image.getAlignment() & Image.UNDERLYING) == Image.UNDERLYING; float diff = leading / 2; if (textwrap) { diff += leading; } float lowerleft = indentTop() - currentHeight - image.getScaledHeight() -diff; float mt[] = image.matrix(); float startPosition = indentLeft() - mt[4]; if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) startPosition = indentRight() - image.getScaledWidth() - mt[4]; if ((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE) startPosition = indentLeft() + (indentRight() - indentLeft() - image.getScaledWidth()) / 2 - mt[4]; if (image.hasAbsoluteX()) startPosition = image.getAbsoluteX(); if (textwrap) { if (imageEnd < 0 || imageEnd < currentHeight + image.getScaledHeight() + diff) { imageEnd = currentHeight + image.getScaledHeight() + diff; } if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) { // indentation suggested by Pelikan Stephan indentation.imageIndentRight += image.getScaledWidth() + image.getIndentationLeft(); } else { // indentation suggested by Pelikan Stephan indentation.imageIndentLeft += image.getScaledWidth() + image.getIndentationRight(); } } else { if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) startPosition -= image.getIndentationRight(); else if ((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE) startPosition += image.getIndentationLeft() - image.getIndentationRight(); else startPosition += image.getIndentationLeft(); } graphics.addImage(image, mt[0], mt[1], mt[2], mt[3], startPosition, lowerleft - mt[5]); if (!(textwrap || underlying)) { currentHeight += image.getScaledHeight() + diff; flushLines(); text.moveText(0, - (image.getScaledHeight() + diff)); newLine(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addPTable(final PdfPTable ptable) throws DocumentException { ColumnText ct = new ColumnText(isTagged(writer) ? text : writer.getDirectContent()); // if the table prefers to be on a single page, and it wouldn't //fit on the current page, start a new page. if (ptable.getKeepTogether() && !fitsPage(ptable, 0f) && currentHeight > 0) { newPage(); } if (currentHeight == 0) { ct.setAdjustFirstLine(false); } ct.addElement(ptable); boolean he = ptable.isHeadersInEvent(); ptable.setHeadersInEvent(true); int loop = 0; while (true) { ct.setSimpleColumn(indentLeft(), indentBottom(), indentRight(), indentTop() - currentHeight); int status = ct.go(); if ((status & ColumnText.NO_MORE_TEXT) != 0) { if (isTagged(writer)) { text.setTextMatrix(indentLeft(), ct.getYLine()); } else { text.moveText(0, ct.getYLine() - indentTop() + currentHeight); } currentHeight = indentTop() - ct.getYLine(); break; } if (indentTop() - currentHeight == ct.getYLine()) ++loop; else loop = 0; if (loop == 3) { throw new DocumentException(MessageLocalization.getComposedMessage("infinite.table.loop")); } newPage(); if (isTagged(writer)) { ct.setCanvas(text); } } ptable.setHeadersInEvent(he); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
private void addDiv(final PdfDiv div) throws DocumentException { if (floatingElements == null) { floatingElements = new ArrayList<Element>(); } floatingElements.add(div); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
private void flushFloatingElements() throws DocumentException { if (floatingElements != null && !floatingElements.isEmpty()) { ArrayList<Element> cachedFloatingElements = floatingElements; floatingElements = null; FloatLayout fl = new FloatLayout(cachedFloatingElements, false); int loop = 0; while (true) { fl.setSimpleColumn(indentLeft(), indentBottom(), indentRight(), indentTop() - currentHeight); try { int status = fl.layout(isTagged(writer) ? text : writer.getDirectContent(), false); if ((status & ColumnText.NO_MORE_TEXT) != 0) { if (isTagged(writer)) { text.setTextMatrix(indentLeft(), fl.getYLine()); } else { text.moveText(0, fl.getYLine() - indentTop() + currentHeight); } currentHeight = indentTop() - fl.getYLine(); break; } } catch (Exception exc) { return; } if (indentTop() - currentHeight == fl.getYLine() || isPageEmpty()) ++loop; else { loop = 0; } if (loop == 2) { return; } newPage(); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type3Glyph.java
public void addImage(Image image, float a, float b, float c, float d, float e, float f, boolean inlineImage) throws DocumentException { if (!colorized && (!image.isMask() || !(image.getBpc() == 1 || image.getBpc() > 0xff))) throw new DocumentException(MessageLocalization.getComposedMessage("not.colorized.typed3.fonts.only.accept.mask.images")); super.addImage(image, a, b, c, d, e, f, inlineImage); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
public void addPage(Rectangle rect, int rotation) throws DocumentException { PdfRectangle mediabox = new PdfRectangle(rect, rotation); PageResources resources = new PageResources(); PdfPage page = new PdfPage(mediabox, new HashMap<String, PdfRectangle>(), resources.getResources(), 0); page.put(PdfName.TABS, getTabs()); root.addPage(page); ++currentPageNumber; }
// 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/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/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/PdfPatternPainter.java
public void addImage(Image image, float a, float b, float c, float d, float e, float f) throws DocumentException { if (stencil && !image.isMask()) checkNoColor(); super.addImage(image, a, b, c, d, e, f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFormsImp.java
public void copyDocumentFields(PdfReader reader) throws DocumentException { if (!reader.isOpenedWithFullPermissions()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password")); 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()); fields.add(reader.getAcroFields()); updateCalculationOrder(reader); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDiv.java
public int layout(final PdfContentByte canvas, boolean useAscender, boolean simulate, final float llx, final float lly, final float urx, final float ury) throws DocumentException { float leftX = Math.min(llx, urx); float maxY = Math.max(lly, ury); float minY = Math.min(lly, ury); float rightX = Math.max(llx, urx); float yLine = maxY; boolean contentCutByFixedHeight = false; if (width != null && width > 0) { if (width < rightX - leftX) { rightX = leftX + width; } else if (width > rightX - leftX) { return ColumnText.NO_MORE_COLUMN; } } else if (percentageWidth != null) { contentWidth = (rightX - leftX) * percentageWidth; rightX = leftX + contentWidth; } if (height != null && height > 0) { if (height < maxY - minY) { minY = maxY - height; contentCutByFixedHeight = true; } else if (height > maxY - minY) { return ColumnText.NO_MORE_COLUMN; } } else if (percentageHeight != null) { if (percentageHeight < 1.0) { contentCutByFixedHeight = true; } contentHeight = (maxY - minY) * percentageHeight; minY = maxY - contentHeight; } if (!simulate && position == PdfDiv.PositionType.RELATIVE) { Float translationX = null; if (left != null) { translationX = left; } else if (right != null) { translationX = -right; } else { translationX = 0f; } Float translationY = null; if (top != null) { translationY = -top; } else if (bottom != null) { translationY = bottom; } else { translationY = 0f; } canvas.saveState(); canvas.transform(new AffineTransform(1f, 0, 0, 1f, translationX, translationY)); } if (!simulate) { if (backgroundColor != null && getActualWidth() > 0 && getActualHeight() > 0) { float backgroundWidth = getActualWidth(); float backgroundHeight = getActualHeight(); if (width != null) { backgroundWidth = width > 0 ? width : 0; } if (height != null) { backgroundHeight = height > 0 ? height : 0; } if (backgroundWidth > 0 && backgroundHeight > 0) { Rectangle background = new Rectangle(leftX, maxY - backgroundHeight, leftX + backgroundWidth, maxY); background.setBackgroundColor(backgroundColor); canvas.rectangle(background); } } } if (percentageWidth == null) { contentWidth = 0; } if (percentageHeight == null) { contentHeight = 0; } minY += paddingBottom; leftX += paddingLeft; rightX -= paddingRight; yLine -= paddingTop; int status = ColumnText.NO_MORE_TEXT; if (!content.isEmpty()) { FloatLayout floatLayout = null; if (this.floatLayout == null) { ArrayList<Element> floatingElements = new ArrayList<Element>(); floatingElements.addAll(content); if (simulate) { floatLayout = new FloatLayout(floatingElements, useAscender); } else { floatLayout = this.floatLayout = new FloatLayout(floatingElements, useAscender); } } else { if (simulate) { ArrayList<Element> floatingElements = new ArrayList<Element>(); floatingElements.addAll(this.floatLayout.content); floatLayout = new FloatLayout(floatingElements, useAscender); } else { floatLayout = this.floatLayout; } } floatLayout.setSimpleColumn(leftX, minY, rightX, yLine); status = floatLayout.layout(canvas, simulate); yLine = floatLayout.getYLine(); if (percentageWidth == null && contentWidth < floatLayout.getFilledWidth()) { contentWidth = floatLayout.getFilledWidth(); } } if (!simulate && position == PdfDiv.PositionType.RELATIVE) { canvas.restoreState(); } yLine -= paddingBottom; if (percentageHeight == null) { contentHeight = maxY - yLine; } if (percentageWidth == null) { contentWidth += paddingLeft + paddingRight; } return contentCutByFixedHeight ? ColumnText.NO_MORE_TEXT : status; }
// 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/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 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 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/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 void loadCMaps() throws DocumentException { try { fontDesc = allFonts.get(fontName); hMetrics = (IntHashtable)fontDesc.get("W"); vMetrics = (IntHashtable)fontDesc.get("W2"); String registry = (String)fontDesc.get("Registry"); uniMap = ""; for (String name : registryNames.get(registry + "_Uni")) { uniMap = name; if (name.endsWith("V") && vertical) break; if (!name.endsWith("V") && !vertical) break; } if (cidDirect) { cidUni = CMapCache.getCachedCMapCidUni(uniMap); } else { uniCid = CMapCache.getCachedCMapUniCid(uniMap); cidByte = CMapCache.getCachedCMapCidByte(CMap); } } catch (Exception ex) { throw new DocumentException(ex); } }
// 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/PdfPTable.java
public void setWidths(final float relativeWidths[]) throws DocumentException { if (relativeWidths.length != getNumberOfColumns()) throw new DocumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); this.relativeWidths = new float[relativeWidths.length]; System.arraycopy(relativeWidths, 0, this.relativeWidths, 0, relativeWidths.length); absoluteWidths = new float[relativeWidths.length]; totalHeight = 0; calculateWidths(); calculateHeights(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setWidths(final int relativeWidths[]) throws DocumentException { float tb[] = new float[relativeWidths.length]; for (int k = 0; k < relativeWidths.length; ++k) tb[k] = relativeWidths[k]; setWidths(tb); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setTotalWidth(final float columnWidth[]) throws DocumentException { if (columnWidth.length != getNumberOfColumns()) throw new DocumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); totalWidth = 0; for (int k = 0; k < columnWidth.length; ++k) totalWidth += columnWidth[k]; setWidths(columnWidth); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setWidthPercentage(final float columnWidth[], final Rectangle pageSize) throws DocumentException { if (columnWidth.length != getNumberOfColumns()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); float totalWidth = 0; for (int k = 0; k < columnWidth.length; ++k) totalWidth += columnWidth[k]; widthPercentage = totalWidth / (pageSize.getRight() - pageSize.getLeft()) * 100f; setWidths(columnWidth); }
// 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/FloatLayout.java
public int layout(PdfContentByte canvas, boolean simulate) throws DocumentException { compositeColumn.setCanvas(canvas); int status = ColumnText.NO_MORE_TEXT; filledWidth = 0; ArrayList<Element> floatingElements = new ArrayList<Element>(); List<Element> content = simulate ? new ArrayList<Element>(this.content) : this.content; while (!content.isEmpty()) { if (content.get(0) instanceof PdfDiv) { PdfDiv floatingElement = (PdfDiv)content.get(0); if (floatingElement.getFloatType() == PdfDiv.FloatType.LEFT || floatingElement.getFloatType() == PdfDiv.FloatType.RIGHT) { floatingElements.add(floatingElement); content.remove(0); } else { if (!floatingElements.isEmpty()) { status = floatingLayout(floatingElements, simulate); if ((status & ColumnText.NO_MORE_TEXT) == 0) { break; } } content.remove(0); status = floatingElement.layout(canvas, useAscender, true, floatLeftX, minY, floatRightX, yLine); if (!simulate) { canvas.openMCBlock(floatingElement); status = floatingElement.layout(canvas, useAscender, simulate, floatLeftX, minY, floatRightX, yLine); canvas.closeMCBlock(floatingElement); } yLine -= floatingElement.getActualHeight(); if (floatingElement.getActualWidth() > filledWidth) { filledWidth = floatingElement.getActualWidth(); } if ((status & ColumnText.NO_MORE_TEXT) == 0) { content.add(0, floatingElement); break; } } } else { floatingElements.add(content.get(0)); content.remove(0); } } if ((status & ColumnText.NO_MORE_TEXT) != 0 && !floatingElements.isEmpty()) { status = floatingLayout(floatingElements, simulate); } content.addAll(0, floatingElements); return status; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FloatLayout.java
private int floatingLayout(List<Element> floatingElements, boolean simulate) throws DocumentException { int status = ColumnText.NO_MORE_TEXT; float minYLine = yLine; float leftWidth = 0; float rightWidth = 0; ColumnText currentCompositeColumn = compositeColumn; if (simulate) { currentCompositeColumn = ColumnText.duplicate(compositeColumn); } while (!floatingElements.isEmpty()) { Element nextElement = floatingElements.get(0); floatingElements.remove(0); if (nextElement instanceof PdfDiv) { PdfDiv floatingElement = (PdfDiv) nextElement; status = floatingElement.layout(compositeColumn.getCanvas(), useAscender, true, floatLeftX, minY, floatRightX, yLine); if ((status & ColumnText.NO_MORE_TEXT) == 0) { yLine = minYLine; floatLeftX = leftX; floatRightX = rightX; status = floatingElement.layout(compositeColumn.getCanvas(), useAscender, true, floatLeftX, minY, floatRightX, yLine); if ((status & ColumnText.NO_MORE_TEXT) == 0) { floatingElements.add(0, floatingElement); break; } } if (floatingElement.getFloatType() == PdfDiv.FloatType.LEFT) { status = floatingElement.layout(compositeColumn.getCanvas(), useAscender, simulate, floatLeftX, minY, floatRightX, yLine); floatLeftX += floatingElement.getActualWidth(); leftWidth += floatingElement.getActualWidth(); } else if (floatingElement.getFloatType() == PdfDiv.FloatType.RIGHT) { status = floatingElement.layout(compositeColumn.getCanvas(), useAscender, simulate, floatRightX - floatingElement.getActualWidth() - 0.01f, minY, floatRightX, yLine); floatRightX -= floatingElement.getActualWidth(); rightWidth += floatingElement.getActualWidth(); } minYLine = Math.min(minYLine, yLine - floatingElement.getActualHeight()); } else { if (nextElement instanceof Spaceable) { yLine -= ((Spaceable) nextElement).getSpacingBefore(); } if (simulate) { if (nextElement instanceof PdfPTable) currentCompositeColumn.addElement(new PdfPTable((PdfPTable)nextElement)); else currentCompositeColumn.addElement(nextElement); } else { currentCompositeColumn.addElement(nextElement); } if (yLine > minYLine) currentCompositeColumn.setSimpleColumn(floatLeftX, yLine, floatRightX, minYLine); else currentCompositeColumn.setSimpleColumn(floatLeftX, yLine, floatRightX, minY); currentCompositeColumn.setFilledWidth(0); status = currentCompositeColumn.go(simulate); if (yLine > minYLine && (floatLeftX > leftX || floatRightX < rightX) && (status & ColumnText.NO_MORE_TEXT) == 0) { yLine = minYLine; floatLeftX = leftX; floatRightX = rightX; if (leftWidth != 0 && rightWidth != 0) { filledWidth = rightX - leftX; } else { if (leftWidth > filledWidth) { filledWidth = leftWidth; } if (rightWidth > filledWidth) { filledWidth = rightWidth; } } leftWidth = 0; rightWidth = 0; if (simulate && nextElement instanceof PdfPTable) { currentCompositeColumn.addElement(new PdfPTable((PdfPTable)nextElement)); } currentCompositeColumn.setSimpleColumn(floatLeftX, yLine, floatRightX, minY); status = currentCompositeColumn.go(simulate); minYLine = currentCompositeColumn.getYLine() + currentCompositeColumn.getDescender(); yLine = minYLine; if (currentCompositeColumn.getFilledWidth() > filledWidth) { filledWidth = currentCompositeColumn.getFilledWidth(); } } else { if (rightWidth > 0) { rightWidth += currentCompositeColumn.getFilledWidth(); } else if (leftWidth > 0) { leftWidth += currentCompositeColumn.getFilledWidth(); } else if (currentCompositeColumn.getFilledWidth() > filledWidth) { filledWidth = currentCompositeColumn.getFilledWidth(); } minYLine = Math.min(currentCompositeColumn.getYLine() + currentCompositeColumn.getDescender(), minYLine); yLine = currentCompositeColumn.getYLine() + currentCompositeColumn.getDescender(); } if ((status & ColumnText.NO_MORE_TEXT) == 0) { if (!simulate) { floatingElements.addAll(0, currentCompositeColumn.getCompositeElements()); currentCompositeColumn.getCompositeElements().clear(); } else { floatingElements.add(0, nextElement); currentCompositeColumn.setText(null); } break; } else { currentCompositeColumn.setText(null); } } } if (leftWidth != 0 && rightWidth != 0) { filledWidth = rightX - leftX; } else { if (leftWidth > filledWidth) { filledWidth = leftWidth; } if (rightWidth > filledWidth) { filledWidth = rightWidth; } } yLine = minYLine; floatLeftX = leftX; floatRightX = rightX; return status; }
// 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 setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final boolean strength128Bits) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(userPassword, ownerPassword, permissions, strength128Bits ? PdfWriter.STANDARD_ENCRYPTION_128 : PdfWriter.STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final int encryptionType) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(userPassword, ownerPassword, permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final boolean strength, final String userPassword, final String ownerPassword, final int permissions) throws DocumentException { setEncryption(DocWriter.getISOBytes(userPassword), DocWriter.getISOBytes(ownerPassword), permissions, strength); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final int encryptionType, final String userPassword, final String ownerPassword, final int permissions) throws DocumentException { setEncryption(DocWriter.getISOBytes(userPassword), DocWriter.getISOBytes(ownerPassword), permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final Certificate[] certs, final int[] permissions, final int encryptionType) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(certs, permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setThumbnail(final Image image, final int page) throws PdfException, DocumentException { stamper.setThumbnail(image, page); }
// 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/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/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/Document.java
public boolean add(Element element) throws DocumentException { if (close) { throw new DocumentException(MessageLocalization.getComposedMessage("the.document.has.been.closed.you.can.t.add.any.elements")); } if (!open && element.isContent()) { throw new DocumentException(MessageLocalization.getComposedMessage("the.document.is.not.open.yet.you.can.only.add.meta.information")); } boolean success = false; if (element instanceof ChapterAutoNumber) { chapternumber = ((ChapterAutoNumber)element).setAutomaticNumber(chapternumber); } for (DocListener listener : listeners) { success |= listener.add(element); } if (element instanceof LargeElement) { LargeElement e = (LargeElement)element; if (!e.isComplete()) e.flushContent(); } return success; }
// 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 { worker.carriageReturn(); if (worker.isPendingLI()) worker.endElement(HtmlTags.LI); worker.setSkipText(true); worker.updateChain(tag, attrs);; worker.pushToStack(worker.createList(tag)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); if (worker.isPendingLI()) worker.endElement(HtmlTags.LI); worker.setSkipText(false); worker.updateChain(tag); worker.processList(); }
// 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 { worker.carriageReturn(); worker.pushToStack(worker.createLineSeparator(attrs)); }
// 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 { worker.carriageReturn(); if (!attrs.containsKey(HtmlTags.SIZE)) { int v = 7 - Integer.parseInt(tag.substring(1)); attrs.put(HtmlTags.SIZE, Integer.toString(v)); } worker.updateChain(tag, attrs); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); worker.updateChain(tag); }
// 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 { worker.carriageReturn(); if (worker.isPendingLI()) worker.endElement(tag); worker.setSkipText(false); worker.setPendingLI(true); worker.updateChain(tag, attrs); worker.pushToStack(worker.createListItem()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); worker.setPendingLI(false); worker.setSkipText(true); worker.updateChain(tag); worker.processListItem(); }
// 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 { worker.carriageReturn(); if (!attrs.containsKey(HtmlTags.FACE)) { attrs.put(HtmlTags.FACE, "Courier"); } worker.updateChain(tag, attrs); worker.setInsidePRE(true); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); worker.updateChain(tag); worker.setInsidePRE(false); }
// 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 { worker.carriageReturn(); worker.updateChain(tag, attrs); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); worker.updateChain(tag); }
// 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 { worker.carriageReturn(); TableWrapper table = new TableWrapper(attrs); worker.pushToStack(table); worker.pushTableState(); worker.setPendingTD(false); worker.setPendingTR(false); worker.setSkipText(true); // Table alignment should not affect children elements, thus remove attrs.remove(HtmlTags.ALIGN); // In case this is a nested table reset colspan and rowspan attrs.put(HtmlTags.COLSPAN, "1"); attrs.put(HtmlTags.ROWSPAN, "1"); worker.updateChain(tag, attrs); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); if (worker.isPendingTR()) worker.endElement(HtmlTags.TR); worker.updateChain(tag); worker.processTable(); worker.popTableState(); worker.setSkipText(false); }
// 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 { worker.carriageReturn(); if (worker.isPendingTR()) worker.endElement(tag); worker.setSkipText(true); worker.setPendingTR(true); worker.updateChain(tag, attrs); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); if (worker.isPendingTD()) worker.endElement(HtmlTags.TD); worker.setPendingTR(false); worker.updateChain(tag); worker.processRow(); worker.setSkipText(true); }
// 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 { worker.carriageReturn(); if (worker.isPendingTD()) worker.endElement(tag); worker.setSkipText(false); worker.setPendingTD(true); worker.updateChain(HtmlTags.TD, attrs); worker.pushToStack(worker.createCell(tag)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); worker.setPendingTD(false); worker.updateChain(HtmlTags.TD); worker.setSkipText(true); }
// 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 carriageReturn() throws DocumentException { if (currentParagraph == null) return; if (stack.empty()) document.add(currentParagraph); else { Element obj = stack.pop(); if (obj instanceof TextElementArray) { TextElementArray current = (TextElementArray) obj; current.add(currentParagraph); } stack.push(obj); } currentParagraph = null; }
// 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 void processList() throws DocumentException { if (stack.empty()) return; Element obj = stack.pop(); if (!(obj instanceof com.itextpdf.text.List)) { stack.push(obj); return; } if (stack.empty()) document.add(obj); else ((TextElementArray) stack.peek()).add(obj); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void processListItem() throws DocumentException { if (stack.empty()) return; Element obj = stack.pop(); if (!(obj instanceof ListItem)) { stack.push(obj); return; } if (stack.empty()) { document.add(obj); return; } ListItem item = (ListItem) obj; Element list = stack.pop(); if (!(list instanceof com.itextpdf.text.List)) { stack.push(list); return; } ((com.itextpdf.text.List) list).add(item); item.adjustListSymbolFont(); stack.push(list); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void processImage(final Image img, final Map<String, String> attrs) throws DocumentException { ImageProcessor processor = (ImageProcessor)providers.get(HTMLWorker.IMG_PROCESSOR); if (processor == null || !processor.process(img, attrs, chain, document)) { String align = attrs.get(HtmlTags.ALIGN); if (align != null) { carriageReturn(); } if (currentParagraph == null) { currentParagraph = createParagraph(); } currentParagraph.add(new Chunk(img, 0, 0, true)); currentParagraph.setAlignment(HtmlUtilities.alignmentValue(align)); if (align != null) { carriageReturn(); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void processTable() throws DocumentException{ TableWrapper table = (TableWrapper) stack.pop(); PdfPTable tb = table.createTable(); tb.setSplitRows(true); if (stack.empty()) document.add(tb); else ((TextElementArray) stack.peek()).add(tb); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public boolean add(final Element element) throws DocumentException { objectList.add(element); return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
public boolean add(Element element) throws DocumentException { return false; }
(Lib) IOException 55
              
// 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 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/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/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 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 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 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/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/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 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 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/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/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/TiffImage.java
protected static Image getTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s) { try { int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); int predictor = 1; TIFFLZWDecoder lzwDecoder = null; switch (compression) { case TIFFConstants.COMPRESSION_NONE: case TIFFConstants.COMPRESSION_LZW: case TIFFConstants.COMPRESSION_PACKBITS: case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: case TIFFConstants.COMPRESSION_OJPEG: case TIFFConstants.COMPRESSION_JPEG: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.compression.1.is.not.supported", compression)); } int photometric = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); switch (photometric) { case TIFFConstants.PHOTOMETRIC_MINISWHITE: case TIFFConstants.PHOTOMETRIC_MINISBLACK: case TIFFConstants.PHOTOMETRIC_RGB: case TIFFConstants.PHOTOMETRIC_SEPARATED: case TIFFConstants.PHOTOMETRIC_PALETTE: break; default: if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.photometric.1.is.not.supported", photometric)); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } if (dir.isTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) && dir.getFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("planar.images.are.not.supported")); int extraSamples = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES)) extraSamples = 1; int samplePerPixel = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4 samplePerPixel = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL); int bitsPerSample = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE)) bitsPerSample = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE); switch (bitsPerSample) { case 1: case 2: case 4: case 8: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample)); } Image img = null; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); int fillOrder = 1; boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE) { TIFFField predictorField = dir.getField(TIFFConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.getAsInt(0); if (predictor != 1 && predictor != 2) { throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.value.for.predictor.in.tiff.file")); } if (predictor == 2 && bitsPerSample != 8) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample)); } } } if (compression == TIFFConstants.COMPRESSION_LZW) { lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel); } int rowsLeft = h; ByteArrayOutputStream stream = null; ByteArrayOutputStream mstream = null; DeflaterOutputStream zip = null; DeflaterOutputStream mzip = null; if (extraSamples > 0) { mstream = new ByteArrayOutputStream(); mzip = new DeflaterOutputStream(mstream); } CCITTG4Encoder g4 = null; if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4 = new CCITTG4Encoder(w); } else { stream = new ByteArrayOutputStream(); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) zip = new DeflaterOutputStream(stream); } if (compression == TIFFConstants.COMPRESSION_OJPEG) { // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and // is often missing if ((!dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET))) { throw new IOException(MessageLocalization.getComposedMessage("missing.tag.s.for.ojpeg.compression")); } int jpegOffset = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET); int jpegLength = (int)s.length() - jpegOffset; if (dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT)) { jpegLength = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0]; } byte[] jpeg = new byte[Math.min(jpegLength, (int)s.length() - jpegOffset)]; int posFilePointer = (int)s.getFilePointer(); posFilePointer += jpegOffset; s.seek(posFilePointer); s.readFully(jpeg); img = new Jpeg(jpeg); } else if (compression == TIFFConstants.COMPRESSION_JPEG) { if (size.length > 1) throw new IOException(MessageLocalization.getComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.length)); byte[] jpeg = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(jpeg); // if quantization and/or Huffman tables are stored separately in the tiff, // we need to add them to the jpeg data TIFFField jpegtables = dir.getField(TIFFConstants.TIFFTAG_JPEGTABLES); if (jpegtables != null) { byte[] temp = jpegtables.getAsBytes(); int tableoffset = 0; int tablelength = temp.length; // remove FFD8 from start if (temp[0] == (byte) 0xFF && temp[1] == (byte) 0xD8) { tableoffset = 2; tablelength -= 2; } // remove FFD9 from end if (temp[temp.length-2] == (byte) 0xFF && temp[temp.length-1] == (byte) 0xD9) tablelength -= 2; byte[] tables = new byte[tablelength]; System.arraycopy(temp, tableoffset, tables, 0, tablelength); // TODO insert after JFIF header, instead of at the start byte[] jpegwithtables = new byte[jpeg.length + tables.length]; System.arraycopy(jpeg, 0, jpegwithtables, 0, 2); System.arraycopy(tables, 0, jpegwithtables, 2, tables.length); System.arraycopy(jpeg, 2, jpegwithtables, tables.length+2, jpeg.length-2); jpeg = jpegwithtables; } img = new Jpeg(jpeg); } else { for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); byte outBuf[] = null; if (compression != TIFFConstants.COMPRESSION_NONE) outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height]; if (reverse) TIFFFaxDecoder.reverseBits(im); switch (compression) { case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: inflate(im, outBuf); applyPredictor(outBuf, predictor, w, height, samplePerPixel); break; case TIFFConstants.COMPRESSION_NONE: outBuf = im; break; case TIFFConstants.COMPRESSION_PACKBITS: decodePackbits(im, outBuf); break; case TIFFConstants.COMPRESSION_LZW: lzwDecoder.decode(im, outBuf, height); break; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4.fax4Encode(outBuf, height); } else { if (extraSamples > 0) ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height); else zip.write(outBuf); } rowsLeft -= rowsStrip; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { img = Image.getInstance(w, h, false, Image.CCITTG4, photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.close()); } else { zip.close(); img = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.toByteArray()); img.setDeflated(true); } } img.setDpi(dpiX, dpiY); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) { if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (samplePerPixel - extraSamples == icc_prof.getNumComponents()) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } if (dir.isTagPresent(TIFFConstants.TIFFTAG_COLORMAP)) { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_COLORMAP); char rgb[] = fd.getAsChars(); byte palette[] = new byte[rgb.length]; int gColor = rgb.length / 3; int bColor = gColor * 2; for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)(rgb[k] >>> 8); palette[k * 3 + 1] = (byte)(rgb[k + gColor] >>> 8); palette[k * 3 + 2] = (byte)(rgb[k + bColor] >>> 8); } // Colormap components are supposed to go from 0 to 655535 but, // as usually, some tiff producers just put values from 0 to 255. // Let's check for these broken tiffs. boolean colormapBroken = true; for (int k = 0; k < palette.length; ++k) { if (palette[k] != 0) { colormapBroken = false; break; } } if (colormapBroken) { for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)rgb[k]; palette[k * 3 + 1] = (byte)rgb[k + gColor]; palette[k * 3 + 2] = (byte)rgb[k + bColor]; } } PdfArray indexed = new PdfArray(); indexed.add(PdfName.INDEXED); indexed.add(PdfName.DEVICERGB); indexed.add(new PdfNumber(gColor - 1)); indexed.add(new PdfString(palette)); PdfDictionary additional = new PdfDictionary(); additional.put(PdfName.COLORSPACE, indexed); img.setAdditional(additional); } img.setOriginalType(Image.ORIGINAL_TIFF); } if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE) img.setInverted(true); if (rotation != 0) img.setInitialRotation(rotation); if (extraSamples > 0) { mzip.close(); Image mimg = Image.getInstance(w, h, 1, bitsPerSample, mstream.toByteArray()); mimg.makeMask(); mimg.setDeflated(true); img.setImageMask(mimg); } return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// 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/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/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/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/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/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/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/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/fonts/cmaps/CMapToUnicode.java
Override void addChar(PdfString mark, PdfObject code) { try { byte[] src = mark.getBytes(); String dest = createStringFromBytes(code.getBytes()); if (src.length == 1) { singleByteMappings.put(Integer.valueOf(src[0] & 0xff), dest); } else if (src.length == 2) { int intSrc = src[0] & 0xFF; intSrc <<= 8; intSrc |= src[1] & 0xFF; doubleByteMappings.put(Integer.valueOf(intSrc), dest); } else { throw new IOException(MessageLocalization.getComposedMessage("mapping.code.should.be.1.or.two.bytes.and.not.1", src.length)); } } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// 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/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/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/OcspClientBouncyCastle.java
public byte[] getEncoded(X509Certificate checkCert, X509Certificate rootCert, String url) { try { BasicOCSPResp basicResponse = getBasicOCSPResp(checkCert, rootCert, url); if (basicResponse != null) { SingleResp[] responses = basicResponse.getResponses(); if (responses.length == 1) { SingleResp resp = responses[0]; Object status = resp.getCertStatus(); if (status == CertificateStatus.GOOD) { return basicResponse.getEncoded(); } else if (status instanceof org.bouncycastle.ocsp.RevokedStatus) { throw new IOException(MessageLocalization.getComposedMessage("ocsp.status.is.revoked")); } else { throw new IOException(MessageLocalization.getComposedMessage("ocsp.status.is.unknown")); } } } } catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); } return null; }
// 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/CrlClientOnline.java
public Collection<byte[]> getEncoded(X509Certificate checkCert, String url) { if (checkCert == null) return null; List<URL> urllist = new ArrayList<URL>(urls); if (urllist.size() == 0) { LOGGER.info("Looking for CRL for certificate " + checkCert.getSubjectDN()); try { if (url == null) url = CertificateUtil.getCRLURL(checkCert); if (url == null) throw new NullPointerException(); urllist.add(new URL(url)); LOGGER.info("Found CRL url: " + url); } catch (Exception e) { LOGGER.info("Skipped CRL url: " + e.getMessage()); } } ArrayList<byte[]> ar = new ArrayList<byte[]>(); for (URL urlt : urllist) { try { LOGGER.info("Checking CRL: " + urlt); HttpURLConnection con = (HttpURLConnection)urlt.openConnection(); if (con.getResponseCode() / 100 != 2) { throw new IOException(MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode())); } //Get Response InputStream inp = (InputStream) con.getContent(); byte[] buf = new byte[1024]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while (true) { int n = inp.read(buf, 0, buf.length); if (n <= 0) break; bout.write(buf, 0, n); } inp.close(); ar.add(bout.toByteArray()); LOGGER.info("Added CRL found at: " + urlt); } catch (Exception e) { LOGGER.info("Skipped CRL: " + e.getMessage() + " for " + urlt); } } return ar; }
// 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(); }
3
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/TSAClientBouncyCastle.java
catch (IOException ioe) { throw new IOException(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL)); }
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. &lt;, &#187;, 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; }
(Domain) WriterException 34
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void embedDataBits(BitVector dataBits, int maskPattern, ByteMatrix matrix) throws WriterException { int bitIndex = 0; int direction = -1; // Start from the right bottom cell. int x = matrix.getWidth() - 1; int y = matrix.getHeight() - 1; while (x > 0) { // Skip the vertical timing pattern. if (x == 6) { x -= 1; } while (y >= 0 && y < matrix.getHeight()) { for (int i = 0; i < 2; ++i) { int xx = x - i; // Skip the cell if it's not empty. if (!isEmpty(matrix.get(xx, y))) { continue; } int bit; if (bitIndex < dataBits.size()) { bit = dataBits.at(bitIndex); ++bitIndex; } else { // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described // in 8.4.9 of JISX0510:2004 (p. 24). bit = 0; } // Skip masking if mask_pattern is -1. if (maskPattern != -1) { if (MaskUtil.getDataMaskBit(maskPattern, xx, y)) { bit ^= 0x1; } } matrix.set(xx, y, bit); } y += direction; } direction = -direction; // Reverse the direction. y += direction; x -= 2; // Move to the left. } // All bits should be consumed. if (bitIndex != dataBits.size()) { throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitVector bits) throws WriterException { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new WriterException("Invalid mask pattern"); } int typeInfo = (ecLevel.getBits() << 3) | maskPattern; bits.appendBits(typeInfo, 5); int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); bits.appendBits(bchCode, 10); BitVector maskBits = new BitVector(); maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); bits.xor(maskBits); if (bits.size() != 15) { // Just in case. throw new WriterException("should not happen but we got: " + bits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void makeVersionInfoBits(int version, BitVector bits) throws WriterException { bits.appendBits(version, 6); int bchCode = calculateBCHCode(version, VERSION_INFO_POLY); bits.appendBits(bchCode, 12); if (bits.size() != 18) { // Just in case. throw new WriterException("should not happen but we got: " + bits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedTimingPatterns(ByteMatrix matrix) throws WriterException { // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical // separation patterns (size 1). Thus, 8 = 7 + 1. for (int i = 8; i < matrix.getWidth() - 8; ++i) { int bit = (i + 1) % 2; // Horizontal line. if (!isValidValue(matrix.get(i, 6))) { throw new WriterException(); } if (isEmpty(matrix.get(i, 6))) { matrix.set(i, 6, bit); } // Vertical line. if (!isValidValue(matrix.get(6, i))) { throw new WriterException(); } if (isEmpty(matrix.get(6, i))) { matrix.set(6, i, bit); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) throws WriterException { if (matrix.get(8, matrix.getHeight() - 8) == 0) { throw new WriterException(); } matrix.set(8, matrix.getHeight() - 8, 1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedHorizontalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (HORIZONTAL_SEPARATION_PATTERN[0].length != 8 || HORIZONTAL_SEPARATION_PATTERN.length != 1) { throw new WriterException("Bad horizontal separation pattern"); } for (int x = 0; x < 8; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart))) { throw new WriterException(); } matrix.set(xStart + x, yStart, HORIZONTAL_SEPARATION_PATTERN[0][x]); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedVerticalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (VERTICAL_SEPARATION_PATTERN[0].length != 1 || VERTICAL_SEPARATION_PATTERN.length != 7) { throw new WriterException("Bad vertical separation pattern"); } for (int y = 0; y < 7; ++y) { if (!isEmpty(matrix.get(xStart, yStart + y))) { throw new WriterException(); } matrix.set(xStart, yStart + y, VERTICAL_SEPARATION_PATTERN[y][0]); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedPositionAdjustmentPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (POSITION_ADJUSTMENT_PATTERN[0].length != 5 || POSITION_ADJUSTMENT_PATTERN.length != 5) { throw new WriterException("Bad position adjustment"); } for (int y = 0; y < 5; ++y) { for (int x = 0; x < 5; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart + y))) { throw new WriterException(); } matrix.set(xStart + x, yStart + y, POSITION_ADJUSTMENT_PATTERN[y][x]); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedPositionDetectionPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (POSITION_DETECTION_PATTERN[0].length != 7 || POSITION_DETECTION_PATTERN.length != 7) { throw new WriterException("Bad position detection pattern"); } for (int y = 0; y < 7; ++y) { for (int x = 0; x < 7; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart + y))) { throw new WriterException(); } matrix.set(xStart + x, yStart + y, POSITION_DETECTION_PATTERN[y][x]); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
public static void encode(String content, ErrorCorrectionLevel ecLevel, Map<EncodeHintType,Object> hints, QRCode qrCode) throws WriterException { String encoding = hints == null ? null : (String) hints.get(EncodeHintType.CHARACTER_SET); if (encoding == null) { encoding = DEFAULT_BYTE_MODE_ENCODING; } // Step 1: Choose the mode (encoding). Mode mode = chooseMode(content, encoding); // Step 2: Append "bytes" into "dataBits" in appropriate encoding. BitVector dataBits = new BitVector(); appendBytes(content, mode, dataBits, encoding); // Step 3: Initialize QR code that can contain "dataBits". int numInputBytes = dataBits.sizeInBytes(); initQRCode(numInputBytes, ecLevel, mode, qrCode); // Step 4: Build another bit vector that contains header and data. BitVector headerAndDataBits = new BitVector(); // Step 4.5: Append ECI message if applicable if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.equals(encoding)) { CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding); if (eci != null) { appendECI(eci, headerAndDataBits); } } appendModeInfo(mode, headerAndDataBits); int numLetters = mode.equals(Mode.BYTE) ? dataBits.sizeInBytes() : content.length(); appendLengthInfo(numLetters, qrCode.getVersion(), mode, headerAndDataBits); headerAndDataBits.appendBitVector(dataBits); // Step 5: Terminate the bits properly. terminateBits(qrCode.getNumDataBytes(), headerAndDataBits); // Step 6: Interleave data bits with error correction code. BitVector finalBits = new BitVector(); interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(), qrCode.getNumRSBlocks(), finalBits); // Step 7: Choose the mask pattern and set to "qrCode". ByteMatrix matrix = new ByteMatrix(qrCode.getMatrixWidth(), qrCode.getMatrixWidth()); qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(), matrix)); // Step 8. Build the matrix and set it to "qrCode". MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(), qrCode.getMaskPattern(), matrix); qrCode.setMatrix(matrix); // Step 9. Make sure we have a valid QR Code. if (!qrCode.isValid()) { throw new WriterException("Invalid QR code: " + qrCode.toString()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode) throws WriterException { qrCode.setECLevel(ecLevel); qrCode.setMode(mode); // In the following comments, we use numbers of Version 7-H. for (int versionNum = 1; versionNum <= 40; versionNum++) { Version version = Version.getVersionForNumber(versionNum); // numBytes = 196 int numBytes = version.getTotalCodewords(); // getNumECBytes = 130 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); int numEcBytes = ecBlocks.getTotalECCodewords(); // getNumRSBlocks = 5 int numRSBlocks = ecBlocks.getNumBlocks(); // getNumDataBytes = 196 - 130 = 66 int numDataBytes = numBytes - numEcBytes; // We want to choose the smallest version which can contain data of "numInputBytes" + some // extra bits for the header (mode info and length info). The header can be three bytes // (precisely 4 + 16 bits) at most. Hence we do +3 here. if (numDataBytes >= numInputBytes + 3) { // Yay, we found the proper rs block info! qrCode.setVersion(versionNum); qrCode.setNumTotalBytes(numBytes); qrCode.setNumDataBytes(numDataBytes); qrCode.setNumRSBlocks(numRSBlocks); // getNumECBytes = 196 - 66 = 130 qrCode.setNumECBytes(numEcBytes); // matrix width = 21 + 6 * 4 = 45 qrCode.setMatrixWidth(version.getDimensionForVersion()); return; } } throw new WriterException("Cannot find proper rs block info (input data too big?)"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void terminateBits(int numDataBytes, BitVector bits) throws WriterException { int capacity = numDataBytes << 3; if (bits.size() > capacity) { throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity); } // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes // either way. for (int i = 0; i < 4 && bits.size() < capacity; ++i) { bits.appendBit(0); } int numBitsInLastByte = bits.size() % 8; // If the last byte isn't 8-bit aligned, we'll add padding bits. if (numBitsInLastByte > 0) { int numPaddingBits = 8 - numBitsInLastByte; for (int i = 0; i < numPaddingBits; ++i) { bits.appendBit(0); } } // Should be 8-bit aligned here. if (bits.size() % 8 != 0) { throw new WriterException("Number of bits is not a multiple of 8"); } // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). int numPaddingBytes = numDataBytes - bits.sizeInBytes(); for (int i = 0; i < numPaddingBytes; ++i) { if (i % 2 == 0) { bits.appendBits(0xec, 8); } else { bits.appendBits(0x11, 8); } } if (bits.size() != capacity) { throw new WriterException("Bits size does not equal capacity"); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock) throws WriterException { if (blockID >= numRSBlocks) { throw new WriterException("Block ID too large"); } // numRsBlocksInGroup2 = 196 % 5 = 1 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; // numRsBlocksInGroup1 = 5 - 1 = 4 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; // numTotalBytesInGroup1 = 196 / 5 = 39 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; // numTotalBytesInGroup2 = 39 + 1 = 40 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; // numDataBytesInGroup1 = 66 / 5 = 13 int numDataBytesInGroup1 = numDataBytes / numRSBlocks; // numDataBytesInGroup2 = 13 + 1 = 14 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; // numEcBytesInGroup1 = 39 - 13 = 26 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; // numEcBytesInGroup2 = 40 - 14 = 26 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; // Sanity checks. // 26 = 26 if (numEcBytesInGroup1 != numEcBytesInGroup2) { throw new WriterException("EC bytes mismatch"); } // 5 = 4 + 1. if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) { throw new WriterException("RS blocks mismatch"); } // 196 = (13 + 26) * 4 + (14 + 26) * 1 if (numTotalBytes != ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2)) { throw new WriterException("Total bytes mismatch"); } if (blockID < numRsBlocksInGroup1) { numDataBytesInBlock[0] = numDataBytesInGroup1; numECBytesInBlock[0] = numEcBytesInGroup1; } else { numDataBytesInBlock[0] = numDataBytesInGroup2; numECBytesInBlock[0] = numEcBytesInGroup2; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void interleaveWithECBytes(BitVector bits, int numTotalBytes, int numDataBytes, int numRSBlocks, BitVector result) throws WriterException { // "bits" must have "getNumDataBytes" bytes of data. if (bits.sizeInBytes() != numDataBytes) { throw new WriterException("Number of bits and data bytes does not match"); } // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll // store the divided data bytes blocks and error correction bytes blocks into "blocks". int dataBytesOffset = 0; int maxNumDataBytes = 0; int maxNumEcBytes = 0; // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. ArrayList<BlockPair> blocks = new ArrayList<BlockPair>(numRSBlocks); for (int i = 0; i < numRSBlocks; ++i) { int[] numDataBytesInBlock = new int[1]; int[] numEcBytesInBlock = new int[1]; getNumDataBytesAndNumECBytesForBlockID( numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock); ByteArray dataBytes = new ByteArray(); dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]); ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); blocks.add(new BlockPair(dataBytes, ecBytes)); maxNumDataBytes = Math.max(maxNumDataBytes, dataBytes.size()); maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.size()); dataBytesOffset += numDataBytesInBlock[0]; } if (numDataBytes != dataBytesOffset) { throw new WriterException("Data bytes does not match offset"); } // First, place data blocks. for (int i = 0; i < maxNumDataBytes; ++i) { for (int j = 0; j < blocks.size(); ++j) { ByteArray dataBytes = blocks.get(j).getDataBytes(); if (i < dataBytes.size()) { result.appendBits(dataBytes.at(i), 8); } } } // Then, place error correction blocks. for (int i = 0; i < maxNumEcBytes; ++i) { for (int j = 0; j < blocks.size(); ++j) { ByteArray ecBytes = blocks.get(j).getErrorCorrectionBytes(); if (i < ecBytes.size()) { result.appendBits(ecBytes.at(i), 8); } } } if (numTotalBytes != result.sizeInBytes()) { // Should be same. throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() + " differ."); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits) throws WriterException { int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version)); if (numLetters > ((1 << numBits) - 1)) { throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1)); } bits.appendBits(numLetters, numBits); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendBytes(String content, Mode mode, BitVector bits, String encoding) throws WriterException { if (mode.equals(Mode.NUMERIC)) { appendNumericBytes(content, bits); } else if (mode.equals(Mode.ALPHANUMERIC)) { appendAlphanumericBytes(content, bits); } else if (mode.equals(Mode.BYTE)) { append8BitBytes(content, bits, encoding); } else if (mode.equals(Mode.KANJI)) { appendKanjiBytes(content, bits); } else { throw new WriterException("Invalid mode: " + mode); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendAlphanumericBytes(String content, BitVector bits) throws WriterException { int length = content.length(); int i = 0; while (i < length) { int code1 = getAlphanumericCode(content.charAt(i)); if (code1 == -1) { throw new WriterException(); } if (i + 1 < length) { int code2 = getAlphanumericCode(content.charAt(i + 1)); if (code2 == -1) { throw new WriterException(); } // Encode two alphanumeric letters in 11 bits. bits.appendBits(code1 * 45 + code2, 11); i += 2; } else { // Encode one alphanumeric letter in six bits. bits.appendBits(code1, 6); i++; } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void append8BitBytes(String content, BitVector bits, String encoding) throws WriterException { byte[] bytes; try { bytes = content.getBytes(encoding); } catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); } for (int i = 0; i < bytes.length; ++i) { bits.appendBits(bytes[i], 8); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendKanjiBytes(String content, BitVector bits) throws WriterException { byte[] bytes; try { bytes = content.getBytes("Shift_JIS"); } catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); } int length = bytes.length; for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; int byte2 = bytes[i + 1] & 0xFF; int code = (byte1 << 8) | byte2; int subtracted = -1; if (code >= 0x8140 && code <= 0x9ffc) { subtracted = code - 0x8140; } else if (code >= 0xe040 && code <= 0xebbf) { subtracted = code - 0xc140; } if (subtracted == -1) { throw new WriterException("Invalid byte sequence"); } int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded, 13); } }
2
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
29
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void buildMatrix(BitVector dataBits, ErrorCorrectionLevel ecLevel, int version, int maskPattern, ByteMatrix matrix) throws WriterException { clearMatrix(matrix); embedBasicPatterns(version, matrix); // Type information appear with any version. embedTypeInfo(ecLevel, maskPattern, matrix); // Version info appear if version >= 7. maybeEmbedVersionInfo(version, matrix); // Data should be embedded at end. embedDataBits(dataBits, maskPattern, matrix); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void embedBasicPatterns(int version, ByteMatrix matrix) throws WriterException { // Let's get started with embedding big squares at corners. embedPositionDetectionPatternsAndSeparators(matrix); // Then, embed the dark dot at the left bottom corner. embedDarkDotAtLeftBottomCorner(matrix); // Position adjustment patterns appear if version >= 2. maybeEmbedPositionAdjustmentPatterns(version, matrix); // Timing patterns should be embedded after position adj. patterns. embedTimingPatterns(matrix); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix) throws WriterException { BitVector typeInfoBits = new BitVector(); makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits); for (int i = 0; i < typeInfoBits.size(); ++i) { // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in // "typeInfoBits". int bit = typeInfoBits.at(typeInfoBits.size() - 1 - i); // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46). int x1 = TYPE_INFO_COORDINATES[i][0]; int y1 = TYPE_INFO_COORDINATES[i][1]; matrix.set(x1, y1, bit); if (i < 8) { // Right top corner. int x2 = matrix.getWidth() - i - 1; int y2 = 8; matrix.set(x2, y2, bit); } else { // Left bottom corner. int x2 = 8; int y2 = matrix.getHeight() - 7 + (i - 8); matrix.set(x2, y2, bit); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void maybeEmbedVersionInfo(int version, ByteMatrix matrix) throws WriterException { if (version < 7) { // Version info is necessary if version >= 7. return; // Don't need version info. } BitVector versionInfoBits = new BitVector(); makeVersionInfoBits(version, versionInfoBits); int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. for (int i = 0; i < 6; ++i) { for (int j = 0; j < 3; ++j) { // Place bits in LSB (least significant bit) to MSB order. int bit = versionInfoBits.at(bitIndex); bitIndex--; // Left bottom corner. matrix.set(i, matrix.getHeight() - 11 + j, bit); // Right bottom corner. matrix.set(matrix.getHeight() - 11 + j, i, bit); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void embedDataBits(BitVector dataBits, int maskPattern, ByteMatrix matrix) throws WriterException { int bitIndex = 0; int direction = -1; // Start from the right bottom cell. int x = matrix.getWidth() - 1; int y = matrix.getHeight() - 1; while (x > 0) { // Skip the vertical timing pattern. if (x == 6) { x -= 1; } while (y >= 0 && y < matrix.getHeight()) { for (int i = 0; i < 2; ++i) { int xx = x - i; // Skip the cell if it's not empty. if (!isEmpty(matrix.get(xx, y))) { continue; } int bit; if (bitIndex < dataBits.size()) { bit = dataBits.at(bitIndex); ++bitIndex; } else { // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described // in 8.4.9 of JISX0510:2004 (p. 24). bit = 0; } // Skip masking if mask_pattern is -1. if (maskPattern != -1) { if (MaskUtil.getDataMaskBit(maskPattern, xx, y)) { bit ^= 0x1; } } matrix.set(xx, y, bit); } y += direction; } direction = -direction; // Reverse the direction. y += direction; x -= 2; // Move to the left. } // All bits should be consumed. if (bitIndex != dataBits.size()) { throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitVector bits) throws WriterException { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new WriterException("Invalid mask pattern"); } int typeInfo = (ecLevel.getBits() << 3) | maskPattern; bits.appendBits(typeInfo, 5); int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); bits.appendBits(bchCode, 10); BitVector maskBits = new BitVector(); maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); bits.xor(maskBits); if (bits.size() != 15) { // Just in case. throw new WriterException("should not happen but we got: " + bits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void makeVersionInfoBits(int version, BitVector bits) throws WriterException { bits.appendBits(version, 6); int bchCode = calculateBCHCode(version, VERSION_INFO_POLY); bits.appendBits(bchCode, 12); if (bits.size() != 18) { // Just in case. throw new WriterException("should not happen but we got: " + bits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedTimingPatterns(ByteMatrix matrix) throws WriterException { // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical // separation patterns (size 1). Thus, 8 = 7 + 1. for (int i = 8; i < matrix.getWidth() - 8; ++i) { int bit = (i + 1) % 2; // Horizontal line. if (!isValidValue(matrix.get(i, 6))) { throw new WriterException(); } if (isEmpty(matrix.get(i, 6))) { matrix.set(i, 6, bit); } // Vertical line. if (!isValidValue(matrix.get(6, i))) { throw new WriterException(); } if (isEmpty(matrix.get(6, i))) { matrix.set(6, i, bit); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) throws WriterException { if (matrix.get(8, matrix.getHeight() - 8) == 0) { throw new WriterException(); } matrix.set(8, matrix.getHeight() - 8, 1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedHorizontalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (HORIZONTAL_SEPARATION_PATTERN[0].length != 8 || HORIZONTAL_SEPARATION_PATTERN.length != 1) { throw new WriterException("Bad horizontal separation pattern"); } for (int x = 0; x < 8; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart))) { throw new WriterException(); } matrix.set(xStart + x, yStart, HORIZONTAL_SEPARATION_PATTERN[0][x]); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedVerticalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (VERTICAL_SEPARATION_PATTERN[0].length != 1 || VERTICAL_SEPARATION_PATTERN.length != 7) { throw new WriterException("Bad vertical separation pattern"); } for (int y = 0; y < 7; ++y) { if (!isEmpty(matrix.get(xStart, yStart + y))) { throw new WriterException(); } matrix.set(xStart, yStart + y, VERTICAL_SEPARATION_PATTERN[y][0]); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedPositionAdjustmentPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (POSITION_ADJUSTMENT_PATTERN[0].length != 5 || POSITION_ADJUSTMENT_PATTERN.length != 5) { throw new WriterException("Bad position adjustment"); } for (int y = 0; y < 5; ++y) { for (int x = 0; x < 5; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart + y))) { throw new WriterException(); } matrix.set(xStart + x, yStart + y, POSITION_ADJUSTMENT_PATTERN[y][x]); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedPositionDetectionPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (POSITION_DETECTION_PATTERN[0].length != 7 || POSITION_DETECTION_PATTERN.length != 7) { throw new WriterException("Bad position detection pattern"); } for (int y = 0; y < 7; ++y) { for (int x = 0; x < 7; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart + y))) { throw new WriterException(); } matrix.set(xStart + x, yStart + y, POSITION_DETECTION_PATTERN[y][x]); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException { // Embed three big squares at corners. int pdpWidth = POSITION_DETECTION_PATTERN[0].length; // Left top corner. embedPositionDetectionPattern(0, 0, matrix); // Right top corner. embedPositionDetectionPattern(matrix.getWidth() - pdpWidth, 0, matrix); // Left bottom corner. embedPositionDetectionPattern(0, matrix.getWidth() - pdpWidth, matrix); // Embed horizontal separation patterns around the squares. int hspWidth = HORIZONTAL_SEPARATION_PATTERN[0].length; // Left top corner. embedHorizontalSeparationPattern(0, hspWidth - 1, matrix); // Right top corner. embedHorizontalSeparationPattern(matrix.getWidth() - hspWidth, hspWidth - 1, matrix); // Left bottom corner. embedHorizontalSeparationPattern(0, matrix.getWidth() - hspWidth, matrix); // Embed vertical separation patterns around the squares. int vspSize = VERTICAL_SEPARATION_PATTERN.length; // Left top corner. embedVerticalSeparationPattern(vspSize, 0, matrix); // Right top corner. embedVerticalSeparationPattern(matrix.getHeight() - vspSize - 1, 0, matrix); // Left bottom corner. embedVerticalSeparationPattern(vspSize, matrix.getHeight() - vspSize, matrix); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void maybeEmbedPositionAdjustmentPatterns(int version, ByteMatrix matrix) throws WriterException { if (version < 2) { // The patterns appear if version >= 2 return; } int index = version - 1; int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index]; int numCoordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index].length; for (int i = 0; i < numCoordinates; ++i) { for (int j = 0; j < numCoordinates; ++j) { int y = coordinates[i]; int x = coordinates[j]; if (x == -1 || y == -1) { continue; } // If the cell is unset, we embed the position adjustment pattern here. if (isEmpty(matrix.get(x, y))) { // -2 is necessary since the x/y coordinates point to the center of the pattern, not the // left top corner. embedPositionAdjustmentPattern(x - 2, y - 2, matrix); } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/QRCodeWriter.java
public ByteMatrix encode(String contents, int width, int height) throws WriterException { return encode(contents, width, height, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/QRCodeWriter.java
public ByteMatrix encode(String contents, int width, int height, Map<EncodeHintType,Object> hints) throws WriterException { if (contents == null || contents.length() == 0) { throw new IllegalArgumentException("Found empty contents"); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height); } ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; if (hints != null) { ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints.get(EncodeHintType.ERROR_CORRECTION); if (requestedECLevel != null) { errorCorrectionLevel = requestedECLevel; } } QRCode code = new QRCode(); Encoder.encode(contents, errorCorrectionLevel, hints, code); return renderResult(code, width, height); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
public static void encode(String content, ErrorCorrectionLevel ecLevel, QRCode qrCode) throws WriterException { encode(content, ecLevel, null, qrCode); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
public static void encode(String content, ErrorCorrectionLevel ecLevel, Map<EncodeHintType,Object> hints, QRCode qrCode) throws WriterException { String encoding = hints == null ? null : (String) hints.get(EncodeHintType.CHARACTER_SET); if (encoding == null) { encoding = DEFAULT_BYTE_MODE_ENCODING; } // Step 1: Choose the mode (encoding). Mode mode = chooseMode(content, encoding); // Step 2: Append "bytes" into "dataBits" in appropriate encoding. BitVector dataBits = new BitVector(); appendBytes(content, mode, dataBits, encoding); // Step 3: Initialize QR code that can contain "dataBits". int numInputBytes = dataBits.sizeInBytes(); initQRCode(numInputBytes, ecLevel, mode, qrCode); // Step 4: Build another bit vector that contains header and data. BitVector headerAndDataBits = new BitVector(); // Step 4.5: Append ECI message if applicable if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.equals(encoding)) { CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding); if (eci != null) { appendECI(eci, headerAndDataBits); } } appendModeInfo(mode, headerAndDataBits); int numLetters = mode.equals(Mode.BYTE) ? dataBits.sizeInBytes() : content.length(); appendLengthInfo(numLetters, qrCode.getVersion(), mode, headerAndDataBits); headerAndDataBits.appendBitVector(dataBits); // Step 5: Terminate the bits properly. terminateBits(qrCode.getNumDataBytes(), headerAndDataBits); // Step 6: Interleave data bits with error correction code. BitVector finalBits = new BitVector(); interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(), qrCode.getNumRSBlocks(), finalBits); // Step 7: Choose the mask pattern and set to "qrCode". ByteMatrix matrix = new ByteMatrix(qrCode.getMatrixWidth(), qrCode.getMatrixWidth()); qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(), matrix)); // Step 8. Build the matrix and set it to "qrCode". MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(), qrCode.getMaskPattern(), matrix); qrCode.setMatrix(matrix); // Step 9. Make sure we have a valid QR Code. if (!qrCode.isValid()) { throw new WriterException("Invalid QR code: " + qrCode.toString()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version, ByteMatrix matrix) throws WriterException { int minPenalty = Integer.MAX_VALUE; // Lower penalty is better. int bestMaskPattern = -1; // We try all mask patterns to choose the best one. for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) { MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); int penalty = calculateMaskPenalty(matrix); if (penalty < minPenalty) { minPenalty = penalty; bestMaskPattern = maskPattern; } } return bestMaskPattern; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode) throws WriterException { qrCode.setECLevel(ecLevel); qrCode.setMode(mode); // In the following comments, we use numbers of Version 7-H. for (int versionNum = 1; versionNum <= 40; versionNum++) { Version version = Version.getVersionForNumber(versionNum); // numBytes = 196 int numBytes = version.getTotalCodewords(); // getNumECBytes = 130 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); int numEcBytes = ecBlocks.getTotalECCodewords(); // getNumRSBlocks = 5 int numRSBlocks = ecBlocks.getNumBlocks(); // getNumDataBytes = 196 - 130 = 66 int numDataBytes = numBytes - numEcBytes; // We want to choose the smallest version which can contain data of "numInputBytes" + some // extra bits for the header (mode info and length info). The header can be three bytes // (precisely 4 + 16 bits) at most. Hence we do +3 here. if (numDataBytes >= numInputBytes + 3) { // Yay, we found the proper rs block info! qrCode.setVersion(versionNum); qrCode.setNumTotalBytes(numBytes); qrCode.setNumDataBytes(numDataBytes); qrCode.setNumRSBlocks(numRSBlocks); // getNumECBytes = 196 - 66 = 130 qrCode.setNumECBytes(numEcBytes); // matrix width = 21 + 6 * 4 = 45 qrCode.setMatrixWidth(version.getDimensionForVersion()); return; } } throw new WriterException("Cannot find proper rs block info (input data too big?)"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void terminateBits(int numDataBytes, BitVector bits) throws WriterException { int capacity = numDataBytes << 3; if (bits.size() > capacity) { throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity); } // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes // either way. for (int i = 0; i < 4 && bits.size() < capacity; ++i) { bits.appendBit(0); } int numBitsInLastByte = bits.size() % 8; // If the last byte isn't 8-bit aligned, we'll add padding bits. if (numBitsInLastByte > 0) { int numPaddingBits = 8 - numBitsInLastByte; for (int i = 0; i < numPaddingBits; ++i) { bits.appendBit(0); } } // Should be 8-bit aligned here. if (bits.size() % 8 != 0) { throw new WriterException("Number of bits is not a multiple of 8"); } // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). int numPaddingBytes = numDataBytes - bits.sizeInBytes(); for (int i = 0; i < numPaddingBytes; ++i) { if (i % 2 == 0) { bits.appendBits(0xec, 8); } else { bits.appendBits(0x11, 8); } } if (bits.size() != capacity) { throw new WriterException("Bits size does not equal capacity"); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock) throws WriterException { if (blockID >= numRSBlocks) { throw new WriterException("Block ID too large"); } // numRsBlocksInGroup2 = 196 % 5 = 1 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; // numRsBlocksInGroup1 = 5 - 1 = 4 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; // numTotalBytesInGroup1 = 196 / 5 = 39 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; // numTotalBytesInGroup2 = 39 + 1 = 40 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; // numDataBytesInGroup1 = 66 / 5 = 13 int numDataBytesInGroup1 = numDataBytes / numRSBlocks; // numDataBytesInGroup2 = 13 + 1 = 14 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; // numEcBytesInGroup1 = 39 - 13 = 26 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; // numEcBytesInGroup2 = 40 - 14 = 26 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; // Sanity checks. // 26 = 26 if (numEcBytesInGroup1 != numEcBytesInGroup2) { throw new WriterException("EC bytes mismatch"); } // 5 = 4 + 1. if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) { throw new WriterException("RS blocks mismatch"); } // 196 = (13 + 26) * 4 + (14 + 26) * 1 if (numTotalBytes != ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2)) { throw new WriterException("Total bytes mismatch"); } if (blockID < numRsBlocksInGroup1) { numDataBytesInBlock[0] = numDataBytesInGroup1; numECBytesInBlock[0] = numEcBytesInGroup1; } else { numDataBytesInBlock[0] = numDataBytesInGroup2; numECBytesInBlock[0] = numEcBytesInGroup2; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void interleaveWithECBytes(BitVector bits, int numTotalBytes, int numDataBytes, int numRSBlocks, BitVector result) throws WriterException { // "bits" must have "getNumDataBytes" bytes of data. if (bits.sizeInBytes() != numDataBytes) { throw new WriterException("Number of bits and data bytes does not match"); } // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll // store the divided data bytes blocks and error correction bytes blocks into "blocks". int dataBytesOffset = 0; int maxNumDataBytes = 0; int maxNumEcBytes = 0; // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. ArrayList<BlockPair> blocks = new ArrayList<BlockPair>(numRSBlocks); for (int i = 0; i < numRSBlocks; ++i) { int[] numDataBytesInBlock = new int[1]; int[] numEcBytesInBlock = new int[1]; getNumDataBytesAndNumECBytesForBlockID( numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock); ByteArray dataBytes = new ByteArray(); dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]); ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); blocks.add(new BlockPair(dataBytes, ecBytes)); maxNumDataBytes = Math.max(maxNumDataBytes, dataBytes.size()); maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.size()); dataBytesOffset += numDataBytesInBlock[0]; } if (numDataBytes != dataBytesOffset) { throw new WriterException("Data bytes does not match offset"); } // First, place data blocks. for (int i = 0; i < maxNumDataBytes; ++i) { for (int j = 0; j < blocks.size(); ++j) { ByteArray dataBytes = blocks.get(j).getDataBytes(); if (i < dataBytes.size()) { result.appendBits(dataBytes.at(i), 8); } } } // Then, place error correction blocks. for (int i = 0; i < maxNumEcBytes; ++i) { for (int j = 0; j < blocks.size(); ++j) { ByteArray ecBytes = blocks.get(j).getErrorCorrectionBytes(); if (i < ecBytes.size()) { result.appendBits(ecBytes.at(i), 8); } } } if (numTotalBytes != result.sizeInBytes()) { // Should be same. throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() + " differ."); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits) throws WriterException { int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version)); if (numLetters > ((1 << numBits) - 1)) { throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1)); } bits.appendBits(numLetters, numBits); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendBytes(String content, Mode mode, BitVector bits, String encoding) throws WriterException { if (mode.equals(Mode.NUMERIC)) { appendNumericBytes(content, bits); } else if (mode.equals(Mode.ALPHANUMERIC)) { appendAlphanumericBytes(content, bits); } else if (mode.equals(Mode.BYTE)) { append8BitBytes(content, bits, encoding); } else if (mode.equals(Mode.KANJI)) { appendKanjiBytes(content, bits); } else { throw new WriterException("Invalid mode: " + mode); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendAlphanumericBytes(String content, BitVector bits) throws WriterException { int length = content.length(); int i = 0; while (i < length) { int code1 = getAlphanumericCode(content.charAt(i)); if (code1 == -1) { throw new WriterException(); } if (i + 1 < length) { int code2 = getAlphanumericCode(content.charAt(i + 1)); if (code2 == -1) { throw new WriterException(); } // Encode two alphanumeric letters in 11 bits. bits.appendBits(code1 * 45 + code2, 11); i += 2; } else { // Encode one alphanumeric letter in six bits. bits.appendBits(code1, 6); i++; } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void append8BitBytes(String content, BitVector bits, String encoding) throws WriterException { byte[] bytes; try { bytes = content.getBytes(encoding); } catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); } for (int i = 0; i < bytes.length; ++i) { bits.appendBits(bytes[i], 8); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendKanjiBytes(String content, BitVector bits) throws WriterException { byte[] bytes; try { bytes = content.getBytes("Shift_JIS"); } catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); } int length = bytes.length; for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; int byte2 = bytes[i + 1] & 0xFF; int code = (byte1 << 8) | byte2; int subtracted = -1; if (code >= 0x8140 && code <= 0x9ffc) { subtracted = code - 0x8140; } else if (code >= 0xe040 && code <= 0xebbf) { subtracted = code - 0xc140; } if (subtracted == -1) { throw new WriterException("Invalid byte sequence"); } int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded, 13); } }
(Domain) IllegalPdfSyntaxException 25
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void moveTo(final float x, final float y) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x).append(' ').append(y).append(" m").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void lineTo(final float x, final float y) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x).append(' ').append(y).append(" l").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void curveTo(final float x1, final float y1, final float x2, final float y2, final float x3, final float y3) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x1).append(' ').append(y1).append(' ').append(x2).append(' ').append(y2).append(' ').append(x3).append(' ').append(y3).append(" c").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void curveTo(final float x2, final float y2, final float x3, final float y3) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x2).append(' ').append(y2).append(' ').append(x3).append(' ').append(y3).append(" v").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void curveFromTo(final float x1, final float y1, final float x3, final float y3) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x1).append(' ').append(y1).append(' ').append(x3).append(' ').append(y3).append(" y").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void rectangle(final float x, final float y, final float w, final float h) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x).append(' ').append(y).append(' ').append(w).append(' ').append(h).append(" re").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void closePath() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("h").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void newPath() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("n").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void stroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("S").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void closePathStroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("s").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void fill() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("f").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void eoFill() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("f*").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void fillStroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("B").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void closePathFillStroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("b").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void eoFillStroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("B*").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void closePathEoFillStroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("b*").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
protected void beginText(boolean restoreTM) { if (inText) { if (isTagged()) { } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.begin.end.text.operators")); } } else { inText = true; content.append("BT").append_i(separator); if (restoreTM) { float xTLM = state.xTLM; float tx = state.tx; setTextMatrix(state.aTLM, state.bTLM, state.cTLM, state.dTLM, state.tx, state.yTLM); state.xTLM = xTLM; state.tx = tx; } else { state.xTLM = 0; state.yTLM = 0; state.tx = 0; } if (isTagged()) { try { restoreColor(); } catch (IOException ioe) { } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void endText() { if (!inText) { if (isTagged()) { } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.begin.end.text.operators")); } } else { inText = false; content.append("ET").append_i(separator); if (isTagged()) { try { restoreColor(); } catch (IOException ioe) { } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void restoreState() { if (inText && isTagged()) { endText(); } content.append("Q").append_i(separator); int idx = stateList.size() - 1; if (idx < 0) throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.save.restore.state.operators")); state = stateList.get(idx); stateList.remove(idx); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void endLayer() { int n = 1; if (layerDepth != null && !layerDepth.isEmpty()) { n = layerDepth.get(layerDepth.size() - 1).intValue(); layerDepth.remove(layerDepth.size() - 1); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.layer.operators")); } while (n-- > 0) content.append("EMC").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void endMarkedContentSequence() { if (getMcDepth() == 0) { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.begin.end.marked.content.operators")); } int contentSize = content.size(); setMcDepth(getMcDepth() - 1); content.append("EMC").append_i(separator); markedContentSize += content.size() - contentSize; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void sanityCheck() { if (getMcDepth() != 0) { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.marked.content.operators")); } if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.begin.end.text.operators")); } } if (layerDepth != null && !layerDepth.isEmpty()) { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.layer.operators")); } if (!stateList.isEmpty()) { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.save.restore.state.operators")); } }
0 0
(Lib) IllegalStateException 25
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ChapterAutoNumber.java
Override public Section addSection(final String title) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } return addSection(title, 2); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ChapterAutoNumber.java
Override public Section addSection(final Paragraph title) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } return addSection(title, 2); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/ArrayRandomAccessSource.java
public int get(long offset, byte[] bytes, int off, int len) { if (array == null) throw new IllegalStateException("Already closed"); if (offset >= array.length) return -1; if (offset + len > array.length) len = (int)(array.length - offset); System.arraycopy(array, (int)offset, bytes, off, len); return len; }
// 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/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/PdfSignatureAppearance.java
public PdfTemplate getAppearance() throws DocumentException { if (isInvisible()) { PdfTemplate t = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(0, 0)); writer.addDirectTemplateSimple(t, null); return t; } if (app[0] == null) { PdfTemplate t = app[0] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n0")); t.setLiteral("% DSBlank\n"); } if (app[1] == null && !acro6Layers) { PdfTemplate t = app[1] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n1")); t.setLiteral(questionMark); } if (app[2] == null) { String text; if (layer2Text == null) { StringBuilder buf = new StringBuilder(); buf.append("Digitally signed by "); String name = null; X500Name x500name = CertificateInfo.getSubjectFields((X509Certificate)signCertificate); if (x500name != null) { name = x500name.getField("CN"); if (name == null) name = x500name.getField("E"); } if (name == null) name = ""; buf.append(name).append('\n'); SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); buf.append("Date: ").append(sd.format(signDate.getTime())); if (reason != null) buf.append('\n').append("Reason: ").append(reason); if (location != null) buf.append('\n').append("Location: ").append(location); text = buf.toString(); } else text = layer2Text; PdfTemplate t = app[2] = new PdfTemplate(writer); t.setBoundingBox(rect); writer.addDirectTemplateSimple(t, new PdfName("n2")); if (image != null) { if (imageScale == 0) { t.addImage(image, rect.getWidth(), 0, 0, rect.getHeight(), 0, 0); } else { float usableScale = imageScale; if (imageScale < 0) usableScale = Math.min(rect.getWidth() / image.getWidth(), rect.getHeight() / image.getHeight()); float w = image.getWidth() * usableScale; float h = image.getHeight() * usableScale; float x = (rect.getWidth() - w) / 2; float y = (rect.getHeight() - h) / 2; t.addImage(image, w, 0, 0, h, x, y); } } Font font; if (layer2Font == null) font = new Font(); else font = new Font(layer2Font); float size = font.getSize(); Rectangle dataRect = null; Rectangle signatureRect = null; if (renderingMode == RenderingMode.NAME_AND_DESCRIPTION || renderingMode == RenderingMode.GRAPHIC_AND_DESCRIPTION && this.signatureGraphic != null) { // origin is the bottom-left signatureRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() / 2 - MARGIN, rect.getHeight() - MARGIN); dataRect = new Rectangle( rect.getWidth() / 2 + MARGIN / 2, MARGIN, rect.getWidth() - MARGIN / 2, rect.getHeight() - MARGIN); if (rect.getHeight() > rect.getWidth()) { signatureRect = new Rectangle( MARGIN, rect.getHeight() / 2, rect.getWidth() - MARGIN, rect.getHeight()); dataRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, rect.getHeight() / 2 - MARGIN); } } else if (renderingMode == RenderingMode.GRAPHIC) { if (signatureGraphic == null) { throw new IllegalStateException(MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.only")); } signatureRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, // take all space available rect.getHeight() - MARGIN); } else { dataRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, rect.getHeight() * (1 - TOP_SECTION) - MARGIN); } switch (renderingMode) { case NAME_AND_DESCRIPTION: String signedBy = CertificateInfo.getSubjectFields((X509Certificate)signCertificate).getField("CN"); if (signedBy == null) signedBy = CertificateInfo.getSubjectFields((X509Certificate)signCertificate).getField("E"); if (signedBy == null) signedBy = ""; Rectangle sr2 = new Rectangle(signatureRect.getWidth() - MARGIN, signatureRect.getHeight() - MARGIN ); float signedSize = ColumnText.fitText(font, signedBy, sr2, -1, runDirection); ColumnText ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(new Phrase(signedBy, font), signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), signedSize, Element.ALIGN_LEFT); ct2.go(); break; case GRAPHIC_AND_DESCRIPTION: if (signatureGraphic == null) { throw new IllegalStateException(MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.and.description")); } ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), 0, Element.ALIGN_RIGHT); Image im = Image.getInstance(signatureGraphic); im.scaleToFit(signatureRect.getWidth(), signatureRect.getHeight()); Paragraph p = new Paragraph(); // must calculate the point to draw from to make image appear in middle of column float x = 0; // experimentation found this magic number to counteract Adobe's signature graphic, which // offsets the y co-ordinate by 15 units float y = -im.getScaledHeight() + 15; x = x + (signatureRect.getWidth() - im.getScaledWidth()) / 2; y = y - (signatureRect.getHeight() - im.getScaledHeight()) / 2; p.add(new Chunk(im, x + (signatureRect.getWidth() - im.getScaledWidth()) / 2, y, false)); ct2.addElement(p); ct2.go(); break; case GRAPHIC: ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), 0, Element.ALIGN_RIGHT); im = Image.getInstance(signatureGraphic); im.scaleToFit(signatureRect.getWidth(), signatureRect.getHeight()); p = new Paragraph(signatureRect.getHeight()); // must calculate the point to draw from to make image appear in middle of column x = (signatureRect.getWidth() - im.getScaledWidth()) / 2; y = (signatureRect.getHeight() - im.getScaledHeight()) / 2; p.add(new Chunk(im, x, y, false)); ct2.addElement(p); ct2.go(); break; default: } if(renderingMode != RenderingMode.GRAPHIC) { if (size <= 0) { Rectangle sr = new Rectangle(dataRect.getWidth(), dataRect.getHeight()); size = ColumnText.fitText(font, text, sr, 12, runDirection); } ColumnText ct = new ColumnText(t); ct.setRunDirection(runDirection); ct.setSimpleColumn(new Phrase(text, font), dataRect.getLeft(), dataRect.getBottom(), dataRect.getRight(), dataRect.getTop(), size, Element.ALIGN_LEFT); ct.go(); } } if (app[3] == null && !acro6Layers) { PdfTemplate t = app[3] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n3")); t.setLiteral("% DSBlank\n"); } if (app[4] == null && !acro6Layers) { PdfTemplate t = app[4] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(0, rect.getHeight() * (1 - TOP_SECTION), rect.getRight(), rect.getTop())); writer.addDirectTemplateSimple(t, new PdfName("n4")); Font font; if (layer2Font == null) font = new Font(); else font = new Font(layer2Font); //float size = font.getSize(); String text = "Signature Not Verified"; if (layer4Text != null) text = layer4Text; Rectangle sr = new Rectangle(rect.getWidth() - 2 * MARGIN, rect.getHeight() * TOP_SECTION - 2 * MARGIN); float size = ColumnText.fitText(font, text, sr, 15, runDirection); ColumnText ct = new ColumnText(t); ct.setRunDirection(runDirection); ct.setSimpleColumn(new Phrase(text, font), MARGIN, 0, rect.getWidth() - MARGIN, rect.getHeight() - MARGIN, size, Element.ALIGN_LEFT); ct.go(); } int rotation = writer.reader.getPageRotation(page); Rectangle rotated = new Rectangle(rect); int n = rotation; while (n > 0) { rotated = rotated.rotate(); n -= 90; } if (frm == null) { frm = new PdfTemplate(writer); frm.setBoundingBox(rotated); writer.addDirectTemplateSimple(frm, new PdfName("FRM")); float scale = Math.min(rect.getWidth(), rect.getHeight()) * 0.9f; float x = (rect.getWidth() - scale) / 2; float y = (rect.getHeight() - scale) / 2; scale /= 100; if (rotation == 90) frm.concatCTM(0, 1, -1, 0, rect.getHeight(), 0); else if (rotation == 180) frm.concatCTM(-1, 0, 0, -1, rect.getWidth(), rect.getHeight()); else if (rotation == 270) frm.concatCTM(0, -1, 1, 0, 0, rect.getWidth()); frm.addTemplate(app[0], 0, 0); if (!acro6Layers) frm.addTemplate(app[1], scale, 0, 0, scale, x, y); frm.addTemplate(app[2], 0, 0); if (!acro6Layers) { frm.addTemplate(app[3], scale, 0, 0, scale, x, y); frm.addTemplate(app[4], 0, 0); } } PdfTemplate napp = new PdfTemplate(writer); napp.setBoundingBox(rotated); writer.addDirectTemplateSimple(napp, null); napp.addTemplate(frm, 0, 0); return napp; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void replacePage(PdfReader r, int pageImported, int pageReplaced) { PdfDictionary pageN = reader.getPageN(pageReplaced); if (pagesToContent.containsKey(pageN)) throw new IllegalStateException(MessageLocalization.getComposedMessage("this.page.cannot.be.replaced.new.content.was.already.added")); PdfImportedPage p = getImportedPage(r, pageImported); PdfDictionary dic2 = reader.getPageNRelease(pageReplaced); dic2.remove(PdfName.RESOURCES); dic2.remove(PdfName.CONTENTS); moveRectangle(dic2, r, pageImported, PdfName.MEDIABOX, "media"); moveRectangle(dic2, r, pageImported, PdfName.CROPBOX, "crop"); moveRectangle(dic2, r, pageImported, PdfName.TRIMBOX, "trim"); moveRectangle(dic2, r, pageImported, PdfName.ARTBOX, "art"); moveRectangle(dic2, r, pageImported, PdfName.BLEEDBOX, "bleed"); dic2.put(PdfName.ROTATE, new PdfNumber(r.getPageRotation(pageImported))); PdfContentByte cb = getOverContent(pageReplaced); cb.addTemplate(p, 0, 0); PageStamp ps = pagesToContent.get(pageN); ps.replacePoint = ps.over.getInternalBuffer().size(); }
// 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/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/MarkedContentInfo.java
public int getMcid(){ PdfNumber id = dictionary.getAsNumber(PdfName.MCID); if (id == null) throw new IllegalStateException("MarkedContentInfo does not contain MCID"); return id.intValue(); }
// 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/BarcodePDF417.java
private void macroCodes() { if (macroSegmentId < 0) { throw new IllegalStateException(MessageLocalization.getComposedMessage("macrosegmentid.must.be.gt.eq.0")); } if (macroSegmentId >= macroSegmentCount) { throw new IllegalStateException(MessageLocalization.getComposedMessage("macrosegmentid.must.be.lt.macrosemgentcount")); } if (macroSegmentCount < 1) { throw new IllegalStateException(MessageLocalization.getComposedMessage("macrosemgentcount.must.be.gt.0")); } macroIndex = cwPtr; codewords[cwPtr++] = MACRO_SEGMENT_ID; append(macroSegmentId, 5); if (macroFileId != null) { append(macroFileId); } if (macroSegmentId >= macroSegmentCount-1) { codewords[cwPtr++] = MACRO_LAST_SEGMENT; } }
// 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/Section.java
Override public void add(final int index, final Element element) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } try { if (element.isNestable()) { super.add(index, element); } else { throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
Override public boolean add(final Element element) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } try { if (element.type() == Element.SECTION) { Section section = (Section) element; section.setNumbers(++subsections, numbers); return super.add(section); } else if (element instanceof MarkedSection && ((MarkedObject)element).element.type() == Element.SECTION) { MarkedSection mo = (MarkedSection)element; Section section = (Section)mo.element; section.setNumbers(++subsections, numbers); return super.add(mo); } else if (element.isNestable()) { return super.add(element); } else { throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
public Section addSection(final float indentation, final Paragraph title, final int numberDepth) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } Section section = new Section(title, numberDepth); section.setIndentation(indentation); add(section); return section; }
0 0
(Domain) InvalidPdfException 25
              
// 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/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 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 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 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]; } }
4
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne){ throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()), ne); }
0
(Lib) UnsupportedOperationException 18
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/WritableDirectElement.java
public boolean process(final ElementListener listener) { throw new UnsupportedOperationException(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/WritableDirectElement.java
public boolean isNestable() { throw new UnsupportedOperationException(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFLZWDecoder.java
public byte[] decode(byte data[], byte uncompData[], int h) { if(data[0] == (byte)0x00 && data[1] == (byte)0x01) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("tiff.5.0.style.lzw.codes.are.not.supported")); } initializeStringTable(); this.data = data; this.h = h; this.uncompData = uncompData; // Initialize pointers bytePointer = 0; bitPointer = 0; dstIndex = 0; nextData = 0; nextBits = 0; int code, oldCode = 0; byte string[]; while ( ((code = getNextCode()) != 257) && dstIndex < uncompData.length) { if (code == 256) { initializeStringTable(); code = getNextCode(); if (code == 257) { break; } writeString(stringTable[code]); oldCode = code; } else { if (code < tableIndex) { string = stringTable[code]; writeString(string); addStringToTable(stringTable[oldCode], string[0]); oldCode = code; } else { string = stringTable[oldCode]; string = composeString(string, string[0]); writeString(string); addStringToTable(string); oldCode = code; } } } // Horizontal Differencing Predictor if (predictor == 2) { int count; for (int j = 0; j < h; j++) { count = samplesPerPixel * (j * w + 1); for (int i = samplesPerPixel; i < w * samplesPerPixel; i++) { uncompData[count] += uncompData[count - samplesPerPixel]; count++; } } } return uncompData; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
public void remove() { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("remove.not.supported")); }
// 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/IntHashtable.java
public void remove() { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("remove.not.supported")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
boolean partialFormFlattening(String name) { getAcroFields(); if (acroFields.getXfa().isXfaPresent()) throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("partial.form.flattening.is.not.supported.with.xfa.forms")); if (!acroFields.getFields().containsKey(name)) return false; partialFlattening.add(name); return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setPageAction(PdfName actionType, PdfAction action) throws PdfException { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.setpageaction.pdfname.actiontype.pdfaction.action.int.page")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setDuration(int seconds) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.setpageaction.pdfname.actiontype.pdfaction.action.int.page")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setTransition(PdfTransition transition) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.setpageaction.pdfname.actiontype.pdfaction.action.int.page")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setOpenAction(String name) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("open.actions.by.name.are.not.supported")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setThumbnail(com.itextpdf.text.Image image) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.pdfstamper.setthumbnail")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public PdfContentByte getDirectContentUnder() { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.pdfstamper.getundercontent.or.pdfstamper.getovercontent")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public PdfContentByte getDirectContent() { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.pdfstamper.getundercontent.or.pdfstamper.getovercontent")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
Override public void setPageEvent(PdfPageEvent event) { throw new UnsupportedOperationException(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEANSUPP.java
public java.awt.Image createAwtImage(java.awt.Color foreground, java.awt.Color background) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("the.two.barcodes.must.be.composed.externally")); }
// 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/RectangleReadOnly.java
private void throwReadOnlyError() { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("rectanglereadonly.this.rectangle.is.read.only")); }
0 0
(Lib) EOFException 16
              
// 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/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/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 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)); }
0 0
(Lib) NoSuchElementException 16
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/FlatteningPathIterator.java
public int currentSegment(float[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4Bx")); //$NON-NLS-1$ } evaluate(); int type = bufType; if (type != SEG_CLOSE) { coords[0] = (float)px; coords[1] = (float)py; if (type != SEG_MOVETO) { type = SEG_LINETO; } } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/FlatteningPathIterator.java
public int currentSegment(double[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } evaluate(); int type = bufType; if (type != SEG_CLOSE) { coords[0] = px; coords[1] = py; if (type != SEG_MOVETO) { type = SEG_LINETO; } } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Rectangle2D.java
public int currentSegment(double[] coords) { if (isDone()) { throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } if (index == 5) { return SEG_CLOSE; } int type; if (index == 0) { type = SEG_MOVETO; coords[0] = x; coords[1] = y; } else { type = SEG_LINETO; switch(index) { case 1: coords[0] = x + width; coords[1] = y; break; case 2: coords[0] = x + width; coords[1] = y + height; break; case 3: coords[0] = x; coords[1] = y + height; break; case 4: coords[0] = x; coords[1] = y; break; } } if (t != null) { t.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Rectangle2D.java
public int currentSegment(float[] coords) { if (isDone()) { throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } if (index == 5) { return SEG_CLOSE; } int type; if (index == 0) { coords[0] = (float)x; coords[1] = (float)y; type = SEG_MOVETO; } else { type = SEG_LINETO; switch(index) { case 1: coords[0] = (float)(x + width); coords[1] = (float)y; break; case 2: coords[0] = (float)(x + width); coords[1] = (float)(y + height); break; case 3: coords[0] = (float)x; coords[1] = (float)(y + height); break; case 4: coords[0] = (float)x; coords[1] = (float)y; break; } } if (t != null) { t.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
public int currentSegment(double[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; if (index == 0) { type = SEG_MOVETO; coords[0] = x1; coords[1] = y1; } else { type = SEG_LINETO; coords[0] = x2; coords[1] = y2; } if (t != null) { t.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
public int currentSegment(float[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; if (index == 0) { type = SEG_MOVETO; coords[0] = (float)x1; coords[1] = (float)y1; } else { type = SEG_LINETO; coords[0] = (float)x2; coords[1] = (float)y2; } if (t != null) { t.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
public int currentSegment(double[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; int count; if (index == 0) { type = SEG_MOVETO; coords[0] = c.getX1(); coords[1] = c.getY1(); count = 1; } else { type = SEG_QUADTO; coords[0] = c.getCtrlX(); coords[1] = c.getCtrlY(); coords[2] = c.getX2(); coords[3] = c.getY2(); count = 2; } if (t != null) { t.transform(coords, 0, coords, 0, count); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
public int currentSegment(float[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; int count; if (index == 0) { type = SEG_MOVETO; coords[0] = (float)c.getX1(); coords[1] = (float)c.getY1(); count = 1; } else { type = SEG_QUADTO; coords[0] = (float)c.getCtrlX(); coords[1] = (float)c.getCtrlY(); coords[2] = (float)c.getX2(); coords[3] = (float)c.getY2(); count = 2; } if (t != null) { t.transform(coords, 0, coords, 0, count); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
public int currentSegment(double[] coords) { if (isDone()) { throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; int count; if (index == 0) { type = SEG_MOVETO; coords[0] = c.getX1(); coords[1] = c.getY1(); count = 1; } else { type = SEG_CUBICTO; coords[0] = c.getCtrlX1(); coords[1] = c.getCtrlY1(); coords[2] = c.getCtrlX2(); coords[3] = c.getCtrlY2(); coords[4] = c.getX2(); coords[5] = c.getY2(); count = 3; } if (t != null) { t.transform(coords, 0, coords, 0, count); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
public int currentSegment(float[] coords) { if (isDone()) { throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; int count; if (index == 0) { type = SEG_MOVETO; coords[0] = (float)c.getX1(); coords[1] = (float)c.getY1(); count = 1; } else { type = SEG_CUBICTO; coords[0] = (float)c.getCtrlX1(); coords[1] = (float)c.getCtrlY1(); coords[2] = (float)c.getCtrlX2(); coords[3] = (float)c.getCtrlY2(); coords[4] = (float)c.getX2(); coords[5] = (float)c.getY2(); count = 3; } if (t != null) { t.transform(coords, 0, coords, 0, count); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/PolylineShapeIterator.java
public int currentSegment(double[] coords) { if (isDone()) { throw new NoSuchElementException(MessageLocalization.getComposedMessage("line.iterator.out.of.bounds")); } int type = (index==0)?SEG_MOVETO:SEG_LINETO; coords[0] = poly.x[index]; coords[1] = poly.y[index]; if (affine != null) { affine.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/PolylineShapeIterator.java
public int currentSegment(float[] coords) { if (isDone()) { throw new NoSuchElementException(MessageLocalization.getComposedMessage("line.iterator.out.of.bounds")); } int type = (index==0)?SEG_MOVETO:SEG_LINETO; coords[0] = poly.x[index]; coords[1] = poly.y[index]; if (affine != null) { affine.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
public int currentSegment(double[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type = p.types[typeIndex]; int count = GeneralPath.pointShift[type]; for (int i = 0; i < count; i++) { coords[i] = p.points[pointIndex + i]; } if (t != null) { t.transform(coords, 0, coords, 0, count / 2); } pointIndex += count; return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
public int currentSegment(float[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type = p.types[typeIndex]; int count = GeneralPath.pointShift[type]; System.arraycopy(p.points, pointIndex, coords, 0, count); if (t != null) { t.transform(coords, 0, coords, 0, count / 2); } pointIndex += count; return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
public Entry next() { if (entry == null) { while (index-- > 0 && (entry = table[index]) == null); } if (entry != null) { Entry e = entry; entry = e.next; return e; } throw new NoSuchElementException(MessageLocalization.getComposedMessage("inthashtableiterator")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/IntHashtable.java
public Entry next() { if (entry == null) { while (index-- > 0 && (entry = table[index]) == null); } if (entry != null) { Entry e = entry; entry = e.next; return e; } throw new NoSuchElementException(MessageLocalization.getComposedMessage("inthashtableiterator")); }
0 0
(Lib) NullPointerException 15
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/misc/RenderingHints.java
public boolean containsKey(Object key) { if (key == null) { throw new NullPointerException(); } return map.containsKey(key); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactory.java
public static void setFontImp(final FontFactoryImp fontImp) { if (fontImp == null) throw new NullPointerException(MessageLocalization.getComposedMessage("fontfactoryimp.cannot.be.null")); FontFactory.fontImp = fontImp; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/VerticalText.java
public int go(boolean simulate) { boolean dirty = false; PdfContentByte graphics = null; if (text != null) { graphics = text.getDuplicate(); } else if (!simulate) throw new NullPointerException(MessageLocalization.getComposedMessage("verticaltext.go.with.simulate.eq.eq.false.and.text.eq.eq.null")); int status = 0; for (;;) { if (maxLines <= 0) { status = NO_MORE_COLUMN; if (chunks.isEmpty()) status |= NO_MORE_TEXT; break; } if (chunks.isEmpty()) { status = NO_MORE_TEXT; break; } PdfLine line = createLine(height); if (!simulate && !dirty) { text.beginText(); dirty = true; } shortenChunkArray(); if (!simulate) { text.setTextMatrix(startX, startY - line.indentLeft()); writeLine(line, text, graphics); } --maxLines; startX -= leading; } if (dirty) { text.endText(); text.add(graphics); } return status; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public int go(final boolean simulate, final IAccessibleElement elementToGo) throws DocumentException { if (composite) return goComposite(simulate); ListBody lBody = null; if (isTagged(canvas) && elementToGo instanceof ListItem) { lBody = ((ListItem)elementToGo).getListBody(); } addWaitingPhrase(); if (bidiLine == null) return NO_MORE_TEXT; descender = 0; linesWritten = 0; lastX = 0; boolean dirty = false; float ratio = spaceCharRatio; Object currentValues[] = new Object[2]; PdfFont currentFont = null; Float lastBaseFactor = new Float(0); currentValues[1] = lastBaseFactor; PdfDocument pdf = null; PdfContentByte graphics = null; PdfContentByte text = null; firstLineY = Float.NaN; int localRunDirection = PdfWriter.RUN_DIRECTION_NO_BIDI; if (runDirection != PdfWriter.RUN_DIRECTION_DEFAULT) localRunDirection = runDirection; if (canvas != null) { graphics = canvas; pdf = canvas.getPdfDocument(); if (!isTagged(canvas)) text = canvas.getDuplicate(); else text = canvas; } else if (!simulate) throw new NullPointerException(MessageLocalization.getComposedMessage("columntext.go.with.simulate.eq.eq.false.and.text.eq.eq.null")); if (!simulate) { if (ratio == GLOBAL_SPACE_CHAR_RATIO) ratio = text.getPdfWriter().getSpaceCharRatio(); else if (ratio < 0.001f) ratio = 0.001f; } if (!rectangularMode) { float max = 0; for (PdfChunk c : bidiLine.chunks) { max = Math.max(max, c.font.size()); } currentLeading = fixedLeading + max * multipliedLeading; } float firstIndent = 0; PdfLine line; float x1; int status = 0; while(true) { firstIndent = lastWasNewline ? indent : followingIndent; // if (rectangularMode) { if (rectangularWidth <= firstIndent + rightIndent) { status = NO_MORE_COLUMN; if (bidiLine.isEmpty()) status |= NO_MORE_TEXT; break; } if (bidiLine.isEmpty()) { status = NO_MORE_TEXT; break; } line = bidiLine.processLine(leftX, rectangularWidth - firstIndent - rightIndent, alignment, localRunDirection, arabicOptions, minY, yLine, descender); if (line == null) { status = NO_MORE_TEXT; break; } float[] maxSize = line.getMaxSize(fixedLeading, multipliedLeading); if (isUseAscender() && Float.isNaN(firstLineY)) currentLeading = line.getAscender(); else currentLeading = Math.max(maxSize[0], maxSize[1] - descender); if (yLine > maxY || yLine - currentLeading < minY ) { status = NO_MORE_COLUMN; bidiLine.restore(); break; } yLine -= currentLeading; if (!simulate && !dirty) { text.beginText(); dirty = true; } if (Float.isNaN(firstLineY)) firstLineY = yLine; updateFilledWidth(rectangularWidth - line.widthLeft()); x1 = leftX; } else { float yTemp = yLine - currentLeading; float xx[] = findLimitsTwoLines(); if (xx == null) { status = NO_MORE_COLUMN; if (bidiLine.isEmpty()) status |= NO_MORE_TEXT; yLine = yTemp; break; } if (bidiLine.isEmpty()) { status = NO_MORE_TEXT; yLine = yTemp; break; } x1 = Math.max(xx[0], xx[2]); float x2 = Math.min(xx[1], xx[3]); if (x2 - x1 <= firstIndent + rightIndent) continue; if (!simulate && !dirty) { text.beginText(); dirty = true; } line = bidiLine.processLine(x1, x2 - x1 - firstIndent - rightIndent, alignment, localRunDirection, arabicOptions, minY, yLine, descender); if (line == null) { status = NO_MORE_TEXT; yLine = yTemp; break; } } if (isTagged(canvas) && elementToGo instanceof ListItem) { if (!Float.isNaN(firstLineY) && !firstLineYDone) { if (!simulate) { ListLabel lbl = ((ListItem)elementToGo).getListLabel(); canvas.openMCBlock(lbl); Chunk symbol = new Chunk(((ListItem)elementToGo).getListSymbol()); if (!lbl.getTagLabelContent()) { symbol.setRole(null); } ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(symbol), leftX + lbl.getIndentation(), firstLineY, 0); canvas.closeMCBlock(lbl); } firstLineYDone = true; } } if (!simulate) { if (lBody != null) { canvas.openMCBlock(lBody); lBody = null; } currentValues[0] = currentFont; text.setTextMatrix(x1 + (line.isRTL() ? rightIndent : firstIndent) + line.indentLeft(), yLine); lastX = pdf.writeLineToContent(line, text, graphics, currentValues, ratio); currentFont = (PdfFont)currentValues[0]; } lastWasNewline = repeatFirstLineIndent && line.isNewlineSplit(); yLine -= line.isNewlineSplit() ? extraParagraphSpace : 0; ++linesWritten; descender = line.getDescender(); } if (dirty) { text.endText(); if (canvas != text) canvas.add(text); } return status; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
private void showText2(final String text) { if (state.fontDetails == null) throw new NullPointerException(MessageLocalization.getComposedMessage("font.and.size.must.be.set.before.writing.any.text")); byte b[] = state.fontDetails.convertToBytes(text); escapeString(b, content); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void showTextKerned(final String text) { if (state.fontDetails == null) throw new NullPointerException(MessageLocalization.getComposedMessage("font.and.size.must.be.set.before.writing.any.text")); BaseFont bf = state.fontDetails.getBaseFont(); if (bf.hasKernPairs()) showText(getKernArray(text, bf)); else { showText(text); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
private void showTextAligned(final int alignment, final String text, float x, float y, final float rotation, final boolean kerned) { if (state.fontDetails == null) throw new NullPointerException(MessageLocalization.getComposedMessage("font.and.size.must.be.set.before.writing.any.text")); if (rotation == 0) { switch (alignment) { case ALIGN_CENTER: x -= getEffectiveStringWidth(text, kerned) / 2; break; case ALIGN_RIGHT: x -= getEffectiveStringWidth(text, kerned); break; } setTextMatrix(x, y); if (kerned) showTextKerned(text); else showText(text); } else { double alpha = rotation * Math.PI / 180.0; float cos = (float)Math.cos(alpha); float sin = (float)Math.sin(alpha); float len; switch (alignment) { case ALIGN_CENTER: len = getEffectiveStringWidth(text, kerned) / 2; x -= len * cos; y -= len * sin; break; case ALIGN_RIGHT: len = getEffectiveStringWidth(text, kerned); x -= len * cos; y -= len * sin; break; } setTextMatrix(cos, sin, -sin, cos, x, y); if (kerned) showTextKerned(text); else showText(text); setTextMatrix(0f, 0f); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
protected void checkWriter() { if (writer == null) throw new NullPointerException(MessageLocalization.getComposedMessage("the.writer.in.pdfcontentbyte.is.null")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void showText(final PdfTextArray text) { if (!inText && isTagged()) { beginText(true); } if (state.fontDetails == null) throw new NullPointerException(MessageLocalization.getComposedMessage("font.and.size.must.be.set.before.writing.any.text")); content.append("["); ArrayList<Object> arrayList = text.getArrayList(); boolean lastWasNumber = false; for (Object obj : arrayList) { if (obj instanceof String) { showText2((String)obj); updateTx((String)obj, 0); lastWasNumber = false; } else { if (lastWasNumber) content.append(' '); else lastWasNumber = true; content.append(((Float)obj).floatValue()); updateTx("", ((Float)obj).floatValue()); } } content.append("]TJ").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfLayer.java
public static PdfLayer createTitle(String title, PdfWriter writer) { if (title == null) throw new NullPointerException(MessageLocalization.getComposedMessage("title.cannot.be.null")); PdfLayer layer = new PdfLayer(title); writer.registerLayer(layer); return layer; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
public void paintCode() { int maxErr, lenErr, tot, pad; if ((options & PDF417_USE_RAW_CODEWORDS) != 0) { if (lenCodewords > MAX_DATA_CODEWORDS || lenCodewords < 1 || lenCodewords != codewords[0]) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.codeword.size")); } } else { if (text == null) throw new NullPointerException(MessageLocalization.getComposedMessage("text.cannot.be.null")); if (text.length > ABSOLUTE_MAX_TEXT_SIZE) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } segmentList = new SegmentList(); breakString(); //dumpList(); assemble(); segmentList = null; codewords[0] = lenCodewords = cwPtr; } maxErr = maxPossibleErrorLevel(MAX_DATA_CODEWORDS + 2 - lenCodewords); if ((options & PDF417_USE_ERROR_LEVEL) == 0) { if (lenCodewords < 41) errorLevel = 2; else if (lenCodewords < 161) errorLevel = 3; else if (lenCodewords < 321) errorLevel = 4; else errorLevel = 5; } if (errorLevel < 0) errorLevel = 0; else if (errorLevel > maxErr) errorLevel = maxErr; if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) codeRows = 90; lenErr = 2 << errorLevel; boolean fixedColumn = (options & PDF417_FIXED_ROWS) == 0; boolean skipRowColAdjust = false; tot = lenCodewords + lenErr; if ((options & PDF417_FIXED_RECTANGLE) != 0) { tot = codeColumns * codeRows; if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } if (tot < lenCodewords + lenErr) tot = lenCodewords + lenErr; else skipRowColAdjust = true; } else if ((options & (PDF417_FIXED_COLUMNS | PDF417_FIXED_ROWS)) == 0) { double c, b; fixedColumn = true; if (aspectRatio < 0.001) aspectRatio = 0.001f; else if (aspectRatio > 1000) aspectRatio = 1000; b = 73 * aspectRatio - 4; c = (-b + Math.sqrt(b * b + 4 * 17 * aspectRatio * (lenCodewords + lenErr) * yHeight)) / (2 * 17 * aspectRatio); codeColumns = (int)(c + 0.5); if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; } if (!skipRowColAdjust) { if (fixedColumn) { codeRows = (tot - 1) / codeColumns + 1; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) { codeRows = 90; codeColumns = (tot - 1) / 90 + 1; } } else { codeColumns = (tot - 1) / codeRows + 1; if (codeColumns > 30) { codeColumns = 30; codeRows = (tot - 1) / 30 + 1; } } tot = codeRows * codeColumns; } if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } errorLevel = maxPossibleErrorLevel(tot - lenCodewords); lenErr = 2 << errorLevel; pad = tot - lenErr - lenCodewords; if ((options & PDF417_USE_MACRO) != 0) { // the padding comes before the control block System.arraycopy(codewords, macroIndex, codewords, macroIndex + pad, pad); cwPtr = lenCodewords + pad; while (pad-- != 0) codewords[macroIndex++] = TEXT_MODE; } else { cwPtr = lenCodewords; while (pad-- != 0) codewords[cwPtr++] = TEXT_MODE; } codewords[0] = lenCodewords = cwPtr; calculateErrorCorrection(lenCodewords); lenCodewords = tot; outPaintCode(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
public Collection<byte[]> getEncoded(X509Certificate checkCert, String url) { if (checkCert == null) return null; List<URL> urllist = new ArrayList<URL>(urls); if (urllist.size() == 0) { LOGGER.info("Looking for CRL for certificate " + checkCert.getSubjectDN()); try { if (url == null) url = CertificateUtil.getCRLURL(checkCert); if (url == null) throw new NullPointerException(); urllist.add(new URL(url)); LOGGER.info("Found CRL url: " + url); } catch (Exception e) { LOGGER.info("Skipped CRL url: " + e.getMessage()); } } ArrayList<byte[]> ar = new ArrayList<byte[]>(); for (URL urlt : urllist) { try { LOGGER.info("Checking CRL: " + urlt); HttpURLConnection con = (HttpURLConnection)urlt.openConnection(); if (con.getResponseCode() / 100 != 2) { throw new IOException(MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode())); } //Get Response InputStream inp = (InputStream) con.getContent(); byte[] buf = new byte[1024]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while (true) { int n = inp.read(buf, 0, buf.length); if (n <= 0) break; bout.write(buf, 0, n); } inp.close(); ar.add(bout.toByteArray()); LOGGER.info("Added CRL found at: " + urlt); } catch (Exception e) { LOGGER.info("Skipped CRL: " + e.getMessage() + " for " + urlt); } } return ar; }
0 0
(Domain) PdfXConformanceException 14
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setPDFXConformance(final int pdfx) { if (!(pdfIsoConformance instanceof PdfXConformanceImp)) return; if (((PdfXConformance)pdfIsoConformance).getPDFXConformance() == pdfx) return; if (pdf.isOpen()) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("pdfx.conformance.can.only.be.set.before.opening.the.document")); if (crypto != null) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("a.pdfx.conforming.document.cannot.be.encrypted")); if (pdfx != PDFXNONE) setPdfVersion(VERSION_1_3); ((PdfXConformance)pdfIsoConformance).setPDFXConformance(pdfx); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfXConformanceImp.java
public static void checkPDFXConformance(PdfWriter writer, int key, Object obj1) { if (writer == null || !writer.isPdfX()) return; int conf = writer.getPDFXConformance(); switch (key) { case PdfIsoKeys.PDFISOKEY_COLOR: switch (conf) { case PdfWriter.PDFX1A2001: if (obj1 instanceof ExtendedColor) { ExtendedColor ec = (ExtendedColor)obj1; switch (ec.getType()) { case ExtendedColor.TYPE_CMYK: case ExtendedColor.TYPE_GRAY: return; case ExtendedColor.TYPE_RGB: throw new PdfXConformanceException(MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed")); case ExtendedColor.TYPE_SEPARATION: SpotColor sc = (SpotColor)ec; checkPDFXConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, sc.getPdfSpotColor().getAlternativeCS()); break; case ExtendedColor.TYPE_SHADING: ShadingColor xc = (ShadingColor)ec; checkPDFXConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, xc.getPdfShadingPattern().getShading().getColorSpace()); break; case ExtendedColor.TYPE_PATTERN: PatternColor pc = (PatternColor)ec; checkPDFXConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, pc.getPainter().getDefaultColor()); break; } } else if (obj1 instanceof BaseColor) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed")); break; } break; case PdfIsoKeys.PDFISOKEY_CMYK: break; case PdfIsoKeys.PDFISOKEY_RGB: if (conf == PdfWriter.PDFX1A2001) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed")); break; case PdfIsoKeys.PDFISOKEY_FONT: if (!((BaseFont)obj1).isEmbedded()) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("all.the.fonts.must.be.embedded.this.one.isn.t.1", ((BaseFont)obj1).getPostscriptFontName())); break; case PdfIsoKeys.PDFISOKEY_IMAGE: PdfImage image = (PdfImage)obj1; if (image.get(PdfName.SMASK) != null) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("the.smask.key.is.not.allowed.in.images")); switch (conf) { case PdfWriter.PDFX1A2001: PdfObject cs = image.get(PdfName.COLORSPACE); if (cs == null) return; if (cs.isName()) { if (PdfName.DEVICERGB.equals(cs)) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed")); } else if (cs.isArray()) { if (PdfName.CALRGB.equals(((PdfArray)cs).getPdfObject(0))) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("colorspace.calrgb.is.not.allowed")); } break; } break; case PdfIsoKeys.PDFISOKEY_GSTATE: PdfDictionary gs = (PdfDictionary)obj1; PdfObject obj = gs.get(PdfName.BM); if (obj != null && !PdfGState.BM_NORMAL.equals(obj) && !PdfGState.BM_COMPATIBLE.equals(obj)) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("blend.mode.1.not.allowed", obj.toString())); obj = gs.get(PdfName.CA); double v = 0.0; if (obj != null && (v = ((PdfNumber)obj).doubleValue()) != 1.0) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("transparency.is.not.allowed.ca.eq.1", String.valueOf(v))); obj = gs.get(PdfName.ca); v = 0.0; if (obj != null && (v = ((PdfNumber)obj).doubleValue()) != 1.0) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("transparency.is.not.allowed.ca.eq.1", String.valueOf(v))); break; case PdfIsoKeys.PDFISOKEY_LAYER: throw new PdfXConformanceException(MessageLocalization.getComposedMessage("layers.are.not.allowed")); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public boolean newPage() { try { flushFloatingElements(); } catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } lastElementType = -1; if (isPageEmpty()) { setNewPageSizeAndMargins(); return false; } if (!open || close) { throw new RuntimeException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) pageEvent.onEndPage(writer, this); //Added to inform any listeners that we are moving to a new page (added by David Freels) super.newPage(); // the following 2 lines were added by Pelikan Stephan indentation.imageIndentLeft = 0; indentation.imageIndentRight = 0; try { // we flush the arraylist with recently written lines flushLines(); // we prepare the elements of the page dictionary // [U1] page size and rotation int rotation = pageSize.getRotation(); // [C10] if (writer.isPdfIso()) { if (thisBoxSize.containsKey("art") && thisBoxSize.containsKey("trim")) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("only.one.of.artbox.or.trimbox.can.exist.in.the.page")); if (!thisBoxSize.containsKey("art") && !thisBoxSize.containsKey("trim")) { if (thisBoxSize.containsKey("crop")) thisBoxSize.put("trim", thisBoxSize.get("crop")); else thisBoxSize.put("trim", new PdfRectangle(pageSize, pageSize.getRotation())); } } // [M1] pageResources.addDefaultColorDiff(writer.getDefaultColorspace()); if (writer.isRgbTransparencyBlending()) { PdfDictionary dcs = new PdfDictionary(); dcs.put(PdfName.CS, PdfName.DEVICERGB); pageResources.addDefaultColorDiff(dcs); } PdfDictionary resources = pageResources.getResources(); // we create the page dictionary PdfPage page = new PdfPage(new PdfRectangle(pageSize, rotation), thisBoxSize, resources, rotation); if (isTagged(writer)) { page.put(PdfName.TABS, PdfName.S); } else { page.put(PdfName.TABS, writer.getTabs()); } page.putAll(writer.getPageDictEntries()); writer.resetPageDictEntries(); // we complete the page dictionary // [U3] page actions: additional actions if (pageAA != null) { page.put(PdfName.AA, writer.addToBody(pageAA).getIndirectReference()); pageAA = null; } // [C5] and [C8] we add the annotations if (annotationsImp.hasUnusedAnnotations()) { PdfArray array = annotationsImp.rotateAnnotations(writer, pageSize); if (array.size() != 0) page.put(PdfName.ANNOTS, array); } // [F12] we add tag info if (isTagged(writer)) page.put(PdfName.STRUCTPARENTS, new PdfNumber(writer.getCurrentPageNumber() - 1)); if (text.size() > textEmptySize || isTagged(writer)) text.endText(); else text = null; ArrayList<IAccessibleElement> mcBlocks = null; if (isTagged(writer)) { mcBlocks = writer.getDirectContent().saveMCBlocks(); } writer.add(page, new PdfContents(writer.getDirectContentUnder(), graphics, !isTagged(writer) ? text : null, writer.getDirectContent(), pageSize)); // we initialize the new page initPage(); if (isTagged(writer)) { writer.getDirectContentUnder().restoreMCBlocks(mcBlocks); } } catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } catch (IOException ioe) { throw new ExceptionConverter(ioe); } return true; }
0 0
(Domain) BadElementException 12
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final int width, final int height, final boolean reverseBits, final int typeCCITT, final int parameters, final byte[] data, final int transparency[]) throws BadElementException { if (transparency != null && transparency.length != 2) throw new BadElementException(MessageLocalization.getComposedMessage("transparency.length.must.be.equal.to.2.with.ccitt.images")); Image img = new ImgCCITT(width, height, reverseBits, typeCCITT, parameters, data); img.transparency = transparency; return img; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final int width, final int height, final int components, final int bpc, final byte data[], final int transparency[]) throws BadElementException { if (transparency != null && transparency.length != components * 2) throw new BadElementException(MessageLocalization.getComposedMessage("transparency.length.must.be.equal.to.componentes.2")); if (components == 1 && bpc == 1) { byte g4[] = CCITTG4Encoder.compress(data, width, height); return Image.getInstance(width, height, false, Image.CCITTG4, Image.CCITT_BLACKIS1, g4, transparency); } Image img = new ImgRaw(width, height, components, bpc, data); img.transparency = transparency; return img; }
// 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/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(); } }
0 38
              
// 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 int width, final int height, final int components, final int bpc, final byte data[]) throws BadElementException { return Image.getInstance(width, height, components, bpc, data, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final int width, final int height, final boolean reverseBits, final int typeCCITT, final int parameters, final byte[] data) throws BadElementException { return Image.getInstance(width, height, reverseBits, typeCCITT, parameters, data, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final int width, final int height, final boolean reverseBits, final int typeCCITT, final int parameters, final byte[] data, final int transparency[]) throws BadElementException { if (transparency != null && transparency.length != 2) throw new BadElementException(MessageLocalization.getComposedMessage("transparency.length.must.be.equal.to.2.with.ccitt.images")); Image img = new ImgCCITT(width, height, reverseBits, typeCCITT, parameters, data); img.transparency = transparency; return img; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final int width, final int height, final int components, final int bpc, final byte data[], final int transparency[]) throws BadElementException { if (transparency != null && transparency.length != components * 2) throw new BadElementException(MessageLocalization.getComposedMessage("transparency.length.must.be.equal.to.componentes.2")); if (components == 1 && bpc == 1) { byte g4[] = CCITTG4Encoder.compress(data, width, height); return Image.getInstance(width, height, false, Image.CCITTG4, Image.CCITT_BLACKIS1, g4, transparency); } Image img = new ImgRaw(width, height, components, bpc, data); img.transparency = transparency; return img; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final PdfTemplate template) throws BadElementException { return new ImgTemplate(template); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final PRIndirectReference ref) throws BadElementException { PdfDictionary dic = (PdfDictionary)PdfReader.getPdfObjectRelease(ref); int width = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.WIDTH))).intValue(); int height = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.HEIGHT))).intValue(); Image imask = null; PdfObject obj = dic.get(PdfName.SMASK); if (obj != null && obj.isIndirect()) { imask = getInstance((PRIndirectReference)obj); } else { obj = dic.get(PdfName.MASK); if (obj != null && obj.isIndirect()) { PdfObject obj2 = PdfReader.getPdfObjectRelease(obj); if (obj2 instanceof PdfDictionary) imask = getInstance((PRIndirectReference)obj); } } Image img = new ImgRaw(width, height, 1, 1, null); img.imageMask = imask; img.directReference = ref; 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, 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 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/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/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 Image indexedModel(byte bdata[], int bpc, int paletteEntries) throws BadElementException { Image img = new ImgRaw(width, height, 1, bpc, bdata); PdfArray colorspace = new PdfArray(); colorspace.add(PdfName.INDEXED); colorspace.add(PdfName.DEVICERGB); byte np[] = getPalette(paletteEntries); int len = np.length; colorspace.add(new PdfNumber(len / 3 - 1)); colorspace.add(new PdfString(np)); PdfDictionary ad = new PdfDictionary(); ad.put(PdfName.COLORSPACE, colorspace); img.setAdditional(ad); return img; }
// 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/BarcodeQRCode.java
public Image getImage() throws BadElementException { byte[] b = getBitMatrix(); byte g4[] = CCITTG4Encoder.compress(b, bm.getWidth(), bm.getHeight()); return Image.getInstance(bm.getWidth(), bm.getHeight(), false, Image.CCITTG4, Image.CCITT_BLACKIS1, g4, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
public Image getImage() throws BadElementException { paintCode(); byte g4[] = CCITTG4Encoder.compress(outBits, bitColumns, codeRows); return Image.getInstance(bitColumns, codeRows, false, Image.CCITTG4, (options & PDF417_INVERT_BITMAP) == 0 ? 0 : Image.CCITT_BLACKIS1, g4, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeDatamatrix.java
public Image createImage() throws BadElementException { if (image == null) return null; byte g4[] = CCITTG4Encoder.compress(image, width + 2 * ws, height + 2 * ws); return Image.getInstance(width + 2 * ws, height + 2 * ws, false, Image.CCITTG4, 0, g4, null); }
(Domain) UnsupportedPdfException 12
              
// 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/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/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; }
0 0
(Lib) ClassCastException 11
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFField.java
public int getAsInt(int index) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return ((byte[])data)[index] & 0xff; case TIFF_SBYTE: return ((byte[])data)[index]; case TIFF_SHORT: return ((char[])data)[index] & 0xffff; case TIFF_SSHORT: return ((short[])data)[index]; case TIFF_SLONG: return ((int[])data)[index]; default: throw new ClassCastException(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFField.java
public long getAsLong(int index) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return ((byte[])data)[index] & 0xff; case TIFF_SBYTE: return ((byte[])data)[index]; case TIFF_SHORT: return ((char[])data)[index] & 0xffff; case TIFF_SSHORT: return ((short[])data)[index]; case TIFF_SLONG: return ((int[])data)[index]; case TIFF_LONG: return ((long[])data)[index]; default: throw new ClassCastException(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFField.java
public float getAsFloat(int index) { switch (type) { case TIFF_BYTE: return ((byte[])data)[index] & 0xff; case TIFF_SBYTE: return ((byte[])data)[index]; case TIFF_SHORT: return ((char[])data)[index] & 0xffff; case TIFF_SSHORT: return ((short[])data)[index]; case TIFF_SLONG: return ((int[])data)[index]; case TIFF_LONG: return ((long[])data)[index]; case TIFF_FLOAT: return ((float[])data)[index]; case TIFF_DOUBLE: return (float)((double[])data)[index]; case TIFF_SRATIONAL: int[] ivalue = getAsSRational(index); return (float)((double)ivalue[0]/ivalue[1]); case TIFF_RATIONAL: long[] lvalue = getAsRational(index); return (float)((double)lvalue[0]/lvalue[1]); default: throw new ClassCastException(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFField.java
public double getAsDouble(int index) { switch (type) { case TIFF_BYTE: return ((byte[])data)[index] & 0xff; case TIFF_SBYTE: return ((byte[])data)[index]; case TIFF_SHORT: return ((char[])data)[index] & 0xffff; case TIFF_SSHORT: return ((short[])data)[index]; case TIFF_SLONG: return ((int[])data)[index]; case TIFF_LONG: return ((long[])data)[index]; case TIFF_FLOAT: return ((float[])data)[index]; case TIFF_DOUBLE: return ((double[])data)[index]; case TIFF_SRATIONAL: int[] ivalue = getAsSRational(index); return (double)ivalue[0]/ivalue[1]; case TIFF_RATIONAL: long[] lvalue = getAsRational(index); return (double)lvalue[0]/lvalue[1]; default: throw new ClassCastException(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
Override public void add(final int index, final Element element) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } try { if (element.isNestable()) { super.add(index, element); } else { throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
Override public boolean add(final Element element) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } try { if (element.type() == Element.SECTION) { Section section = (Section) element; section.setNumbers(++subsections, numbers); return super.add(section); } else if (element instanceof MarkedSection && ((MarkedObject)element).element.type() == Element.SECTION) { MarkedSection mo = (MarkedSection)element; Section section = (Section)mo.element; section.setNumbers(++subsections, numbers); return super.add(mo); } else if (element.isNestable()) { return super.add(element); } else { throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
Override public void add(final int index, final Element element) { if (element == null) return; switch (element.type()) { case Element.CHUNK: Chunk chunk = (Chunk) element; if (!font.isStandardFont()) { chunk.setFont(font.difference(chunk.getFont())); } if (hyphenation != null && chunk.getHyphenation() == null && !chunk.isEmpty()) { chunk.setHyphenation(hyphenation); } super.add(index, chunk); return; case Element.PHRASE: case Element.PARAGRAPH: case Element.MARKED: case Element.DIV: case Element.ANCHOR: case Element.ANNOTATION: case Element.PTABLE: case Element.LIST: case Element.YMARK: case Element.WRITABLE_DIRECT: super.add(index, element); return; default: throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", element.getClass().getName())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
Override public boolean add(final Element element) { if (element == null) return false; try { // TODO same as in document - change switch to generic adding that works everywhere switch(element.type()) { case Element.CHUNK: return addChunk((Chunk) element); case Element.PHRASE: case Element.PARAGRAPH: Phrase phrase = (Phrase) element; boolean success = true; Element e; for (Object element2 : phrase) { e = (Element) element2; if (e instanceof Chunk) { success &= addChunk((Chunk)e); } else { success &= this.add(e); } } return success; case Element.MARKED: case Element.DIV: case Element.ANCHOR: case Element.ANNOTATION: case Element.PTABLE: // case added by mr. Karen Vardanyan case Element.LIST: case Element.YMARK: case Element.WRITABLE_DIRECT: return super.add(element); default: throw new ClassCastException(String.valueOf(element.type())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } }
3
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
0
(Domain) BadPdfFormatException 10
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
protected void setReader(PdfReader reader) throws BadPdfFormatException { this.reader = reader; PdfObject obj = reader.getCatalog().get(PdfName.STRUCTTREEROOT); obj = getDirectObject(obj); if ((obj == null) || (!obj.isDictionary())) throw new BadPdfFormatException(MessageLocalization.getComposedMessage("no.structtreeroot.found")); structTreeRoot = (PdfDictionary) obj; obj = PdfStructTreeController.getDirectObject(structTreeRoot.get(PdfName.PARENTTREE)); if (!obj.isDictionary()) throw new BadPdfFormatException(MessageLocalization.getComposedMessage("the.document.does.not.contain.parenttree")); parentTree = (PdfDictionary) obj; sourceRoleMap = null; sourceClassMap = null; }
// 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
protected void addClass(PdfObject object) throws BadPdfFormatException { object = getDirectObject(object); if (object.isDictionary()) { PdfObject curClass = ((PdfDictionary) object).get(PdfName.C); if (curClass == null) return; if (curClass.isArray()) { PdfArray array = (PdfArray) curClass; for (int i = 0; i < array.size(); ++i) { addClass(array.getPdfObject(i)); } } else if (curClass.isName()) addClass(curClass); } else if (object.isName()) { PdfName name = (PdfName) object; if (sourceClassMap == null) { object = getDirectObject(structTreeRoot.get(PdfName.CLASSMAP)); if (object == null || !object.isDictionary()) { return; } sourceClassMap = (PdfDictionary) object; } object = getDirectObject(sourceClassMap.get(name)); if (object == null) { return; } PdfObject put = structureTreeRoot.getMappedClass(name); if (put != null) { if (!compareObjects(put, object)) { throw new BadPdfFormatException(MessageLocalization.getComposedMessage("conflict.in.classmap", name)); } } else { if (object.isDictionary()) structureTreeRoot.mapClass(name, getDirectDict((PdfDictionary) object)); else if (object.isArray()) { structureTreeRoot.mapClass(name, getDirectArray((PdfArray) object)); } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
protected void addRole(PdfName structType) throws BadPdfFormatException { if (structType == null) { return; } for (PdfName name : standardTypes) { if (name.equals(structType)) return; } if (sourceRoleMap == null) { PdfObject object = getDirectObject(structTreeRoot.get(PdfName.ROLEMAP)); if (object == null || !object.isDictionary()) { return; } sourceRoleMap = (PdfDictionary) object; } PdfObject object = sourceRoleMap.get(structType); if (object == null || !object.isName()) { return; } PdfObject currentRole; if (roleMap == null) { roleMap = new PdfDictionary(); structureTreeRoot.put(PdfName.ROLEMAP, roleMap); roleMap.put(structType, object); } else if ((currentRole = roleMap.get(structType)) != null) { if (!currentRole.equals(object)) { throw new BadPdfFormatException(MessageLocalization.getComposedMessage("conflict.in.rolemap", object)); } } else { roleMap.put(structType, object); } }
2
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContents.java
catch (Exception e) { throw new BadPdfFormatException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
catch(IOException ioe) { throw new BadPdfFormatException(ioe.getMessage()); }
24
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
protected void setReader(PdfReader reader) throws BadPdfFormatException { this.reader = reader; PdfObject obj = reader.getCatalog().get(PdfName.STRUCTTREEROOT); obj = getDirectObject(obj); if ((obj == null) || (!obj.isDictionary())) throw new BadPdfFormatException(MessageLocalization.getComposedMessage("no.structtreeroot.found")); structTreeRoot = (PdfDictionary) obj; obj = PdfStructTreeController.getDirectObject(structTreeRoot.get(PdfName.PARENTTREE)); if (!obj.isDictionary()) throw new BadPdfFormatException(MessageLocalization.getComposedMessage("the.document.does.not.contain.parenttree")); parentTree = (PdfDictionary) obj; sourceRoleMap = null; sourceClassMap = null; }
// 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/PdfStructTreeController.java
protected void addClass(PdfObject object) throws BadPdfFormatException { object = getDirectObject(object); if (object.isDictionary()) { PdfObject curClass = ((PdfDictionary) object).get(PdfName.C); if (curClass == null) return; if (curClass.isArray()) { PdfArray array = (PdfArray) curClass; for (int i = 0; i < array.size(); ++i) { addClass(array.getPdfObject(i)); } } else if (curClass.isName()) addClass(curClass); } else if (object.isName()) { PdfName name = (PdfName) object; if (sourceClassMap == null) { object = getDirectObject(structTreeRoot.get(PdfName.CLASSMAP)); if (object == null || !object.isDictionary()) { return; } sourceClassMap = (PdfDictionary) object; } object = getDirectObject(sourceClassMap.get(name)); if (object == null) { return; } PdfObject put = structureTreeRoot.getMappedClass(name); if (put != null) { if (!compareObjects(put, object)) { throw new BadPdfFormatException(MessageLocalization.getComposedMessage("conflict.in.classmap", name)); } } else { if (object.isDictionary()) structureTreeRoot.mapClass(name, getDirectDict((PdfDictionary) object)); else if (object.isArray()) { structureTreeRoot.mapClass(name, getDirectArray((PdfArray) object)); } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
protected void addRole(PdfName structType) throws BadPdfFormatException { if (structType == null) { return; } for (PdfName name : standardTypes) { if (name.equals(structType)) return; } if (sourceRoleMap == null) { PdfObject object = getDirectObject(structTreeRoot.get(PdfName.ROLEMAP)); if (object == null || !object.isDictionary()) { return; } sourceRoleMap = (PdfDictionary) object; } PdfObject object = sourceRoleMap.get(structType); if (object == null || !object.isName()) { return; } PdfObject currentRole; if (roleMap == null) { roleMap = new PdfDictionary(); structureTreeRoot.put(PdfName.ROLEMAP, roleMap); roleMap.put(structType, object); } else if ((currentRole = roleMap.get(structType)) != null) { if (!currentRole.equals(object)) { throw new BadPdfFormatException(MessageLocalization.getComposedMessage("conflict.in.rolemap", object)); } } else { roleMap.put(structType, object); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
public PdfImportedPage getImportedPage(PdfReader reader, int pageNumber, boolean keepTaggedPdfStructure) throws BadPdfFormatException { updateRootKids = false; if (!keepTaggedPdfStructure) return getImportedPage(reader, pageNumber); else { if (structTreeController != null) { if (reader != structTreeController.reader) structTreeController.setReader(reader); } else { structTreeController = new PdfStructTreeController(reader, this); } ImportedPage newPage = new ImportedPage(reader, pageNumber); switch (checkStructureTreeRootKids(newPage)) { case -1: //-1 - clear , update clearIndirects(reader); updateRootKids = true; break; case 0: //0 - not clear, not update updateRootKids = false; break; case 1: //1 - not clear, update updateRootKids = true; break; } importedPages.add(newPage); disableIndirects.clear(); parentObjects.clear(); return getImportedPageImpl(reader, pageNumber); } }
// 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
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/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; }
(Lib) InternalError 10
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/RectangularShape.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Dimension2D.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Point2D.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
Override public Object clone() { try { GeneralPath p = (GeneralPath) super.clone(); p.types = types.clone(); p.points = points.clone(); return p; } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
Override public Object clone() { try { LongHashtable t = (LongHashtable)super.clone(); t.table = new Entry[table.length]; for (int i = table.length ; i-- > 0 ; ) { t.table[i] = table[i] != null ? (Entry)table[i].clone() : null; } return t; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/IntHashtable.java
Override public Object clone() { try { IntHashtable t = (IntHashtable)super.clone(); t.table = new Entry[table.length]; for (int i = table.length ; i-- > 0 ; ) { t.table[i] = table[i] != null ? (Entry)table[i].clone() : null; } return t; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } }
10
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/RectangularShape.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Dimension2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Point2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/IntHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
0
(Lib) IndexOutOfBoundsException 7
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfIndirectReference getPageReference(int page) { --page; if (page < 0) throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.page.number.must.be.gt.eq.1")); PdfIndirectReference ref; if (page < pageReferences.size()) { ref = pageReferences.get(page); if (ref == null) { ref = body.getPdfIndirectReference(); pageReferences.set(page, ref); } } else { int empty = page - pageReferences.size(); for (int k = 0; k < empty; ++k) pageReferences.add(null); ref = body.getPdfIndirectReference(); pageReferences.add(ref); } return ref; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontSelector.java
public Phrase process(String text) { int fsize = fonts.size(); if (fsize == 0) throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("no.font.is.defined")); char cc[] = text.toCharArray(); int len = cc.length; StringBuffer sb = new StringBuffer(); Font font = null; int lastidx = -1; Phrase ret = new Phrase(); for (int k = 0; k < len; ++k) { char c = cc[k]; if (c == '\n' || c == '\r') { sb.append(c); continue; } if (Utilities.isSurrogatePair(cc, k)) { int u = Utilities.convertToUtf32(cc, k); for (int f = 0; f < fsize; ++f) { font = fonts.get(f); if (font.getBaseFont().charExists(u)) { if (lastidx != f) { if (sb.length() > 0 && lastidx != -1) { Chunk ck = new Chunk(sb.toString(), fonts.get(lastidx)); ret.add(ck); sb.setLength(0); } lastidx = f; } sb.append(c); sb.append(cc[++k]); break; } } } else { for (int f = 0; f < fsize; ++f) { font = fonts.get(f); if (font.getBaseFont().charExists(c)) { if (lastidx != f) { if (sb.length() > 0 && lastidx != -1) { Chunk ck = new Chunk(sb.toString(), fonts.get(lastidx)); ret.add(ck); sb.setLength(0); } lastidx = f; } sb.append(c); break; } } } } if (sb.length() > 0) { Chunk ck = new Chunk(sb.toString(), fonts.get(lastidx == -1 ? 0 : lastidx)); ret.add(ck); } return ret; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
private void textCompaction(byte[] input, int start, int length) { int dest[] = new int[ABSOLUTE_MAX_TEXT_SIZE * 2]; int mode = ALPHA; int ptr = 0; int fullBytes = 0; int v = 0; int k; int size; length += start; for (k = start; k < length; ++k) { v = getTextTypeAndValue(input, length, k); if ((v & mode) != 0) { dest[ptr++] = v & 0xff; continue; } if ((v & ISBYTE) != 0) { if ((ptr & 1) != 0) { //add a padding word dest[ptr++] = PAL; mode = (mode & PUNCTUATION) != 0 ? ALPHA : mode; } dest[ptr++] = BYTESHIFT; dest[ptr++] = v & 0xff; fullBytes += 2; continue; } switch (mode) { case ALPHA: if ((v & LOWER) != 0) { dest[ptr++] = LL; dest[ptr++] = v & 0xff; mode = LOWER; } else if ((v & MIXED) != 0) { dest[ptr++] = ML; dest[ptr++] = v & 0xff; mode = MIXED; } else if ((getTextTypeAndValue(input, length, k + 1) & getTextTypeAndValue(input, length, k + 2) & PUNCTUATION) != 0) { dest[ptr++] = ML; dest[ptr++] = PL; dest[ptr++] = v & 0xff; mode = PUNCTUATION; } else { dest[ptr++] = PS; dest[ptr++] = v & 0xff; } break; case LOWER: if ((v & ALPHA) != 0) { if ((getTextTypeAndValue(input, length, k + 1) & getTextTypeAndValue(input, length, k + 2) & ALPHA) != 0) { dest[ptr++] = ML; dest[ptr++] = AL; mode = ALPHA; } else { dest[ptr++] = AS; } dest[ptr++] = v & 0xff; } else if ((v & MIXED) != 0) { dest[ptr++] = ML; dest[ptr++] = v & 0xff; mode = MIXED; } else if ((getTextTypeAndValue(input, length, k + 1) & getTextTypeAndValue(input, length, k + 2) & PUNCTUATION) != 0) { dest[ptr++] = ML; dest[ptr++] = PL; dest[ptr++] = v & 0xff; mode = PUNCTUATION; } else { dest[ptr++] = PS; dest[ptr++] = v & 0xff; } break; case MIXED: if ((v & LOWER) != 0) { dest[ptr++] = LL; dest[ptr++] = v & 0xff; mode = LOWER; } else if ((v & ALPHA) != 0) { dest[ptr++] = AL; dest[ptr++] = v & 0xff; mode = ALPHA; } else if ((getTextTypeAndValue(input, length, k + 1) & getTextTypeAndValue(input, length, k + 2) & PUNCTUATION) != 0) { dest[ptr++] = PL; dest[ptr++] = v & 0xff; mode = PUNCTUATION; } else { dest[ptr++] = PS; dest[ptr++] = v & 0xff; } break; case PUNCTUATION: dest[ptr++] = PAL; mode = ALPHA; --k; break; } } if ((ptr & 1) != 0) dest[ptr++] = PS; size = (ptr + fullBytes) / 2; if (size + cwPtr > MAX_DATA_CODEWORDS) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } length = ptr; ptr = 0; while (ptr < length) { v = dest[ptr++]; if (v >= 30) { codewords[cwPtr++] = v; codewords[cwPtr++] = dest[ptr++]; } else codewords[cwPtr++] = v * 30 + dest[ptr++]; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
private void numberCompaction(byte[] input, int start, int length) { int full = length / 44 * 15; int size = length % 44; int k; if (size == 0) size = full; else size = full + size / 3 + 1; if (size + cwPtr > MAX_DATA_CODEWORDS) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } length += start; for (k = start; k < length; k += 44) { size = length - k < 44 ? length - k : 44; basicNumberCompaction(input, k, size); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
void byteCompaction(int start, int length) { int k, j; int size = length / 6 * 5 + length % 6; if (size + cwPtr > MAX_DATA_CODEWORDS) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } length += start; for (k = start; k < length; k += 6) { size = length - k < 44 ? length - k : 6; if (size < 6) { for (j = 0; j < size; ++j) codewords[cwPtr++] = text[k + j] & 0xff; } else { byteCompaction6(k); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
public void paintCode() { int maxErr, lenErr, tot, pad; if ((options & PDF417_USE_RAW_CODEWORDS) != 0) { if (lenCodewords > MAX_DATA_CODEWORDS || lenCodewords < 1 || lenCodewords != codewords[0]) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.codeword.size")); } } else { if (text == null) throw new NullPointerException(MessageLocalization.getComposedMessage("text.cannot.be.null")); if (text.length > ABSOLUTE_MAX_TEXT_SIZE) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } segmentList = new SegmentList(); breakString(); //dumpList(); assemble(); segmentList = null; codewords[0] = lenCodewords = cwPtr; } maxErr = maxPossibleErrorLevel(MAX_DATA_CODEWORDS + 2 - lenCodewords); if ((options & PDF417_USE_ERROR_LEVEL) == 0) { if (lenCodewords < 41) errorLevel = 2; else if (lenCodewords < 161) errorLevel = 3; else if (lenCodewords < 321) errorLevel = 4; else errorLevel = 5; } if (errorLevel < 0) errorLevel = 0; else if (errorLevel > maxErr) errorLevel = maxErr; if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) codeRows = 90; lenErr = 2 << errorLevel; boolean fixedColumn = (options & PDF417_FIXED_ROWS) == 0; boolean skipRowColAdjust = false; tot = lenCodewords + lenErr; if ((options & PDF417_FIXED_RECTANGLE) != 0) { tot = codeColumns * codeRows; if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } if (tot < lenCodewords + lenErr) tot = lenCodewords + lenErr; else skipRowColAdjust = true; } else if ((options & (PDF417_FIXED_COLUMNS | PDF417_FIXED_ROWS)) == 0) { double c, b; fixedColumn = true; if (aspectRatio < 0.001) aspectRatio = 0.001f; else if (aspectRatio > 1000) aspectRatio = 1000; b = 73 * aspectRatio - 4; c = (-b + Math.sqrt(b * b + 4 * 17 * aspectRatio * (lenCodewords + lenErr) * yHeight)) / (2 * 17 * aspectRatio); codeColumns = (int)(c + 0.5); if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; } if (!skipRowColAdjust) { if (fixedColumn) { codeRows = (tot - 1) / codeColumns + 1; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) { codeRows = 90; codeColumns = (tot - 1) / 90 + 1; } } else { codeColumns = (tot - 1) / codeRows + 1; if (codeColumns > 30) { codeColumns = 30; codeRows = (tot - 1) / 30 + 1; } } tot = codeRows * codeColumns; } if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } errorLevel = maxPossibleErrorLevel(tot - lenCodewords); lenErr = 2 << errorLevel; pad = tot - lenErr - lenCodewords; if ((options & PDF417_USE_MACRO) != 0) { // the padding comes before the control block System.arraycopy(codewords, macroIndex, codewords, macroIndex + pad, pad); cwPtr = lenCodewords + pad; while (pad-- != 0) codewords[macroIndex++] = TEXT_MODE; } else { cwPtr = lenCodewords; while (pad-- != 0) codewords[cwPtr++] = TEXT_MODE; } codewords[0] = lenCodewords = cwPtr; calculateErrorCorrection(lenCodewords); lenCodewords = tot; outPaintCode(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ByteBuffer.java
public void setSize(int size) { if (size > count || size < 0) throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.new.size.must.be.positive.and.lt.eq.of.the.current.size")); count = size; }
0 0
(Domain) BadPasswordException 6
              
// 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/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/PdfEncryption.java
public boolean readKey(PdfDictionary enc, byte[] password) throws BadPasswordException { try { if (password == null) password = new byte[0]; byte[] oValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.O).toString()); byte[] uValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.U).toString()); byte[] oeValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.OE).toString()); byte[] ueValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.UE).toString()); byte[] perms = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.PERMS).toString()); boolean isUserPass = false; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); byte[] hash = md.digest(); boolean isOwnerPass = compareArray(hash, oValue, 32); if (isOwnerPass) { md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, KEY_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(oeValue, 0, oeValue.length); } else { md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); isUserPass = compareArray(hash, uValue, 32); if (!isUserPass) throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, KEY_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(ueValue, 0, ueValue.length); } AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, key); byte[] decPerms = ac.processBlock(perms, 0, perms.length); if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b') throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); permissions = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8) | ((decPerms[2] & 0xff) << 16) | ((decPerms[2] & 0xff) << 24); encryptMetadata = decPerms[8] == (byte)'T'; return isOwnerPass; } catch (BadPasswordException ex) { throw ex; } catch (Exception ex) { throw new ExceptionConverter(ex); } }
1
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
1
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public boolean readKey(PdfDictionary enc, byte[] password) throws BadPasswordException { try { if (password == null) password = new byte[0]; byte[] oValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.O).toString()); byte[] uValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.U).toString()); byte[] oeValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.OE).toString()); byte[] ueValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.UE).toString()); byte[] perms = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.PERMS).toString()); boolean isUserPass = false; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); byte[] hash = md.digest(); boolean isOwnerPass = compareArray(hash, oValue, 32); if (isOwnerPass) { md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, KEY_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(oeValue, 0, oeValue.length); } else { md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); isUserPass = compareArray(hash, uValue, 32); if (!isUserPass) throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, KEY_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(ueValue, 0, ueValue.length); } AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, key); byte[] decPerms = ac.processBlock(perms, 0, perms.length); if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b') throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); permissions = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8) | ((decPerms[2] & 0xff) << 16) | ((decPerms[2] & 0xff) << 24); encryptMetadata = decPerms[8] == (byte)'T'; return isOwnerPass; } catch (BadPasswordException ex) { throw ex; } catch (Exception ex) { throw new ExceptionConverter(ex); } }
(Domain) VerificationException 6
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
protected PdfPKCS7 coversWholeDocument() throws GeneralSecurityException { PdfPKCS7 pkcs7 = fields.verifySignature(signatureName); if (fields.signatureCoversWholeDocument(signatureName)) { LOGGER.info("The timestamp covers whole document."); } else { throw new VerificationException(null, "Signature doesn't cover whole document."); } if (pkcs7.verify()) { LOGGER.info("The signed document has not been modified."); return pkcs7; } else { throw new VerificationException(null, "The document was altered after the final signature was applied."); } }
// 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/CRLVerifier.java
public boolean verify(X509CRL crl, X509Certificate signCert, X509Certificate issuerCert, Date signDate) throws GeneralSecurityException { if (crl == null || signDate == null) return false; // We only check CRLs valid on the signing date for which the issuer matches if (crl.getIssuerX500Principal().equals(signCert.getIssuerX500Principal()) && signDate.after(crl.getThisUpdate()) && signDate.before(crl.getNextUpdate())) { // the signing certificate may not be revoked if (isSignatureValid(crl, issuerCert) && crl.isRevoked(signCert)) { throw new VerificationException(signCert, "The certificate has been revoked."); } 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"); }
2
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch(GeneralSecurityException e) { throw new VerificationException(signCert, "Couldn't verify with CRL or OCSP or trusted anchor"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch(GeneralSecurityException e) { if (super.verify(responderCert, issuerCert, null).size() == 0) throw new VerificationException(responderCert, "Responder certificate couldn't be verified"); }
0
(Lib) NoSuchAlgorithmException 4
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/BouncyCastleDigest.java
public MessageDigest getMessageDigest(String hashAlgorithm) throws GeneralSecurityException { String oid = DigestAlgorithms.getAllowedDigests(hashAlgorithm); if (oid == null) throw new NoSuchAlgorithmException(hashAlgorithm); if (oid.equals("1.2.840.113549.2.2")) { //MD2 return new MD2.Digest(); } else if (oid.equals("1.2.840.113549.2.5")) { //MD5 return new MD5.Digest(); } else if (oid.equals("1.3.14.3.2.26")) { //SHA1 return new SHA1.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.4")) { //SHA224 return new SHA224.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.1")) { //SHA256 return new SHA256.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.2")) { //SHA384 return new SHA384.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.3")) { //SHA512 return new SHA512.Digest(); } else if (oid.equals("1.3.36.3.2.2")) { //RIPEMD128 return new RIPEMD128.Digest(); } else if (oid.equals("1.3.36.3.2.1")) { //RIPEMD160 return new RIPEMD160.Digest(); } else if (oid.equals("1.3.36.3.2.3")) { //RIPEMD256 return new RIPEMD256.Digest(); } else if (oid.equals("1.2.643.2.2.9")) { //GOST3411 return new GOST3411.Digest(); } throw new NoSuchAlgorithmException(hashAlgorithm); //shouldn't get here }
0 5
              
// 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
private static byte[] hashBytesSha1(byte[] b) throws NoSuchAlgorithmException { MessageDigest sh = MessageDigest.getInstance("SHA1"); return sh.digest(b); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/DigestAlgorithms.java
public static MessageDigest getMessageDigestFromOid(String digestOid, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { return getMessageDigest(getDigest(digestOid), provider); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/DigestAlgorithms.java
public static MessageDigest getMessageDigest(String hashAlgorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { if (provider == null || provider.startsWith("SunPKCS11") || provider.startsWith("SunMSCAPI")) return MessageDigest.getInstance(DigestAlgorithms.normalizeDigestName(hashAlgorithm)); else return MessageDigest.getInstance(hashAlgorithm, provider); }
(Domain) PdfException 4
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectReference add(final PdfPage page, final PdfContents contents) throws PdfException { if (!open) { throw new PdfException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfIndirectObject object; try { object = addToBody(contents); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } page.add(object.getIndirectReference()); // [U5] if (group != null) { page.put(PdfName.GROUP, group); group = null; } else if (rgbTransparencyBlending) { PdfDictionary pp = new PdfDictionary(); pp.put(PdfName.TYPE, PdfName.GROUP); pp.put(PdfName.S, PdfName.TRANSPARENCY); pp.put(PdfName.CS, PdfName.DEVICERGB); page.put(PdfName.GROUP, pp); } root.addPage(page); currentPageNumber++; return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void setPageAction(PdfName actionType, PdfAction action, int page) throws PdfException { if (!actionType.equals(PAGE_OPEN) && !actionType.equals(PAGE_CLOSE)) throw new PdfException(MessageLocalization.getComposedMessage("invalid.page.additional.action.type.1", actionType.toString())); PdfDictionary pg = reader.getPageN(page); PdfDictionary aa = (PdfDictionary)PdfReader.getPdfObject(pg.get(PdfName.AA), pg); if (aa == null) { aa = new PdfDictionary(); pg.put(PdfName.AA, aa); markUsed(pg); } aa.put(actionType, action); markUsed(aa); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setAdditionalAction(PdfName actionType, PdfAction action) throws PdfException { if (!(actionType.equals(DOCUMENT_CLOSE) || actionType.equals(WILL_SAVE) || actionType.equals(DID_SAVE) || actionType.equals(WILL_PRINT) || actionType.equals(DID_PRINT))) { throw new PdfException(MessageLocalization.getComposedMessage("invalid.additional.action.type.1", actionType.toString())); } PdfDictionary aa = reader.getCatalog().getAsDict(PdfName.AA); if (aa == null) { if (action == null) return; aa = new PdfDictionary(); reader.getCatalog().put(PdfName.AA, aa); } markUsed(aa); if (action == null) aa.remove(actionType); else aa.put(actionType, action); }
0 14
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectReference add(final PdfPage page, final PdfContents contents) throws PdfException { if (!open) { throw new PdfException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfIndirectObject object; try { object = addToBody(contents); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } page.add(object.getIndirectReference()); // [U5] if (group != null) { page.put(PdfName.GROUP, group); group = null; } else if (rgbTransparencyBlending) { PdfDictionary pp = new PdfDictionary(); pp.put(PdfName.TYPE, PdfName.GROUP); pp.put(PdfName.S, PdfName.TRANSPARENCY); pp.put(PdfName.CS, PdfName.DEVICERGB); page.put(PdfName.GROUP, pp); } root.addPage(page); currentPageNumber++; return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setThumbnail(final Image image) throws PdfException, DocumentException { pdf.setThumbnail(image); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfName addDirectImageSimple(final Image image) throws PdfException, DocumentException { return addDirectImageSimple(image, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfName addDirectImageSimple(final Image image, final PdfIndirectReference fixedRef) throws PdfException, DocumentException { PdfName name; // if the images is already added, just retrieve the name if (images.containsKey(image.getMySerialId())) { name = images.get(image.getMySerialId()); } // if it's a new image, add it to the document else { if (image.isImgTemplate()) { name = new PdfName("img" + images.size()); if(image instanceof ImgWMF){ try { ImgWMF wmf = (ImgWMF)image; wmf.readWMF(PdfTemplate.createTemplate(this, 0, 0)); } catch (Exception e) { throw new DocumentException(e); } } } else { PdfIndirectReference dref = image.getDirectReference(); if (dref != null) { PdfName rname = new PdfName("img" + images.size()); images.put(image.getMySerialId(), rname); imageDictionary.put(rname, dref); return rname; } Image maskImage = image.getImageMask(); PdfIndirectReference maskRef = null; if (maskImage != null) { PdfName mname = images.get(maskImage.getMySerialId()); maskRef = getImageReference(mname); } PdfImage i = new PdfImage(image, "img" + images.size(), maskRef); if (image instanceof ImgJBIG2) { byte[] globals = ((ImgJBIG2) image).getGlobalBytes(); if (globals != null) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.put(PdfName.JBIG2GLOBALS, getReferenceJBIG2Globals(globals)); i.put(PdfName.DECODEPARMS, decodeparms); } } if (image.hasICCProfile()) { PdfICCBased icc = new PdfICCBased(image.getICCProfile(), image.getCompressionLevel()); PdfIndirectReference iccRef = add(icc); PdfArray iccArray = new PdfArray(); iccArray.add(PdfName.ICCBASED); iccArray.add(iccRef); PdfArray colorspace = i.getAsArray(PdfName.COLORSPACE); if (colorspace != null) { if (colorspace.size() > 1 && PdfName.INDEXED.equals(colorspace.getPdfObject(0))) colorspace.set(1, iccArray); else i.put(PdfName.COLORSPACE, iccArray); } else i.put(PdfName.COLORSPACE, iccArray); } add(i, fixedRef); name = i.name(); } images.put(image.getMySerialId(), name); } return name; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectReference add(final PdfImage pdfImage, PdfIndirectReference fixedRef) throws PdfException { if (! imageDictionary.contains(pdfImage.name())) { PdfWriter.checkPdfIsoConformance(this, PdfIsoKeys.PDFISOKEY_IMAGE, pdfImage); if (fixedRef instanceof PRIndirectReference) { PRIndirectReference r2 = (PRIndirectReference)fixedRef; fixedRef = new PdfIndirectReference(0, getNewObjectNumber(r2.getReader(), r2.getNumber(), r2.getGeneration())); } try { if (fixedRef == null) fixedRef = addToBody(pdfImage).getIndirectReference(); else addToBody(pdfImage, fixedRef); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } imageDictionary.put(pdfImage.name(), fixedRef); return fixedRef; } return (PdfIndirectReference) imageDictionary.get(pdfImage.name()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setPageAction(PdfName actionType, PdfAction action) throws PdfException { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.setpageaction.pdfname.actiontype.pdfaction.action.int.page")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void setPageAction(PdfName actionType, PdfAction action, int page) throws PdfException { if (!actionType.equals(PAGE_OPEN) && !actionType.equals(PAGE_CLOSE)) throw new PdfException(MessageLocalization.getComposedMessage("invalid.page.additional.action.type.1", actionType.toString())); PdfDictionary pg = reader.getPageN(page); PdfDictionary aa = (PdfDictionary)PdfReader.getPdfObject(pg.get(PdfName.AA), pg); if (aa == null) { aa = new PdfDictionary(); pg.put(PdfName.AA, aa); markUsed(pg); } aa.put(actionType, action); markUsed(aa); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setAdditionalAction(PdfName actionType, PdfAction action) throws PdfException { if (!(actionType.equals(DOCUMENT_CLOSE) || actionType.equals(WILL_SAVE) || actionType.equals(DID_SAVE) || actionType.equals(WILL_PRINT) || actionType.equals(DID_PRINT))) { throw new PdfException(MessageLocalization.getComposedMessage("invalid.additional.action.type.1", actionType.toString())); } PdfDictionary aa = reader.getCatalog().getAsDict(PdfName.AA); if (aa == null) { if (action == null) return; aa = new PdfDictionary(); reader.getCatalog().put(PdfName.AA, aa); } markUsed(aa); if (action == null) aa.remove(actionType); else aa.put(actionType, action); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void setThumbnail(Image image, int page) throws PdfException, DocumentException { PdfIndirectReference thumb = getImageReference(addDirectImageSimple(image)); reader.resetReleasePage(); PdfDictionary dic = reader.getPageN(page); dic.put(PdfName.THUMB, thumb); reader.resetReleasePage(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void setThumbnail(final Image image) throws PdfException, DocumentException { writer.addPageDictEntry(PdfName.THUMB, writer.getImageReference(writer.addDirectImageSimple(image))); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void add(final Image image) throws PdfException, DocumentException { if (image.hasAbsoluteY()) { graphics.addImage(image); pageEmpty = false; return; } // if there isn't enough room for the image on this page, save it for the next page if (currentHeight != 0 && indentTop() - currentHeight - image.getScaledHeight() < indentBottom()) { if (!strictImageSequence && imageWait == null) { imageWait = image; return; } newPage(); if (currentHeight != 0 && indentTop() - currentHeight - image.getScaledHeight() < indentBottom()) { imageWait = image; return; } } pageEmpty = false; // avoid endless loops if (image == imageWait) imageWait = null; boolean textwrap = (image.getAlignment() & Image.TEXTWRAP) == Image.TEXTWRAP && !((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE); boolean underlying = (image.getAlignment() & Image.UNDERLYING) == Image.UNDERLYING; float diff = leading / 2; if (textwrap) { diff += leading; } float lowerleft = indentTop() - currentHeight - image.getScaledHeight() -diff; float mt[] = image.matrix(); float startPosition = indentLeft() - mt[4]; if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) startPosition = indentRight() - image.getScaledWidth() - mt[4]; if ((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE) startPosition = indentLeft() + (indentRight() - indentLeft() - image.getScaledWidth()) / 2 - mt[4]; if (image.hasAbsoluteX()) startPosition = image.getAbsoluteX(); if (textwrap) { if (imageEnd < 0 || imageEnd < currentHeight + image.getScaledHeight() + diff) { imageEnd = currentHeight + image.getScaledHeight() + diff; } if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) { // indentation suggested by Pelikan Stephan indentation.imageIndentRight += image.getScaledWidth() + image.getIndentationLeft(); } else { // indentation suggested by Pelikan Stephan indentation.imageIndentLeft += image.getScaledWidth() + image.getIndentationRight(); } } else { if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) startPosition -= image.getIndentationRight(); else if ((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE) startPosition += image.getIndentationLeft() - image.getIndentationRight(); else startPosition += image.getIndentationLeft(); } graphics.addImage(image, mt[0], mt[1], mt[2], mt[3], startPosition, lowerleft - mt[5]); if (!(textwrap || underlying)) { currentHeight += image.getScaledHeight() + diff; flushLines(); text.moveText(0, - (image.getScaledHeight() + diff)); newLine(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
Override PdfIndirectReference add(PdfPage page, PdfContents contents) throws PdfException { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setThumbnail(final Image image, final int page) throws PdfException, DocumentException { stamper.setThumbnail(image, page); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setPageAction(final PdfName actionType, final PdfAction action, final int page) throws PdfException { stamper.setPageAction(actionType, action, page); }
(Domain) FontReadingException 3
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
public Language getSupportedLanguage() throws FontReadingException { Language[] allLangs = Language.values(); for (String supportedLang : supportedLanguages) { for (Language lang : allLangs) { if (lang.isSupported(supportedLang)) { return lang; } } } throw new FontReadingException("Unsupported languages " + supportedLanguages); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
protected final void startReadingTable() throws FontReadingException { try { TableHeader header = readHeader(); // read the Script tables readScriptListTable(tableLocation + header.scriptListOffset); // read Feature table readFeatureListTable(tableLocation + header.featureListOffset); // read LookUpList table readLookupListTable(tableLocation + header.lookupListOffset); } catch (IOException e) { throw new FontReadingException("Error reading font file", e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
private String getTextFromGlyph(int glyphId, Map<Integer, Character> glyphToCharacterMap) throws FontReadingException { StringBuilder chars = new StringBuilder(1); Character c = glyphToCharacterMap.get(glyphId); if (c == null) { // it means this represents a compound glyph List<Integer> constituentGlyphs = rawLigatureSubstitutionMap.get(glyphId); if (constituentGlyphs == null || constituentGlyphs.isEmpty()) { throw new FontReadingException("No corresponding character or simple glyphs found for GlyphID=" + glyphId); } for (int constituentGlyphId : constituentGlyphs) { chars.append(getTextFromGlyph(constituentGlyphId, glyphToCharacterMap)); } } else { chars.append(c.charValue()); } return chars.toString(); }
1
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
catch (IOException e) { throw new FontReadingException("Error reading font file", e); }
6
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
public Language getSupportedLanguage() throws FontReadingException { Language[] allLangs = Language.values(); for (String supportedLang : supportedLanguages) { for (Language lang : allLangs) { if (lang.isSupported(supportedLang)) { return lang; } } } throw new FontReadingException("Unsupported languages " + supportedLanguages); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
protected final void startReadingTable() throws FontReadingException { try { TableHeader header = readHeader(); // read the Script tables readScriptListTable(tableLocation + header.scriptListOffset); // read Feature table readFeatureListTable(tableLocation + header.featureListOffset); // read LookUpList table readLookupListTable(tableLocation + header.lookupListOffset); } catch (IOException e) { throw new FontReadingException("Error reading font file", e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
public void read() throws FontReadingException { rawLigatureSubstitutionMap = new LinkedHashMap<Integer, List<Integer>>(); startReadingTable(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
public Map<String, Glyph> getGlyphSubstitutionMap() throws FontReadingException { Map<String, Glyph> glyphSubstitutionMap = new LinkedHashMap<String, Glyph>(); for (Integer glyphIdToReplace : rawLigatureSubstitutionMap.keySet()) { List<Integer> constituentGlyphs = rawLigatureSubstitutionMap.get(glyphIdToReplace); StringBuilder chars = new StringBuilder(constituentGlyphs.size()); for (Integer constituentGlyphId : constituentGlyphs) { chars.append(getTextFromGlyph(constituentGlyphId, glyphToCharacterMap)); } Glyph glyph = new Glyph(glyphIdToReplace, glyphWidthsByIndex[glyphIdToReplace], chars.toString()); glyphSubstitutionMap.put(glyph.chars, glyph); } return Collections.unmodifiableMap(glyphSubstitutionMap); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
private String getTextFromGlyph(int glyphId, Map<Integer, Character> glyphToCharacterMap) throws FontReadingException { StringBuilder chars = new StringBuilder(1); Character c = glyphToCharacterMap.get(glyphId); if (c == null) { // it means this represents a compound glyph List<Integer> constituentGlyphs = rawLigatureSubstitutionMap.get(glyphId); if (constituentGlyphs == null || constituentGlyphs.isEmpty()) { throw new FontReadingException("No corresponding character or simple glyphs found for GlyphID=" + glyphId); } for (int constituentGlyphId : constituentGlyphs) { chars.append(getTextFromGlyph(constituentGlyphId, glyphToCharacterMap)); } } else { chars.append(c.charValue()); } return chars.toString(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphPositioningTableReader.java
public void read() throws FontReadingException { startReadingTable(); }
(Lib) GeneralSecurityException 3
              
// 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/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<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; }
2
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvTimestamp.java
catch(Exception e) { throw new GeneralSecurityException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch (OCSPException e) { throw new GeneralSecurityException(e); }
34
              
// 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/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/PrivateKeySignature.java
public byte[] sign(byte[] b) throws GeneralSecurityException { String signMode = hashAlgorithm + "with" + encryptionAlgorithm; Signature sig; if (provider == null) sig = Signature.getInstance(signMode); else sig = Signature.getInstance(signMode, provider); sig.initSign(pk); sig.update(b); return sig.sign(); }
// 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 MessageDigest getMessageDigest() throws GeneralSecurityException { return new BouncyCastleDigest().getMessageDigest(digestAlgorithm); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/ExternalBlankSignatureContainer.java
public byte[] sign(InputStream data) throws GeneralSecurityException { return new byte[0]; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
protected PdfPKCS7 coversWholeDocument() throws GeneralSecurityException { PdfPKCS7 pkcs7 = fields.verifySignature(signatureName); if (fields.signatureCoversWholeDocument(signatureName)) { LOGGER.info("The timestamp covers whole document."); } else { throw new VerificationException(null, "Signature doesn't cover whole document."); } if (pkcs7.verify()) { LOGGER.info("The signed document has not been modified."); return pkcs7; } else { throw new VerificationException(null, "The document was altered after the final signature was applied."); } }
// 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 void verifyChain(Certificate[] chain) throws GeneralSecurityException { // Loop over the certificates in the chain for (int i = 0; i < chain.length; i++) { X509Certificate cert = (X509Certificate) chain[i]; // check if the certificate was/is valid cert.checkValidity(signDate); // check if the previous certificate was issued by this certificate if (i > 0) chain[i-1].verify(chain[i].getPublicKey()); } LOGGER.info("All certificates are valid on " + signDate.toString()); }
// 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/CRLVerifier.java
public boolean verify(X509CRL crl, X509Certificate signCert, X509Certificate issuerCert, Date signDate) throws GeneralSecurityException { if (crl == null || signDate == null) return false; // We only check CRLs valid on the signing date for which the issuer matches if (crl.getIssuerX500Principal().equals(signCert.getIssuerX500Principal()) && signDate.after(crl.getThisUpdate()) && signDate.before(crl.getNextUpdate())) { // the signing certificate may not be revoked if (isSignatureValid(crl, issuerCert) && crl.isRevoked(signCert)) { throw new VerificationException(signCert, "The certificate has been revoked."); } return true; } return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
public boolean verifyTimestampImprint() throws GeneralSecurityException { if (timeStampToken == null) return false; TimeStampTokenInfo info = timeStampToken.getTimeStampInfo(); MessageImprint imprint = info.toASN1Structure().getMessageImprint(); String algOID = info.getMessageImprintAlgOID().getId(); byte[] md = new BouncyCastleDigest().getMessageDigest(DigestAlgorithms.getDigest(algOID)).digest(digest); byte[] imphashed = imprint.getHashedMessage(); boolean res = Arrays.equals(md, imphashed); return res; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/BouncyCastleDigest.java
public MessageDigest getMessageDigest(String hashAlgorithm) throws GeneralSecurityException { String oid = DigestAlgorithms.getAllowedDigests(hashAlgorithm); if (oid == null) throw new NoSuchAlgorithmException(hashAlgorithm); if (oid.equals("1.2.840.113549.2.2")) { //MD2 return new MD2.Digest(); } else if (oid.equals("1.2.840.113549.2.5")) { //MD5 return new MD5.Digest(); } else if (oid.equals("1.3.14.3.2.26")) { //SHA1 return new SHA1.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.4")) { //SHA224 return new SHA224.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.1")) { //SHA256 return new SHA256.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.2")) { //SHA384 return new SHA384.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.3")) { //SHA512 return new SHA512.Digest(); } else if (oid.equals("1.3.36.3.2.2")) { //RIPEMD128 return new RIPEMD128.Digest(); } else if (oid.equals("1.3.36.3.2.1")) { //RIPEMD160 return new RIPEMD160.Digest(); } else if (oid.equals("1.3.36.3.2.3")) { //RIPEMD256 return new RIPEMD256.Digest(); } else if (oid.equals("1.2.643.2.2.9")) { //GOST3411 return new GOST3411.Digest(); } throw new NoSuchAlgorithmException(hashAlgorithm); //shouldn't get here }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/ProviderDigest.java
public MessageDigest getMessageDigest(String hashAlgorithm) throws GeneralSecurityException{ return DigestAlgorithms.getMessageDigest(hashAlgorithm, provider); }
// 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/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(); }
(Domain) InlineImageParseException 3
              
// 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"); }
0 0
(Domain) NoninvertibleTransformException 3
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public AffineTransform createInverse() throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } return new AffineTransform( m11 / det, // m00 -m10 / det, // m10 -m01 / det, // m01 m00 / det, // m11 (m01 * m12 - m11 * m02) / det, // m02 (m10 * m02 - m00 * m12) / det // m12 ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public Point2D inverseTransform(Point2D src, Point2D dst) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } if (dst == null) { if (src instanceof Point2D.Double) { dst = new Point2D.Double(); } else { dst = new Point2D.Float(); } } double x = src.getX() - m02; double y = src.getY() - m12; dst.setLocation((x * m11 - y * m01) / det, (y * m00 - x * m10) / det); return dst; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public void inverseTransform(double[] src, int srcOff, double[] dst, int dstOff, int length) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } while (--length >= 0) { double x = src[srcOff++] - m02; double y = src[srcOff++] - m12; dst[dstOff++] = (x * m11 - y * m01) / det; dst[dstOff++] = (y * m00 - x * m10) / det; } }
0 3
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public AffineTransform createInverse() throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } return new AffineTransform( m11 / det, // m00 -m10 / det, // m10 -m01 / det, // m01 m00 / det, // m11 (m01 * m12 - m11 * m02) / det, // m02 (m10 * m02 - m00 * m12) / det // m12 ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public Point2D inverseTransform(Point2D src, Point2D dst) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } if (dst == null) { if (src instanceof Point2D.Double) { dst = new Point2D.Double(); } else { dst = new Point2D.Float(); } } double x = src.getX() - m02; double y = src.getY() - m12; dst.setLocation((x * m11 - y * m01) / det, (y * m00 - x * m10) / det); return dst; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public void inverseTransform(double[] src, int srcOff, double[] dst, int dstOff, int length) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } while (--length >= 0) { double x = src[srcOff++] - m02; double y = src[srcOff++] - m12; dst[dstOff++] = (x * m11 - y * m01) / det; dst[dstOff++] = (y * m00 - x * m10) / det; } }
(Lib) EmptyStackException 2
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public T peek() { if (size() == 0) throw new EmptyStackException(); return get(size() - 1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public T pop() { if (size() == 0) throw new EmptyStackException(); T ret = get(size() - 1); remove(size() - 1); return ret; }
0 0
(Lib) Error 2
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
private String decodeSingleCID(byte[] bytes, int offset, int len){ if (toUnicodeCmap != null){ if (offset + len > bytes.length) throw new ArrayIndexOutOfBoundsException(MessageLocalization.getComposedMessage("invalid.index.1", offset + len)); String s = toUnicodeCmap.lookup(bytes, offset, len); if (s != null) return s; if (len != 1 || cidbyte2uni == null) return null; } if (len == 1){ if (cidbyte2uni == null) return ""; else return new String(cidbyte2uni, 0xff & bytes[offset], 1); } throw new Error("Multi-byte glyphs not implemented yet"); }
// 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; } }
0 0
(Lib) Exception 2
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Version.java
public static Version getInstance() { if (version == null) { version = new Version(); try { Class<?> klass = Class.forName("com.itextpdf.license.LicenseKey"); Method m = klass.getMethod("getLicenseeInfo"); String[] info = (String[])m.invoke(klass.newInstance()); if (info[3] != null && info[3].trim().length() > 0) { version.key = info[3]; } else { version.key = "Trial version "; if (info[5] == null) { version.key += "unauthorised"; } else { version.key += info[5]; } } if (info[4] != null && info[4].trim().length() > 0) { version.iTextVersion = info[4]; } else if (info[2] != null && info[2].trim().length() > 0) { version.iTextVersion += " (" + info[2]; if (!version.key.toLowerCase().startsWith("trial")) { version.iTextVersion += "; licensed version)"; } else { version.iTextVersion += "; " + version.key + ")"; } } // fall back to contact name, if company name is unavailable else if (info[0] != null && info[0].trim().length() > 0) { version.iTextVersion += " (" + info[0]; if (!version.key.toLowerCase().startsWith("trial")) { // we shouldn't have a licensed version without company name, // but let's account for it anyway version.iTextVersion += "; licensed version)"; } else { version.iTextVersion += "; " + version.key + ")"; } } else { throw new Exception(); } } catch (Exception e) { version.iTextVersion += " (AGPL-version)"; } } return version; }
0 4
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
private void invokeOperator(PdfLiteral operator, ArrayList<PdfObject> operands) throws Exception{ ContentOperator op = operators.get(operator.toString()); if (op == null) op = operators.get(DEFAULTOPERATOR); op.invoke(this, operator, operands); }
// 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 Exception { processor.beginMarkedContent((PdfName)operands.get(0), new PdfDictionary()); }
// 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 Exception { PdfObject properties = operands.get(1); processor.beginMarkedContent((PdfName)operands.get(0), getPropertiesDictionary(properties, processor.resources)); }
// 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 Exception { processor.endMarkedContent(); }
(Lib) ArithmeticException 1
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256.java
int inverse(int a) { if (a == 0) { throw new ArithmeticException(); } return expTable[255 - logTable[a]]; }
0 0
(Lib) ArrayIndexOutOfBoundsException 1
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
private String decodeSingleCID(byte[] bytes, int offset, int len){ if (toUnicodeCmap != null){ if (offset + len > bytes.length) throw new ArrayIndexOutOfBoundsException(MessageLocalization.getComposedMessage("invalid.index.1", offset + len)); String s = toUnicodeCmap.lookup(bytes, offset, len); if (s != null) return s; if (len != 1 || cidbyte2uni == null) return null; } if (len == 1){ if (cidbyte2uni == null) return ""; else return new String(cidbyte2uni, 0xff & bytes[offset], 1); } throw new Error("Multi-byte glyphs not implemented yet"); }
0 0
(Domain) IllegalPathStateException 1
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
void checkBuf(int pointCount, boolean checkMove) { if (checkMove && typeSize == 0) { // awt.20A=First segment should be SEG_MOVETO type throw new IllegalPathStateException(Messages.getString("awt.20A")); //$NON-NLS-1$ } if (typeSize == types.length) { byte tmp[] = new byte[typeSize + BUFFER_CAPACITY]; System.arraycopy(types, 0, tmp, 0, typeSize); types = tmp; } if (pointSize + pointCount > points.length) { float tmp[] = new float[pointSize + Math.max(BUFFER_CAPACITY * 2, pointCount)]; System.arraycopy(points, 0, tmp, 0, pointSize); points = tmp; } }
0 0
(Lib) MapFailedException 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); } }
1
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
catch (IOException e){ if (exceptionIsMapFailureException(e)) throw new MapFailedException(e); }
0
(Lib) NumberFormatException 1
              
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/factories/RomanAlphabetFactory.java
public static final String getString(int index) { if (index < 1) throw new NumberFormatException(MessageLocalization.getComposedMessage("you.can.t.translate.a.negative.number.into.an.alphabetical.value")); index--; int bytes = 1; int start = 0; int symbols = 26; while(index >= symbols + start) { bytes++; start += symbols; symbols *= 26; } int c = index - start; char[] value = new char[bytes]; while(bytes > 0) { value[--bytes] = (char)( 'a' + (c % 26)); c /= 26; } return new String(value); }
0 0
Explicit thrown (throw new...): 863/881
Explicit thrown ratio: 98%
Builder thrown ratio: 1%
Variable thrown ratio: 1%
Checked Runtime Total
Domain 203 201 404
Lib 57 323 380
Total 260 524

Caught Exceptions Summary

A (Domain) exception is defined in the application. A (Lib) exception is defined in the JDK or in a library. An exception can be caught, and it happens that the catch block contains a throw (e.g. for wrapping a low-level exception). Hovering over a number triggers showing code snippets from the application code.

Type Exception Caught
(directly)
Caught
with Thrown
(Lib) Exception 246
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/AsianFontMapper.java
catch (Exception e) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/DefaultFontMapper.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/DefaultFontMapper.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { throw new IllegalArgumentException(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { if (fill) cb.setColorFill(BaseColor.GRAY); else cb.setColorStroke(BaseColor.GRAY); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { if (fill) cb.setColorFill(BaseColor.GRAY); else cb.setColorStroke(BaseColor.GRAY); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Utilities.java
catch (Exception e) { return new File(filename).toURI().toURL(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/EntitiesToSymbol.java
catch(Exception exception) { return new Chunk(e, font); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/ByteBufferRandomAccessSource.java
catch (Exception e) { // This really is a show stopper on windows //e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ImgJBIG2.java
catch (Exception e) { //ignore }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Version.java
catch (Exception e) { version.iTextVersion += " (AGPL-version)"; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/error_messages/MessageLocalization.java
catch (Exception ex) { // do nothing }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/error_messages/MessageLocalization.java
catch (Exception exx) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e){ System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); return -1; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e) {}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e) {}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception ex ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception ex ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (Exception eofe) { throw new RuntimeException("No reference line present."); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (Exception eofe) { ++fails; break; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (Exception eofe) { return; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
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/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { // do nothing }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception ex) { if (--maxExc < 0) break; continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { cmapRet = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
catch (Exception e) { //empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEAN.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FdfReader.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FdfReader.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/SimplePatternParser.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/Hyphenator.java
catch (Exception e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/Hyphenator.java
catch (Exception e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { ret[k] = ""; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { // empty }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfICCBased.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
catch (Exception ioe) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAcroForm.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAction.java
catch (Exception e) { js.put(PdfName.JS, new PdfString(code)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new RuntimeException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/crypto/AESCipher.java
catch (Exception ex) { return outp; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
catch (Exception e) {}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPattern.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfName.java
catch (Exception e) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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
catch(Exception ee){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
catch(Exception ee){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
catch(Exception ee){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
catch(Exception ee){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/events/FieldPositioningEvents.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/GlyphList.java
catch (Exception e) { System.err.println("glyphlist.txt loading error: " + e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/GlyphList.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/GlyphList.java
catch (Exception ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { acroForm = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne){ throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()), ne); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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
catch(Exception ee){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { obj = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { obj = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) {}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { tokens.seek(pos); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { return fout.toByteArray(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { if (strict) return null; return out.toByteArray(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFontSubset.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDate.java
catch (Exception e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception ee) { throw new DocumentException(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw ExceptionConverter.convertException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (Exception exc) { return; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFileSpecification.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReaderInstance.java
catch (Exception e) { //Empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentReaderTool.java
catch (Exception e){ e.printStackTrace(System.err); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontUnicode.java
catch (Exception e) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch(Exception x){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContents.java
catch (Exception e) { throw new BadPdfFormatException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeCodabar.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapParserEx.java
catch (Exception ex) { if (--maxExc < 0) break; continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapParserEx.java
catch (Exception ex) {}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RadioCheckField.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new DocumentException(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFont.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeInter25.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
catch (Exception e) { //empty }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
catch (Exception ee) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOffline.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { return e.getMessage(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvTimestamp.java
catch(Exception e) { throw new GeneralSecurityException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception ex) { // ignore }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
catch(Exception ex){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerification.java
catch (Exception e) { // do nothing }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (Exception e) { LOGGER.info("Skipped CRL url: " + e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (Exception e) { LOGGER.info("Skipped CRL: " + e.getMessage() + " for " + urlt); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (Exception e) { // This really is a show stopper on windows //e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Font.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch (Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch(Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { // default leading paragraph.setLeading(0, 1.5f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { list.setAutoindent(true); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/TableWrapper.java
catch (Exception e) { // fail silently }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Jpeg2000.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch (Exception e) { //empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch (Exception e) { //empty on purpose }
107
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/DefaultFontMapper.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { throw new IllegalArgumentException(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (Exception eofe) { throw new RuntimeException("No reference line present."); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEAN.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfICCBased.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAcroForm.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new RuntimeException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPattern.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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/events/FieldPositioningEvents.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne){ throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()), ne); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception ee) { throw new DocumentException(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw ExceptionConverter.convertException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContents.java
catch (Exception e) { throw new BadPdfFormatException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeCodabar.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RadioCheckField.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new DocumentException(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFont.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeInter25.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOffline.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvTimestamp.java
catch(Exception e) { throw new GeneralSecurityException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Font.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch (Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch(Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (Exception e) { throw new ExceptionConverter(e); }
(Lib) IOException 78
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
catch(IOException ioe){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
catch(IOException ioe){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
catch(IOException ioe){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
catch (IOException e){ if (exceptionIsMapFailureException(e)) throw new MapFailedException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2SegmentReader.java
catch (IOException e) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { e.printStackTrace(); return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { e.printStackTrace(); return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { // Just return originally-decoded bytes }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { success = false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { success = false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { System.err.println( "Error decoding from file " + filename ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { System.err.println( "Error encoding from file " + filename ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException ex ) { ex.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException ex ) { ex.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { // Only a problem if we got no data at all. if( i == 0 ) throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
catch (IOException e) { EncodedRecipients = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/SimplePatternParser.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (IOException ioe) { ioe.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (IOException e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfLister.java
catch (IOException e) { System.err.println("I/O exception: " + e); // } catch (java.util.zip.DataFormatException e) { // System.err.println("Data Format Exception: " + e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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/PdfStamperImp.java
catch (IOException ioe) { ioe.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch(IOException e) { xmp = new PdfStream(altMetadata); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch (IOException ioe) { // do nothing }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LZWDecoder.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFunction.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfAnnotationsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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
catch (IOException e) { xref = null; throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (IOException ioe) { // Never happens }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (IOException ioe) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (IOException ioe) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (IOException e1) { throw new ExceptionConverter(e1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
catch (IOException e) { throw new FontReadingException("Error reading font file", e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
catch(IOException ioe) { throw new BadPdfFormatException(ioe.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPageLabels.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
catch (IOException e) { toUnicodeCmap = null; uni2cid = null; // technically, we should log this or provide some sort of feedback... but sometimes the cmap will be junk, but it's still possible to get text, so we don't want to throw an exception //throw new IllegalStateException("Unable to process ToUnicode map - " + e.getMessage(), e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateUtil.java
catch (IOException e) { obj = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateUtil.java
catch (IOException e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateUtil.java
catch (IOException e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/TSAClientBouncyCastle.java
catch (IOException ioe) { throw new IOException(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
catch(IOException e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (IOException e) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (IOException e){ close(); throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(IOException ioe) { // the font is registered as a true type font, but the path was wrong return new Font(FontFamily.UNDEFINED, size, style, color); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
48
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
catch (IOException e){ if (exceptionIsMapFailureException(e)) throw new MapFailedException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { // Only a problem if we got no data at all. if( i == 0 ) throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/SimplePatternParser.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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/PdfStamperImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LZWDecoder.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFunction.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfAnnotationsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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
catch (IOException e) { xref = null; throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (IOException e1) { throw new ExceptionConverter(e1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
catch (IOException e) { throw new FontReadingException("Error reading font file", e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
catch(IOException ioe) { throw new BadPdfFormatException(ioe.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPageLabels.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/TSAClientBouncyCastle.java
catch (IOException ioe) { throw new IOException(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (IOException e) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (IOException e){ close(); throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
(Domain) DocumentException 40
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Meta.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Chunk.java
catch (DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Rectangle.java
catch (DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/draw/VerticalPositionMark.java
catch (DocumentException e) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch (DocumentException de) { // do nothing }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPCell.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDiv.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
catch (DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/List.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Annotation.java
catch (DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/MarkedSection.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Anchor.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/MarkedObject.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(DocumentException de) { return false; }
25
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPCell.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
(Lib) UnsupportedEncodingException 14
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch (java.io.UnsupportedEncodingException uue) { return new String( outBuff, 0, e ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
catch (UnsupportedEncodingException e) { faceName = new String(name, 0, k); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
catch (UnsupportedEncodingException e) { s = new String(text, 0, k); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
catch (UnsupportedEncodingException e) { s = new String(text, 0, k); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
6
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
(Lib) GeneralSecurityException 11
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
catch (GeneralSecurityException e) { EncodedRecipients = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/RootStoreVerifier.java
catch (GeneralSecurityException e) { continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/RootStoreVerifier.java
catch (GeneralSecurityException e) { return super.verify(signCert, issuerCert, signDate); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch(GeneralSecurityException e) { throw new VerificationException(signCert, "Couldn't verify with CRL or OCSP or trusted anchor"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
catch(GeneralSecurityException e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
catch (GeneralSecurityException e) { LOGGER.warn("CRL not issued by the same authority as the certificate that is being checked"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
catch (GeneralSecurityException e) { continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
catch (GeneralSecurityException e) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch(GeneralSecurityException e) { if (super.verify(responderCert, issuerCert, null).size() == 0) throw new VerificationException(responderCert, "Responder certificate couldn't be verified"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch (GeneralSecurityException e) { continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch (GeneralSecurityException e) { return false; }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch(GeneralSecurityException e) { throw new VerificationException(signCert, "Couldn't verify with CRL or OCSP or trusted anchor"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch(GeneralSecurityException e) { if (super.verify(responderCert, issuerCert, null).size() == 0) throw new VerificationException(responderCert, "Responder certificate couldn't be verified"); }
(Lib) CloneNotSupportedException 10
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/RectangularShape.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Dimension2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Point2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/IntHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
10
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/RectangularShape.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Dimension2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Point2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/IntHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
(Lib) ClassCastException 8
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (ClassCastException ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
catch (ClassCastException ex) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.to.consolidate.the.named.destinations.of.your.reader")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFont.java
catch(ClassCastException cce) { return -2; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Font.java
catch (ClassCastException cce) { return -3; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(ClassCastException cce) { }
4
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
catch (ClassCastException ex) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.to.consolidate.the.named.destinations.of.your.reader")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
(Lib) RuntimeException 8
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (RuntimeException e) { //empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
catch (RuntimeException e) { icc_profile = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e) { // let's flip the fill bits and try again... tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS; try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e2) { throw e; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e2) { throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e) { //empty }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e) { //empty }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDestination.java
catch (RuntimeException e) { add(new PdfNull()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (RuntimeException e){ close(); throw e; }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e) { // let's flip the fill bits and try again... tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS; try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e2) { throw e; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e2) { throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (RuntimeException e){ close(); throw e; }
(Lib) NumberFormatException 5
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/EntitiesToUnicode.java
catch(NumberFormatException nfe) { return '\0'; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/EntitiesToUnicode.java
catch(NumberFormatException nfe) { return '\0'; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/XMLUtil.java
catch (NumberFormatException nfe) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfNumber.java
catch (NumberFormatException nfe){ throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.number.2", content, nfe.toString())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/HtmlUtilities.java
catch (NumberFormatException nfe) { sIndex = 0; }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfNumber.java
catch (NumberFormatException nfe){ throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.number.2", content, nfe.toString())); }
(Lib) ArrayIndexOutOfBoundsException 4
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (ArrayIndexOutOfBoundsException e) { //ignore }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFLZWDecoder.java
catch(ArrayIndexOutOfBoundsException e) { // Strip not terminated as expected: return EndOfInformation code. return 257; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
catch (ArrayIndexOutOfBoundsException ae) { // if the data type is unknown we should skip this TIFF Field processTag = false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LZWDecoder.java
catch(ArrayIndexOutOfBoundsException e) { // Strip not terminated as expected: return EndOfInformation code. return 257; }
0
(Lib) IllegalArgumentException 3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Jpeg.java
catch(IllegalArgumentException e) { // ignore ICC profile if it's invalid. }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Version.java
catch (IllegalArgumentException iae) { throw iae; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/HtmlUtilities.java
catch(IllegalArgumentException iae) { return null; }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Version.java
catch (IllegalArgumentException iae) { throw iae; }
(Lib) InterruptedException 3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (InterruptedException e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
(Lib) OCSPException 3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch (OCSPException e) { throw new GeneralSecurityException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch (OCSPException e) { continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch (OCSPException e) { return false; }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch (OCSPException e) { throw new GeneralSecurityException(e); }
(Lib) BufferUnderflowException 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/ByteBufferRandomAccessSource.java
catch (BufferUnderflowException e) { return -1; // EOF }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (BufferUnderflowException e) { return -1; // EOF }
0
(Lib) CertificateParsingException 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (CertificateParsingException e) { // DO NOTHING; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (CertificateParsingException e) { LOGGER.info("Skipped CRL url (certificate could not be parsed)"); }
0
(Lib) MalformedURLException 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (MalformedURLException e) { LOGGER.info("Skipped CRL url (malformed): " + url); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Anchor.java
catch(MalformedURLException mue) { return null; }
0
(Lib) MissingResourceException 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/misc/Messages.java
catch (MissingResourceException e) { return "Missing message: " + msg; //$NON-NLS-1$ }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/misc/Messages.java
catch (MissingResourceException e) { }
0
(Lib) ParserConfigurationException 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/xmp/XmpReader.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/xmp/XmpReader.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
(Lib) SAXException 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch(SAXException e) { xmp = new PdfStream(altMetadata); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (SAXException e) { throw new ExceptionConverter(e); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (SAXException e) { throw new ExceptionConverter(e); }
(Domain) BadElementException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (BadElementException be) { throw new ExceptionConverter(be); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (BadElementException be) { throw new ExceptionConverter(be); }
(Domain) BadPasswordException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (BadPasswordException ex) { throw ex; }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (BadPasswordException ex) { throw ex; }
(Lib) ClassNotFoundException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.lang.ClassNotFoundException e ) { e.printStackTrace(); }
0
(Lib) DataFormatException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch(DataFormatException dfe) { throw new ExceptionConverter(dfe); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch(DataFormatException dfe) { throw new ExceptionConverter(dfe); }
(Lib) EOFException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
catch(EOFException eof) { numDirectories--; break; }
0
(Lib) IndexOutOfBoundsException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfName.java
catch (IndexOutOfBoundsException e) { // empty on purpose }
0
(Lib) InvalidKeyException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
catch(InvalidKeyException e){ cipher.init(1,x509certificate.getPublicKey()); }
0
(Lib) MapFailedException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
catch (MapFailedException e){ return new RAFRandomAccessSource(raf); }
0
(Lib) NoSuchAlgorithmException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
catch (NoSuchAlgorithmException e) { seed = SecureRandom.getSeed(SEED_LENGTH); }
0
(Domain) NoninvertibleTransformException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (NoninvertibleTransformException e) { return null; }
0
(Lib) NullPointerException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(NullPointerException npe) { // null was entered as fontname and/or encoding return new Font(FontFamily.UNDEFINED, size, style, color); }
0
(Lib) OperatorCreationException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch (OperatorCreationException e) { return false; }
0
(Lib) Throwable 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Throwable e) {}
0
(Domain) WriterException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeQRCode.java
catch (WriterException ex) { throw new ExceptionConverter(ex); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeQRCode.java
catch (WriterException ex) { throw new ExceptionConverter(ex); }

Exception Recast Summary

There is a common practice of throwing exceptions from within a catch block (e.g. for wrapping a low-level exception). The following table summarizes the usage of this practice in the application. The last column gives the number of times it happens for a pair of exceptions. The graph below the table graphically renders the same information. For a given node, its color represents its origin (blue means library exception, orange means domain exception); the left-most number is the number of times it is thrown, the right-most is the number of times it is caught.

Catch Throw
(Lib) Exception
(Domain) ExceptionConverter
(Lib) IllegalArgumentException
(Lib) RuntimeException
(Domain) DocumentException
(Domain) InvalidPdfException
(Domain) BadPasswordException
(Domain) BadPdfFormatException
(Lib) GeneralSecurityException
Unknown
87
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/DefaultFontMapper.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEAN.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfICCBased.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAcroForm.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPattern.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/events/FieldPositioningEvents.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeCodabar.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RadioCheckField.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFont.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeInter25.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOffline.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Font.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (Exception e) { throw new ExceptionConverter(e); }
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { throw new IllegalArgumentException(ex); }
4
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (Exception eofe) { throw new RuntimeException("No reference line present."); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new RuntimeException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch (Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch(Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage())); }
7
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception ee) { throw new DocumentException(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new DocumentException(ex); }
4
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne){ throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()), ne); }
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContents.java
catch (Exception e) { throw new BadPdfFormatException(e.getMessage()); }
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvTimestamp.java
catch(Exception e) { throw new GeneralSecurityException(e); }
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw ExceptionConverter.convertException(e); }
(Domain) WriterException
(Domain) ExceptionConverter
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeQRCode.java
catch (WriterException ex) { throw new ExceptionConverter(ex); }
(Domain) BadElementException
(Domain) ExceptionConverter
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (BadElementException be) { throw new ExceptionConverter(be); }
(Domain) DocumentException
(Domain) ExceptionConverter
25
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPCell.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
(Lib) CloneNotSupportedException
(Lib) InternalError
10
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/RectangularShape.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Dimension2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Point2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/IntHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
(Lib) IllegalArgumentException
Unknown
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Version.java
catch (IllegalArgumentException iae) { throw iae; }
(Lib) InterruptedException
(Lib) IOException
2
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
(Lib) IOException
(Lib) MapFailedException
(Domain) ExceptionConverter
(Domain) FontReadingException
(Domain) BadPdfFormatException
(Lib) IOException
(Lib) IllegalArgumentException
Unknown
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
catch (IOException e){ if (exceptionIsMapFailureException(e)) throw new MapFailedException(e); }
38
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/SimplePatternParser.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LZWDecoder.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFunction.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfAnnotationsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (IOException e1) { throw new ExceptionConverter(e1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPageLabels.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
catch (IOException e) { throw new FontReadingException("Error reading font file", e); }
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
catch(IOException ioe) { throw new BadPdfFormatException(ioe.getMessage()); }
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/TSAClientBouncyCastle.java
catch (IOException ioe) { throw new IOException(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL)); }
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (IOException e) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object")); }
5
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { // Only a problem if we got no data at all. if( i == 0 ) throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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/PdfReader.java
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
catch (IOException e) { xref = null; throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (IOException e){ close(); throw e; }
(Domain) BadPasswordException
Unknown
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (BadPasswordException ex) { throw ex; }
(Lib) NumberFormatException
(Lib) RuntimeException
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfNumber.java
catch (NumberFormatException nfe){ throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.number.2", content, nfe.toString())); }
(Lib) ParserConfigurationException
(Domain) ExceptionConverter
2
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/xmp/XmpReader.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
(Lib) RuntimeException
Unknown
2
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e) { // let's flip the fill bits and try again... tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS; try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e2) { throw e; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e2) { throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (RuntimeException e){ close(); throw e; }
(Lib) UnsupportedEncodingException
(Domain) ExceptionConverter
(Domain) WriterException
4
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
2
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
(Lib) DataFormatException
(Domain) ExceptionConverter
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch(DataFormatException dfe) { throw new ExceptionConverter(dfe); }
(Lib) ClassCastException
(Lib) IllegalArgumentException
(Lib) ClassCastException
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
catch (ClassCastException ex) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.to.consolidate.the.named.destinations.of.your.reader")); }
3
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
(Lib) GeneralSecurityException
(Domain) VerificationException
2
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch(GeneralSecurityException e) { throw new VerificationException(signCert, "Couldn't verify with CRL or OCSP or trusted anchor"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch(GeneralSecurityException e) { if (super.verify(responderCert, issuerCert, null).size() == 0) throw new VerificationException(responderCert, "Responder certificate couldn't be verified"); }
(Lib) SAXException
(Domain) ExceptionConverter
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (SAXException e) { throw new ExceptionConverter(e); }
(Lib) OCSPException
(Lib) GeneralSecurityException
1
                    
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch (OCSPException e) { throw new GeneralSecurityException(e); }

Caught / Thrown Exception

Not all exceptions are thrown AND caught in the same project. The following table gives the exceptions types with respect to this. The lower left hand side sell lists all exceptions thrown but not caught (prevalent for libraries), the upper right-hand side lists all exceptions caught but not thrown (usually coming from external dependencies).

Thrown Not Thrown
Caught
Type Name
(Lib) Exception
(Domain) NoninvertibleTransformException
(Domain) WriterException
(Domain) BadElementException
(Domain) DocumentException
(Lib) IllegalArgumentException
(Lib) NullPointerException
(Lib) IOException
(Domain) BadPasswordException
(Lib) NumberFormatException
(Lib) EOFException
(Lib) MapFailedException
(Lib) RuntimeException
(Lib) ArrayIndexOutOfBoundsException
(Lib) ClassCastException
(Lib) NoSuchAlgorithmException
(Lib) GeneralSecurityException
(Lib) IndexOutOfBoundsException
Type Name
(Lib) CloneNotSupportedException
(Lib) MissingResourceException
(Lib) InterruptedException
(Lib) ParserConfigurationException
(Lib) BufferUnderflowException
(Lib) UnsupportedEncodingException
(Lib) ClassNotFoundException
(Lib) DataFormatException
(Lib) InvalidKeyException
(Lib) SAXException
(Lib) Throwable
(Lib) CertificateParsingException
(Lib) OCSPException
(Lib) OperatorCreationException
(Lib) MalformedURLException
Not caught
Type Name
(Lib) InternalError
(Lib) NoSuchElementException
(Domain) IllegalPathStateException
(Domain) ExceptionConverter
(Lib) IllegalStateException
(Lib) UnsupportedOperationException
(Domain) PdfException
(Domain) BadPdfFormatException
(Domain) InvalidPdfException
(Domain) PdfXConformanceException
(Domain) UnsupportedPdfException
(Lib) ArithmeticException
(Lib) EmptyStackException
(Domain) IllegalPdfSyntaxException
(Domain) InlineImageParseException
(Domain) FontReadingException
(Lib) Error
(Domain) VerificationException

Methods called in Catch and Finally Blocks

The following shows the methods that are called inside catch blocks (first column) and finally blocks (second column). For each method, we give the number of times it is called in a catch block (second sub-column), and the total number of calls (third sub-column). If the method name is red, it means that it is only called from catch/finally blocks. Hovering over a number triggers showing code snippets from the application code.

Catch Finally
Method Nbr Nbr total
getMessage 21
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new RuntimeException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/GlyphList.java
catch (Exception e) { System.err.println("glyphlist.txt loading error: " + e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne){ throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()), ne); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContents.java
catch (Exception e) { throw new BadPdfFormatException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
catch(IOException ioe) { throw new BadPdfFormatException(ioe.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { return e.getMessage(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (Exception e) { LOGGER.info("Skipped CRL url: " + e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (Exception e) { LOGGER.info("Skipped CRL: " + e.getMessage() + " for " + urlt); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch(Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
26
getComposedMessage 14
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne){ throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()), ne); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfNumber.java
catch (NumberFormatException nfe){ throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.number.2", content, nfe.toString())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
catch (ClassCastException ex) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.to.consolidate.the.named.destinations.of.your.reader")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/TSAClientBouncyCastle.java
catch (IOException ioe) { throw new IOException(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (IOException e) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch (Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch(Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
515
printStackTrace 13
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/AsianFontMapper.java
catch (Exception e) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2SegmentReader.java
catch (IOException e) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { e.printStackTrace(); return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { e.printStackTrace(); return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.lang.ClassNotFoundException e ) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException ex ) { ex.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException ex ) { ex.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (IOException ioe) { ioe.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfName.java
catch (Exception e) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch (IOException ioe) { ioe.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentReaderTool.java
catch (Exception e){ e.printStackTrace(System.err); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontUnicode.java
catch (Exception e) { e.printStackTrace(); }
17
println 8
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e){ System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); return -1; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { System.err.println( "Error decoding from file " + filename ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { System.err.println( "Error encoding from file " + filename ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfLister.java
catch (IOException e) { System.err.println("I/O exception: " + e); // } catch (java.util.zip.DataFormatException e) { // System.err.println("Data Format Exception: " + e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/GlyphList.java
catch (Exception e) { System.err.println("glyphlist.txt loading error: " + e.getMessage()); }
77
String 6
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch (java.io.UnsupportedEncodingException uue) { return new String( outBuff, 0, e ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
catch (UnsupportedEncodingException e) { faceName = new String(name, 0, k); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
catch (UnsupportedEncodingException e) { s = new String(text, 0, k); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
catch (UnsupportedEncodingException e) { s = new String(text, 0, k); }
134
close 4
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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/PdfReader.java
catch (IOException e) { try{tokens.close();}catch(Exception ee){} throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (IOException e){ close(); throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (RuntimeException e){ close(); throw e; }
167
info 4
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (CertificateParsingException e) { LOGGER.info("Skipped CRL url (certificate could not be parsed)"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (MalformedURLException e) { LOGGER.info("Skipped CRL url (malformed): " + url); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (Exception e) { LOGGER.info("Skipped CRL url: " + e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (Exception e) { LOGGER.info("Skipped CRL: " + e.getMessage() + " for " + urlt); }
76
toByteArray 4
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { return fout.toByteArray(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { if (strict) return null; return out.toByteArray(); }
74
rebuildXref 3
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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); } }
4
toString 3
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfNumber.java
catch (NumberFormatException nfe){ throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.number.2", content, nfe.toString())); }
338
Font 2
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(IOException ioe) { // the font is registered as a true type font, but the path was wrong return new Font(FontFamily.UNDEFINED, size, style, color); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(NullPointerException npe) { // null was entered as fontname and/or encoding return new Font(FontFamily.UNDEFINED, size, style, color); }
39
PdfStream 2
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch(SAXException e) { xmp = new PdfStream(altMetadata); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch(IOException e) { xmp = new PdfStream(altMetadata); }
24
error 2
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); }
3
isLogging 2
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); }
4
setColorFill 2
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { if (fill) cb.setColorFill(BaseColor.GRAY); else cb.setColorStroke(BaseColor.GRAY); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { if (fill) cb.setColorFill(BaseColor.GRAY); else cb.setColorStroke(BaseColor.GRAY); }
48
setColorStroke 2
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { if (fill) cb.setColorFill(BaseColor.GRAY); else cb.setColorStroke(BaseColor.GRAY); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { if (fill) cb.setColorFill(BaseColor.GRAY); else cb.setColorStroke(BaseColor.GRAY); }
33
verify 2
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/RootStoreVerifier.java
catch (GeneralSecurityException e) { return super.verify(signCert, issuerCert, signDate); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch(GeneralSecurityException e) { if (super.verify(responderCert, issuerCert, null).size() == 0) throw new VerificationException(responderCert, "Responder certificate couldn't be verified"); }
30
Chunk 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/EntitiesToSymbol.java
catch(Exception exception) { return new Chunk(e, font); }
39
File 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Utilities.java
catch (Exception e) { return new File(filename).toURI().toURL(); }
25
PdfNull 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDestination.java
catch (RuntimeException e) { add(new PdfNull()); }
8
PdfString 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAction.java
catch (Exception e) { js.put(PdfName.JS, new PdfString(code)); }
167
RAFRandomAccessSource 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
catch (MapFailedException e){ return new RAFRandomAccessSource(raf); }
3
add 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDestination.java
catch (RuntimeException e) { add(new PdfNull()); }
844
convertException
1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw ExceptionConverter.convertException(e); }
1
decode2D 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e) { // let's flip the fill bits and try again... tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS; try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e2) { throw e; } }
2
delete 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
catch (IOException e) { try{raf.close();}catch(Exception ee){} try{tempFile.delete();}catch(Exception ee){} throw e; }
8
exceptionIsMapFailureException
1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
catch (IOException e){ if (exceptionIsMapFailureException(e)) throw new MapFailedException(e); }
1
getBytes 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); }
72
getPublicKey 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
catch(InvalidKeyException e){ cipher.init(1,x509certificate.getPublicKey()); }
18
getSeed 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
catch (NoSuchAlgorithmException e) { seed = SecureRandom.getSeed(SEED_LENGTH); }
2
init 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
catch(InvalidKeyException e){ cipher.init(1,x509certificate.getPublicKey()); }
22
put 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAction.java
catch (Exception e) { js.put(PdfName.JS, new PdfString(code)); }
3153
readDocObj 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
3
seek 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { tokens.seek(pos); }
160
setAutoindent
1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { list.setAutoindent(true); }
1
setLeading 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { // default leading paragraph.setLeading(0, 1.5f); }
19
size 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch(GeneralSecurityException e) { if (super.verify(responderCert, issuerCert, null).size() == 0) throw new VerificationException(responderCert, "Responder certificate couldn't be verified"); }
643
toURI
1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Utilities.java
catch (Exception e) { return new File(filename).toURI().toURL(); }
1
toURL 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Utilities.java
catch (Exception e) { return new File(filename).toURI().toURL(); }
6
warn 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
catch (GeneralSecurityException e) { LOGGER.warn("CRL not issued by the same authority as the certificate that is being checked"); }
2
Method Nbr Nbr total
close 68
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
finally { try {is.close();}catch(IOException ioe){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
finally { try {is.close();}catch(IOException ioe){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
finally { try {is.close();}catch(IOException ioe){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
finally { if (ra != null) ra.close(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
finally { if (ra != null) ra.close(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
finally { if (is != null) { is.close(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
finally { if (ra != null) ra.close(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
finally { if (ra != null) ra.close(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
finally { if (is != null) { is.close(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Jpeg.java
finally { if (is != null) { is.close(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/error_messages/MessageLocalization.java
finally { try { if (null != is){ is.close(); } } catch (Exception exx) { } // do nothing }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ImgWMF.java
finally { if (is != null) { is.close(); } plainWidth = getWidth(); plainHeight = getHeight(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ImgWMF.java
finally { if (is != null) { is.close(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
finally { if (is != null) { is.close(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
finally { if (is != null) { is.close(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
finally { if (is != null) { is.close(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
finally { try{ bos.close(); } catch( Exception e ){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
finally { try{ bos.close(); } catch( Exception e ){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
finally { if (null != bis){ try{ bis.close(); } catch( Exception e) {} } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
finally { try{ bis.close(); } catch( Exception e) {} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
finally { try { out.close(); } catch( Exception ex ){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
finally { try { out.close(); } catch( Exception ex ){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
finally { if (is != null) { is.close(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FdfReader.java
finally { try { tokens.close(); } catch (Exception e) { // empty on purpose } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
finally { if (is != null) { try { is.close(); } catch (Exception e) { // empty on purpose } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
finally { if (rf != null) { try { rf.close(); } catch (Exception e) { // empty on purpose } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
finally { if (rf != null) { try { rf.close(); } catch (Exception e) { // empty on purpose } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
finally { if (rf != null) { try { rf.close(); } catch (Exception e) { // empty on purpose } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
finally { if (rf != null) { try { rf.close(); } catch (Exception e) { // empty on purpose } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/SimplePatternParser.java
finally { try { stream.close(); } catch (Exception e) { } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
finally { try { if (rg != null) rg.close(); } catch (IOException e) { // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
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
finally { try {if (rf2 != null) {rf2.close();}} catch (Exception e) {} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
finally { try { rf2.close(); } catch (Exception e) { // empty on purpose } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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/PdfCopyFieldsImp.java
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 } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/GlyphList.java
finally { if (is != null) { try { is.close(); } catch (Exception e) { // empty on purpose } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
finally { try { if (rf != null) rf.close(); }catch(Exception e){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
finally { try{rf.close();}catch(Exception e){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
finally { try{rf.close();}catch(Exception e){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
finally { try{rf.close();}catch(Exception e){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
finally { try { rf.close(); } catch (Exception e) { // empty on purpose } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
finally { try{rf.close();}catch(Exception e){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFontSubset.java
finally { try { buf.close(); } catch (Exception e) { // empty on purpose } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFileSpecification.java
finally { if (in != null) try{in.close();}catch(Exception e){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/EnumerateTTC.java
finally { if (rf != null) rf.close(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfdfReader.java
finally { try{if (fin != null) {fin.close();}}catch(Exception e){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReaderInstance.java
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/ICC_Profile.java
finally { try{fs.close();}catch(Exception x){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapParserEx.java
finally { inp.close(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
finally { try { rf.close(); } catch (Exception e) { // empty on purpose } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
finally { if (is != null) { try{ is.close(); } catch (Exception ee) { // empty on purpose } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
finally { try{if (fin != null) {fin.close();}}catch(Exception ex){} }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Jpeg2000.java
finally { if (inp != null) { try{inp.close();}catch(Exception e){} inp = null; } }
167
restoreCanvases
2
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
finally { restoreCanvases(canvases); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
finally { if (cell.getRotation() == 180) { restoreCanvases(canvases); } }
2
ExceptionConverter 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
finally { try { if (rg != null) rg.close(); } catch (IOException e) { // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway throw new ExceptionConverter(e); } }
163
delete 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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){} }
8
flushIndirectObjects
1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
finally {flushIndirectObjects();}
1
getHeight 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ImgWMF.java
finally { if (is != null) { is.close(); } plainWidth = getWidth(); plainHeight = getHeight(); }
173
getRotation 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
finally { if (cell.getRotation() == 180) { restoreCanvases(canvases); } }
24
getWidth 1
                  
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ImgWMF.java
finally { if (is != null) { is.close(); } plainWidth = getWidth(); plainHeight = getHeight(); }
194

Reference Table

This table concatenates the results of the previous tables.

Checked/Runtime Type Exception Thrown Thrown from Catch Declared Caught directly Caught
with Thrown
Caught
with Thrown Runtime
unknown (Lib) . 0 0 0 0 0 0
unknown (Lib) ArithmeticException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256.java
int inverse(int a) { if (a == 0) { throw new ArithmeticException(); } return expTable[255 - logTable[a]]; }
0 0 0 0 0
unknown (Lib) ArrayIndexOutOfBoundsException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
private String decodeSingleCID(byte[] bytes, int offset, int len){ if (toUnicodeCmap != null){ if (offset + len > bytes.length) throw new ArrayIndexOutOfBoundsException(MessageLocalization.getComposedMessage("invalid.index.1", offset + len)); String s = toUnicodeCmap.lookup(bytes, offset, len); if (s != null) return s; if (len != 1 || cidbyte2uni == null) return null; } if (len == 1){ if (cidbyte2uni == null) return ""; else return new String(cidbyte2uni, 0xff & bytes[offset], 1); } throw new Error("Multi-byte glyphs not implemented yet"); }
0 0 4
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (ArrayIndexOutOfBoundsException e) { //ignore }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFLZWDecoder.java
catch(ArrayIndexOutOfBoundsException e) { // Strip not terminated as expected: return EndOfInformation code. return 257; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
catch (ArrayIndexOutOfBoundsException ae) { // if the data type is unknown we should skip this TIFF Field processTag = false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LZWDecoder.java
catch(ArrayIndexOutOfBoundsException e) { // Strip not terminated as expected: return EndOfInformation code. return 257; }
0 0
checked (Domain) BadElementException
public class BadElementException extends DocumentException {
    
    private static final long serialVersionUID = -799006030723822254L;

	// constructors
    /**
     * Constructs a BadElementException
     * @param ex an Exception object that has to be turned into a BadElementException
     */
    public BadElementException(Exception ex) {
        super(ex);
    }
    
    /**
     * Constructs a <CODE>BadElementException</CODE> without a message.
     */
    BadElementException() {
        super();
    }
    
    /**
     * Constructs a <code>BadElementException</code> with a message.
     * @param		message			a message describing the exception
     */
    public BadElementException(String message) {
        super(message);
    }
}
12
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final int width, final int height, final boolean reverseBits, final int typeCCITT, final int parameters, final byte[] data, final int transparency[]) throws BadElementException { if (transparency != null && transparency.length != 2) throw new BadElementException(MessageLocalization.getComposedMessage("transparency.length.must.be.equal.to.2.with.ccitt.images")); Image img = new ImgCCITT(width, height, reverseBits, typeCCITT, parameters, data); img.transparency = transparency; return img; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final int width, final int height, final int components, final int bpc, final byte data[], final int transparency[]) throws BadElementException { if (transparency != null && transparency.length != components * 2) throw new BadElementException(MessageLocalization.getComposedMessage("transparency.length.must.be.equal.to.componentes.2")); if (components == 1 && bpc == 1) { byte g4[] = CCITTG4Encoder.compress(data, width, height); return Image.getInstance(width, height, false, Image.CCITTG4, Image.CCITT_BLACKIS1, g4, transparency); } Image img = new ImgRaw(width, height, components, bpc, data); img.transparency = transparency; return img; }
// 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/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(); } }
0 38
            
// 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 int width, final int height, final int components, final int bpc, final byte data[]) throws BadElementException { return Image.getInstance(width, height, components, bpc, data, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final int width, final int height, final boolean reverseBits, final int typeCCITT, final int parameters, final byte[] data) throws BadElementException { return Image.getInstance(width, height, reverseBits, typeCCITT, parameters, data, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final int width, final int height, final boolean reverseBits, final int typeCCITT, final int parameters, final byte[] data, final int transparency[]) throws BadElementException { if (transparency != null && transparency.length != 2) throw new BadElementException(MessageLocalization.getComposedMessage("transparency.length.must.be.equal.to.2.with.ccitt.images")); Image img = new ImgCCITT(width, height, reverseBits, typeCCITT, parameters, data); img.transparency = transparency; return img; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final int width, final int height, final int components, final int bpc, final byte data[], final int transparency[]) throws BadElementException { if (transparency != null && transparency.length != components * 2) throw new BadElementException(MessageLocalization.getComposedMessage("transparency.length.must.be.equal.to.componentes.2")); if (components == 1 && bpc == 1) { byte g4[] = CCITTG4Encoder.compress(data, width, height); return Image.getInstance(width, height, false, Image.CCITTG4, Image.CCITT_BLACKIS1, g4, transparency); } Image img = new ImgRaw(width, height, components, bpc, data); img.transparency = transparency; return img; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final PdfTemplate template) throws BadElementException { return new ImgTemplate(template); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final PRIndirectReference ref) throws BadElementException { PdfDictionary dic = (PdfDictionary)PdfReader.getPdfObjectRelease(ref); int width = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.WIDTH))).intValue(); int height = ((PdfNumber)PdfReader.getPdfObjectRelease(dic.get(PdfName.HEIGHT))).intValue(); Image imask = null; PdfObject obj = dic.get(PdfName.SMASK); if (obj != null && obj.isIndirect()) { imask = getInstance((PRIndirectReference)obj); } else { obj = dic.get(PdfName.MASK); if (obj != null && obj.isIndirect()) { PdfObject obj2 = PdfReader.getPdfObjectRelease(obj); if (obj2 instanceof PdfDictionary) imask = getInstance((PRIndirectReference)obj); } } Image img = new ImgRaw(width, height, 1, 1, null); img.imageMask = imask; img.directReference = ref; 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, 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 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/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/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 Image indexedModel(byte bdata[], int bpc, int paletteEntries) throws BadElementException { Image img = new ImgRaw(width, height, 1, bpc, bdata); PdfArray colorspace = new PdfArray(); colorspace.add(PdfName.INDEXED); colorspace.add(PdfName.DEVICERGB); byte np[] = getPalette(paletteEntries); int len = np.length; colorspace.add(new PdfNumber(len / 3 - 1)); colorspace.add(new PdfString(np)); PdfDictionary ad = new PdfDictionary(); ad.put(PdfName.COLORSPACE, colorspace); img.setAdditional(ad); return img; }
// 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/BarcodeQRCode.java
public Image getImage() throws BadElementException { byte[] b = getBitMatrix(); byte g4[] = CCITTG4Encoder.compress(b, bm.getWidth(), bm.getHeight()); return Image.getInstance(bm.getWidth(), bm.getHeight(), false, Image.CCITTG4, Image.CCITT_BLACKIS1, g4, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
public Image getImage() throws BadElementException { paintCode(); byte g4[] = CCITTG4Encoder.compress(outBits, bitColumns, codeRows); return Image.getInstance(bitColumns, codeRows, false, Image.CCITTG4, (options & PDF417_INVERT_BITMAP) == 0 ? 0 : Image.CCITT_BLACKIS1, g4, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeDatamatrix.java
public Image createImage() throws BadElementException { if (image == null) return null; byte g4[] = CCITTG4Encoder.compress(image, width + 2 * ws, height + 2 * ws); return Image.getInstance(width + 2 * ws, height + 2 * ws, false, Image.CCITTG4, 0, g4, null); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (BadElementException be) { throw new ExceptionConverter(be); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (BadElementException be) { throw new ExceptionConverter(be); }
1
checked (Domain) BadPasswordException
public class BadPasswordException extends IOException {

	/** Serial Version UID. */
	private static final long serialVersionUID = -4333706268155063964L;

	/**
	 * Creates an exception saying the user password was incorrect.
	 * @param message the message
	 */
	public BadPasswordException(final String message) {
		super(message);
	}
}
6
            
// 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/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/PdfEncryption.java
public boolean readKey(PdfDictionary enc, byte[] password) throws BadPasswordException { try { if (password == null) password = new byte[0]; byte[] oValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.O).toString()); byte[] uValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.U).toString()); byte[] oeValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.OE).toString()); byte[] ueValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.UE).toString()); byte[] perms = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.PERMS).toString()); boolean isUserPass = false; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); byte[] hash = md.digest(); boolean isOwnerPass = compareArray(hash, oValue, 32); if (isOwnerPass) { md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, KEY_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(oeValue, 0, oeValue.length); } else { md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); isUserPass = compareArray(hash, uValue, 32); if (!isUserPass) throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, KEY_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(ueValue, 0, ueValue.length); } AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, key); byte[] decPerms = ac.processBlock(perms, 0, perms.length); if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b') throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); permissions = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8) | ((decPerms[2] & 0xff) << 16) | ((decPerms[2] & 0xff) << 24); encryptMetadata = decPerms[8] == (byte)'T'; return isOwnerPass; } catch (BadPasswordException ex) { throw ex; } catch (Exception ex) { throw new ExceptionConverter(ex); } }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public boolean readKey(PdfDictionary enc, byte[] password) throws BadPasswordException { try { if (password == null) password = new byte[0]; byte[] oValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.O).toString()); byte[] uValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.U).toString()); byte[] oeValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.OE).toString()); byte[] ueValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.UE).toString()); byte[] perms = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.PERMS).toString()); boolean isUserPass = false; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); byte[] hash = md.digest(); boolean isOwnerPass = compareArray(hash, oValue, 32); if (isOwnerPass) { md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, KEY_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(oeValue, 0, oeValue.length); } else { md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); isUserPass = compareArray(hash, uValue, 32); if (!isUserPass) throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, KEY_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(ueValue, 0, ueValue.length); } AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, key); byte[] decPerms = ac.processBlock(perms, 0, perms.length); if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b') throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); permissions = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8) | ((decPerms[2] & 0xff) << 16) | ((decPerms[2] & 0xff) << 24); encryptMetadata = decPerms[8] == (byte)'T'; return isOwnerPass; } catch (BadPasswordException ex) { throw ex; } catch (Exception ex) { throw new ExceptionConverter(ex); } }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (BadPasswordException ex) { throw ex; }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (BadPasswordException ex) { throw ex; }
0
checked (Domain) BadPdfFormatException
public class BadPdfFormatException extends PdfException {
    
    // constructors
    
private static final long serialVersionUID = 1802317735708833538L;

/**
 * Constructs a <CODE>BadPdfFormatException</CODE> without a message.
 */
    
    BadPdfFormatException() {
        super();
    }
    
/**
 * Constructs a <code>BadPdfFormatException</code> with a message.
 *
 * @param		message			a message describing the exception
 */
    
    BadPdfFormatException(String message) {
        super(message);
    }
}
10
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
protected void setReader(PdfReader reader) throws BadPdfFormatException { this.reader = reader; PdfObject obj = reader.getCatalog().get(PdfName.STRUCTTREEROOT); obj = getDirectObject(obj); if ((obj == null) || (!obj.isDictionary())) throw new BadPdfFormatException(MessageLocalization.getComposedMessage("no.structtreeroot.found")); structTreeRoot = (PdfDictionary) obj; obj = PdfStructTreeController.getDirectObject(structTreeRoot.get(PdfName.PARENTTREE)); if (!obj.isDictionary()) throw new BadPdfFormatException(MessageLocalization.getComposedMessage("the.document.does.not.contain.parenttree")); parentTree = (PdfDictionary) obj; sourceRoleMap = null; sourceClassMap = null; }
// 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
protected void addClass(PdfObject object) throws BadPdfFormatException { object = getDirectObject(object); if (object.isDictionary()) { PdfObject curClass = ((PdfDictionary) object).get(PdfName.C); if (curClass == null) return; if (curClass.isArray()) { PdfArray array = (PdfArray) curClass; for (int i = 0; i < array.size(); ++i) { addClass(array.getPdfObject(i)); } } else if (curClass.isName()) addClass(curClass); } else if (object.isName()) { PdfName name = (PdfName) object; if (sourceClassMap == null) { object = getDirectObject(structTreeRoot.get(PdfName.CLASSMAP)); if (object == null || !object.isDictionary()) { return; } sourceClassMap = (PdfDictionary) object; } object = getDirectObject(sourceClassMap.get(name)); if (object == null) { return; } PdfObject put = structureTreeRoot.getMappedClass(name); if (put != null) { if (!compareObjects(put, object)) { throw new BadPdfFormatException(MessageLocalization.getComposedMessage("conflict.in.classmap", name)); } } else { if (object.isDictionary()) structureTreeRoot.mapClass(name, getDirectDict((PdfDictionary) object)); else if (object.isArray()) { structureTreeRoot.mapClass(name, getDirectArray((PdfArray) object)); } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
protected void addRole(PdfName structType) throws BadPdfFormatException { if (structType == null) { return; } for (PdfName name : standardTypes) { if (name.equals(structType)) return; } if (sourceRoleMap == null) { PdfObject object = getDirectObject(structTreeRoot.get(PdfName.ROLEMAP)); if (object == null || !object.isDictionary()) { return; } sourceRoleMap = (PdfDictionary) object; } PdfObject object = sourceRoleMap.get(structType); if (object == null || !object.isName()) { return; } PdfObject currentRole; if (roleMap == null) { roleMap = new PdfDictionary(); structureTreeRoot.put(PdfName.ROLEMAP, roleMap); roleMap.put(structType, object); } else if ((currentRole = roleMap.get(structType)) != null) { if (!currentRole.equals(object)) { throw new BadPdfFormatException(MessageLocalization.getComposedMessage("conflict.in.rolemap", object)); } } else { roleMap.put(structType, object); } }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContents.java
catch (Exception e) { throw new BadPdfFormatException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
catch(IOException ioe) { throw new BadPdfFormatException(ioe.getMessage()); }
24
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
protected void setReader(PdfReader reader) throws BadPdfFormatException { this.reader = reader; PdfObject obj = reader.getCatalog().get(PdfName.STRUCTTREEROOT); obj = getDirectObject(obj); if ((obj == null) || (!obj.isDictionary())) throw new BadPdfFormatException(MessageLocalization.getComposedMessage("no.structtreeroot.found")); structTreeRoot = (PdfDictionary) obj; obj = PdfStructTreeController.getDirectObject(structTreeRoot.get(PdfName.PARENTTREE)); if (!obj.isDictionary()) throw new BadPdfFormatException(MessageLocalization.getComposedMessage("the.document.does.not.contain.parenttree")); parentTree = (PdfDictionary) obj; sourceRoleMap = null; sourceClassMap = null; }
// 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/PdfStructTreeController.java
protected void addClass(PdfObject object) throws BadPdfFormatException { object = getDirectObject(object); if (object.isDictionary()) { PdfObject curClass = ((PdfDictionary) object).get(PdfName.C); if (curClass == null) return; if (curClass.isArray()) { PdfArray array = (PdfArray) curClass; for (int i = 0; i < array.size(); ++i) { addClass(array.getPdfObject(i)); } } else if (curClass.isName()) addClass(curClass); } else if (object.isName()) { PdfName name = (PdfName) object; if (sourceClassMap == null) { object = getDirectObject(structTreeRoot.get(PdfName.CLASSMAP)); if (object == null || !object.isDictionary()) { return; } sourceClassMap = (PdfDictionary) object; } object = getDirectObject(sourceClassMap.get(name)); if (object == null) { return; } PdfObject put = structureTreeRoot.getMappedClass(name); if (put != null) { if (!compareObjects(put, object)) { throw new BadPdfFormatException(MessageLocalization.getComposedMessage("conflict.in.classmap", name)); } } else { if (object.isDictionary()) structureTreeRoot.mapClass(name, getDirectDict((PdfDictionary) object)); else if (object.isArray()) { structureTreeRoot.mapClass(name, getDirectArray((PdfArray) object)); } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStructTreeController.java
protected void addRole(PdfName structType) throws BadPdfFormatException { if (structType == null) { return; } for (PdfName name : standardTypes) { if (name.equals(structType)) return; } if (sourceRoleMap == null) { PdfObject object = getDirectObject(structTreeRoot.get(PdfName.ROLEMAP)); if (object == null || !object.isDictionary()) { return; } sourceRoleMap = (PdfDictionary) object; } PdfObject object = sourceRoleMap.get(structType); if (object == null || !object.isName()) { return; } PdfObject currentRole; if (roleMap == null) { roleMap = new PdfDictionary(); structureTreeRoot.put(PdfName.ROLEMAP, roleMap); roleMap.put(structType, object); } else if ((currentRole = roleMap.get(structType)) != null) { if (!currentRole.equals(object)) { throw new BadPdfFormatException(MessageLocalization.getComposedMessage("conflict.in.rolemap", object)); } } else { roleMap.put(structType, object); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
public PdfImportedPage getImportedPage(PdfReader reader, int pageNumber, boolean keepTaggedPdfStructure) throws BadPdfFormatException { updateRootKids = false; if (!keepTaggedPdfStructure) return getImportedPage(reader, pageNumber); else { if (structTreeController != null) { if (reader != structTreeController.reader) structTreeController.setReader(reader); } else { structTreeController = new PdfStructTreeController(reader, this); } ImportedPage newPage = new ImportedPage(reader, pageNumber); switch (checkStructureTreeRootKids(newPage)) { case -1: //-1 - clear , update clearIndirects(reader); updateRootKids = true; break; case 0: //0 - not clear, not update updateRootKids = false; break; case 1: //1 - not clear, update updateRootKids = true; break; } importedPages.add(newPage); disableIndirects.clear(); parentObjects.clear(); return getImportedPageImpl(reader, pageNumber); } }
// 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
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/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; }
0 0 0
unknown (Lib) BufferUnderflowException 0 0 0 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/ByteBufferRandomAccessSource.java
catch (BufferUnderflowException e) { return -1; // EOF }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (BufferUnderflowException e) { return -1; // EOF }
0 0
unknown (Lib) CertificateParsingException 0 0 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateUtil.java
public static String getCRLURL(X509Certificate certificate) throws CertificateParsingException { ASN1Primitive obj; try { obj = getExtensionValue(certificate, Extension.cRLDistributionPoints.getId()); } catch (IOException e) { obj = null; } if (obj == null) { return null; } CRLDistPoint dist = CRLDistPoint.getInstance(obj); DistributionPoint[] dists = dist.getDistributionPoints(); for (DistributionPoint p : dists) { DistributionPointName distributionPointName = p.getDistributionPoint(); if (DistributionPointName.FULL_NAME != distributionPointName.getType()) { continue; } GeneralNames generalNames = (GeneralNames)distributionPointName.getName(); GeneralName[] names = generalNames.getNames(); for (GeneralName name : names) { if (name.getTagNo() != GeneralName.uniformResourceIdentifier) { continue; } DERIA5String derStr = DERIA5String.getInstance((ASN1TaggedObject)name.toASN1Primitive(), false); return derStr.getString(); } } return null; }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (CertificateParsingException e) { // DO NOTHING; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (CertificateParsingException e) { LOGGER.info("Skipped CRL url (certificate could not be parsed)"); }
0 0
unknown (Lib) ClassCastException 11
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFField.java
public int getAsInt(int index) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return ((byte[])data)[index] & 0xff; case TIFF_SBYTE: return ((byte[])data)[index]; case TIFF_SHORT: return ((char[])data)[index] & 0xffff; case TIFF_SSHORT: return ((short[])data)[index]; case TIFF_SLONG: return ((int[])data)[index]; default: throw new ClassCastException(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFField.java
public long getAsLong(int index) { switch (type) { case TIFF_BYTE: case TIFF_UNDEFINED: return ((byte[])data)[index] & 0xff; case TIFF_SBYTE: return ((byte[])data)[index]; case TIFF_SHORT: return ((char[])data)[index] & 0xffff; case TIFF_SSHORT: return ((short[])data)[index]; case TIFF_SLONG: return ((int[])data)[index]; case TIFF_LONG: return ((long[])data)[index]; default: throw new ClassCastException(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFField.java
public float getAsFloat(int index) { switch (type) { case TIFF_BYTE: return ((byte[])data)[index] & 0xff; case TIFF_SBYTE: return ((byte[])data)[index]; case TIFF_SHORT: return ((char[])data)[index] & 0xffff; case TIFF_SSHORT: return ((short[])data)[index]; case TIFF_SLONG: return ((int[])data)[index]; case TIFF_LONG: return ((long[])data)[index]; case TIFF_FLOAT: return ((float[])data)[index]; case TIFF_DOUBLE: return (float)((double[])data)[index]; case TIFF_SRATIONAL: int[] ivalue = getAsSRational(index); return (float)((double)ivalue[0]/ivalue[1]); case TIFF_RATIONAL: long[] lvalue = getAsRational(index); return (float)((double)lvalue[0]/lvalue[1]); default: throw new ClassCastException(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFField.java
public double getAsDouble(int index) { switch (type) { case TIFF_BYTE: return ((byte[])data)[index] & 0xff; case TIFF_SBYTE: return ((byte[])data)[index]; case TIFF_SHORT: return ((char[])data)[index] & 0xffff; case TIFF_SSHORT: return ((short[])data)[index]; case TIFF_SLONG: return ((int[])data)[index]; case TIFF_LONG: return ((long[])data)[index]; case TIFF_FLOAT: return ((float[])data)[index]; case TIFF_DOUBLE: return ((double[])data)[index]; case TIFF_SRATIONAL: int[] ivalue = getAsSRational(index); return (double)ivalue[0]/ivalue[1]; case TIFF_RATIONAL: long[] lvalue = getAsRational(index); return (double)lvalue[0]/lvalue[1]; default: throw new ClassCastException(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
Override public void add(final int index, final Element element) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } try { if (element.isNestable()) { super.add(index, element); } else { throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
Override public boolean add(final Element element) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } try { if (element.type() == Element.SECTION) { Section section = (Section) element; section.setNumbers(++subsections, numbers); return super.add(section); } else if (element instanceof MarkedSection && ((MarkedObject)element).element.type() == Element.SECTION) { MarkedSection mo = (MarkedSection)element; Section section = (Section)mo.element; section.setNumbers(++subsections, numbers); return super.add(mo); } else if (element.isNestable()) { return super.add(element); } else { throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
Override public void add(final int index, final Element element) { if (element == null) return; switch (element.type()) { case Element.CHUNK: Chunk chunk = (Chunk) element; if (!font.isStandardFont()) { chunk.setFont(font.difference(chunk.getFont())); } if (hyphenation != null && chunk.getHyphenation() == null && !chunk.isEmpty()) { chunk.setHyphenation(hyphenation); } super.add(index, chunk); return; case Element.PHRASE: case Element.PARAGRAPH: case Element.MARKED: case Element.DIV: case Element.ANCHOR: case Element.ANNOTATION: case Element.PTABLE: case Element.LIST: case Element.YMARK: case Element.WRITABLE_DIRECT: super.add(index, element); return; default: throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", element.getClass().getName())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
Override public boolean add(final Element element) { if (element == null) return false; try { // TODO same as in document - change switch to generic adding that works everywhere switch(element.type()) { case Element.CHUNK: return addChunk((Chunk) element); case Element.PHRASE: case Element.PARAGRAPH: Phrase phrase = (Phrase) element; boolean success = true; Element e; for (Object element2 : phrase) { e = (Element) element2; if (e instanceof Chunk) { success &= addChunk((Chunk)e); } else { success &= this.add(e); } } return success; case Element.MARKED: case Element.DIV: case Element.ANCHOR: case Element.ANNOTATION: case Element.PTABLE: // case added by mr. Karen Vardanyan case Element.LIST: case Element.YMARK: case Element.WRITABLE_DIRECT: return super.add(element); default: throw new ClassCastException(String.valueOf(element.type())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } }
3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
0 8
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (ClassCastException ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
catch (ClassCastException ex) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.to.consolidate.the.named.destinations.of.your.reader")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFont.java
catch(ClassCastException cce) { return -2; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Font.java
catch (ClassCastException cce) { return -3; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(ClassCastException cce) { }
4
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
catch (ClassCastException ex) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.to.consolidate.the.named.destinations.of.your.reader")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); }
1
unknown (Lib) ClassNotFoundException 0 0 1
            
// 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; }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.lang.ClassNotFoundException e ) { e.printStackTrace(); }
0 0
unknown (Lib) CloneNotSupportedException 0 0 0 10
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/RectangularShape.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Dimension2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Point2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/IntHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
10
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/RectangularShape.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Dimension2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Point2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/IntHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
0
unknown (Lib) DataFormatException 0 0 0 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch(DataFormatException dfe) { throw new ExceptionConverter(dfe); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch(DataFormatException dfe) { throw new ExceptionConverter(dfe); }
1
checked (Domain) DocumentException
public class DocumentException extends Exception {
	
	/** A serial version UID */
    private static final long serialVersionUID = -2191131489390840739L;

    /**
     * Creates a Document exception.
     * @param ex an exception that has to be turned into a DocumentException
     */
    public DocumentException(Exception ex) {
        super(ex);
    }
    
    // constructors
    
    /**
     * Constructs a <CODE>DocumentException</CODE> without a message.
     */
    public DocumentException() {
        super();
    }
    
    /**
     * Constructs a <code>DocumentException</code> with a message.
     *
     * @param		message			a message describing the exception
     */
    public DocumentException(String message) {
        super(message);
    }
}
91
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public void makeMask() throws DocumentException { if (!isMaskCandidate()) throw new DocumentException(MessageLocalization.getComposedMessage("this.image.can.not.be.an.image.mask")); mask = true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public void setImageMask(final Image mask) throws DocumentException { if (this.mask) throw new DocumentException(MessageLocalization.getComposedMessage("an.image.mask.cannot.contain.another.image.mask")); if (!mask.mask) throw new DocumentException(MessageLocalization.getComposedMessage("the.image.mask.is.not.a.mask.did.you.do.makemask")); imageMask = mask; smask = mask.bpc > 1 && mask.bpc <= 8; }
// 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/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 public PdfStream getFullFontStream() throws DocumentException { if (builtinFont || !embedded) return null; RandomAccessFileOrArray rf = null; try { String filePfb = fileName.substring(0, fileName.length() - 3) + "pfb"; if (pfb == null) rf = new RandomAccessFileOrArray(filePfb, true, Document.plainRandomAccess); else rf = new RandomAccessFileOrArray(pfb); int fileLength = (int)rf.length(); byte st[] = new byte[fileLength - 18]; int lengths[] = new int[3]; int bytePtr = 0; for (int k = 0; k < 3; ++k) { if (rf.read() != 0x80) throw new DocumentException(MessageLocalization.getComposedMessage("start.marker.missing.in.1", filePfb)); if (rf.read() != PFB_TYPES[k]) throw new DocumentException(MessageLocalization.getComposedMessage("incorrect.segment.type.in.1", filePfb)); int size = rf.read(); size += rf.read() << 8; size += rf.read() << 16; size += rf.read() << 24; lengths[k] = size; while (size != 0) { int got = rf.read(st, bytePtr, size); if (got < 0) throw new DocumentException(MessageLocalization.getComposedMessage("premature.end.in.1", filePfb)); bytePtr += got; size -= got; } } return new StreamFont(st, lengths, compressionLevel); } catch (Exception e) { throw new DocumentException(e); } finally { if (rf != null) { try { rf.close(); } catch (Exception e) { // empty on purpose } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
protected int goComposite(final boolean simulate) throws DocumentException { PdfDocument pdf = null; if (canvas != null) pdf = canvas.pdf; if (!rectangularMode) throw new DocumentException(MessageLocalization.getComposedMessage("irregular.columns.are.not.supported.in.composite.mode")); linesWritten = 0; descender = 0; boolean firstPass = true; main_loop: while (true) { if (compositeElements.isEmpty()) return NO_MORE_TEXT; Element element = compositeElements.getFirst(); if (element.type() == Element.PARAGRAPH) { Paragraph para = (Paragraph)element; int status = 0; for (int keep = 0; keep < 2; ++keep) { float lastY = yLine; boolean createHere = false; if (compositeColumn == null) { compositeColumn = new ColumnText(canvas); compositeColumn.setAlignment(para.getAlignment()); compositeColumn.setIndent(para.getIndentationLeft() + para.getFirstLineIndent(), false); compositeColumn.setExtraParagraphSpace(para.getExtraParagraphSpace()); compositeColumn.setFollowingIndent(para.getIndentationLeft()); compositeColumn.setRightIndent(para.getIndentationRight()); compositeColumn.setLeading(para.getLeading(), para.getMultipliedLeading()); compositeColumn.setRunDirection(runDirection); compositeColumn.setArabicOptions(arabicOptions); compositeColumn.setSpaceCharRatio(spaceCharRatio); compositeColumn.addText(para); if (!(firstPass && adjustFirstLine)) { yLine -= para.getSpacingBefore(); } createHere = true; } compositeColumn.setUseAscender((firstPass || descender == 0) && adjustFirstLine ? useAscender : false); compositeColumn.leftX = leftX; compositeColumn.rightX = rightX; compositeColumn.yLine = yLine; compositeColumn.rectangularWidth = rectangularWidth; compositeColumn.rectangularMode = rectangularMode; compositeColumn.minY = minY; compositeColumn.maxY = maxY; boolean keepCandidate = para.getKeepTogether() && createHere && !(firstPass && adjustFirstLine); boolean s = simulate || keepCandidate && keep == 0; if (isTagged(canvas) && !s) { canvas.openMCBlock(para); } status = compositeColumn.go(s); if (isTagged(canvas) && !s) { canvas.closeMCBlock(para); } lastX = compositeColumn.getLastX(); updateFilledWidth(compositeColumn.filledWidth); if ((status & NO_MORE_TEXT) == 0 && keepCandidate) { compositeColumn = null; yLine = lastY; return NO_MORE_COLUMN; } if (simulate || !keepCandidate) break; if (keep == 0) { compositeColumn = null; yLine = lastY; } } firstPass = false; if (compositeColumn.getLinesWritten() > 0) { yLine = compositeColumn.yLine; linesWritten += compositeColumn.linesWritten; descender = compositeColumn.descender; } currentLeading = compositeColumn.currentLeading; if ((status & NO_MORE_TEXT) != 0) { compositeColumn = null; compositeElements.removeFirst(); yLine -= para.getSpacingAfter(); } if ((status & NO_MORE_COLUMN) != 0) { return NO_MORE_COLUMN; } } else if (element.type() == Element.LIST) { com.itextpdf.text.List list = (com.itextpdf.text.List)element; ArrayList<Element> items = list.getItems(); ListItem item = null; float listIndentation = list.getIndentationLeft(); int count = 0; Stack<Object[]> stack = new Stack<Object[]>(); for (int k = 0; k < items.size(); ++k) { Object obj = items.get(k); if (obj instanceof ListItem) { if (count == listIdx) { item = (ListItem)obj; break; } else ++count; } else if (obj instanceof com.itextpdf.text.List) { stack.push(new Object[]{list, Integer.valueOf(k), new Float(listIndentation)}); list = (com.itextpdf.text.List)obj; items = list.getItems(); listIndentation += list.getIndentationLeft(); k = -1; continue; } if (k == items.size() - 1) { if (!stack.isEmpty()) { Object objs[] = stack.pop(); list = (com.itextpdf.text.List)objs[0]; items = list.getItems(); k = ((Integer)objs[1]).intValue(); listIndentation = ((Float)objs[2]).floatValue(); } } } int status = 0; for (int keep = 0; keep < 2; ++keep) { float lastY = yLine; boolean createHere = false; if (compositeColumn == null) { if (item == null) { listIdx = 0; compositeElements.removeFirst(); continue main_loop; } compositeColumn = new ColumnText(canvas); compositeColumn.setUseAscender((firstPass || descender == 0) && adjustFirstLine ? useAscender : false); compositeColumn.setAlignment(item.getAlignment()); compositeColumn.setIndent(item.getIndentationLeft() + listIndentation + item.getFirstLineIndent(), false); compositeColumn.setExtraParagraphSpace(item.getExtraParagraphSpace()); compositeColumn.setFollowingIndent(compositeColumn.getIndent()); compositeColumn.setRightIndent(item.getIndentationRight() + list.getIndentationRight()); compositeColumn.setLeading(item.getLeading(), item.getMultipliedLeading()); compositeColumn.setRunDirection(runDirection); compositeColumn.setArabicOptions(arabicOptions); compositeColumn.setSpaceCharRatio(spaceCharRatio); compositeColumn.addText(item); if (!(firstPass && adjustFirstLine)) { yLine -= item.getSpacingBefore(); } createHere = true; } compositeColumn.leftX = leftX; compositeColumn.rightX = rightX; compositeColumn.yLine = yLine; compositeColumn.rectangularWidth = rectangularWidth; compositeColumn.rectangularMode = rectangularMode; compositeColumn.minY = minY; compositeColumn.maxY = maxY; boolean keepCandidate = item.getKeepTogether() && createHere && !(firstPass && adjustFirstLine); boolean s = simulate || keepCandidate && keep == 0; if (isTagged(canvas) && !s) { item.getListLabel().setIndentation(listIndentation); if (list.getFirstItem() == item || (compositeColumn != null && compositeColumn.bidiLine != null)) canvas.openMCBlock(list); canvas.openMCBlock(item); } status = compositeColumn.go(simulate || keepCandidate && keep == 0, item); if (isTagged(canvas) && !s) { canvas.closeMCBlock(item.getListBody()); canvas.closeMCBlock(item); if ((list.getLastItem() == item && (status & NO_MORE_TEXT) != 0) || (status & NO_MORE_COLUMN) != 0) canvas.closeMCBlock(list); } lastX = compositeColumn.getLastX(); updateFilledWidth(compositeColumn.filledWidth); if ((status & NO_MORE_TEXT) == 0 && keepCandidate) { compositeColumn = null; yLine = lastY; return NO_MORE_COLUMN; } if (simulate || !keepCandidate) break; if (keep == 0) { compositeColumn = null; yLine = lastY; } } firstPass = false; yLine = compositeColumn.yLine; linesWritten += compositeColumn.linesWritten; descender = compositeColumn.descender; currentLeading = compositeColumn.currentLeading; if (!isTagged(canvas)) { if (!Float.isNaN(compositeColumn.firstLineY) && !compositeColumn.firstLineYDone) { if (!simulate) { showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(item.getListSymbol()), compositeColumn.leftX + listIndentation, compositeColumn.firstLineY, 0); } compositeColumn.firstLineYDone = true; } } if ((status & NO_MORE_TEXT) != 0) { compositeColumn = null; ++listIdx; yLine -= item.getSpacingAfter(); } if ((status & NO_MORE_COLUMN) != 0) return NO_MORE_COLUMN; } else if (element.type() == Element.PTABLE) { // INITIALISATIONS // get the PdfPTable element PdfPTable table = (PdfPTable)element; // tables without a body are dismissed if (table.size() <= table.getHeaderRows()) { compositeElements.removeFirst(); continue; } // Y-offset float yTemp = yLine; yTemp += descender; if (rowIdx == 0 && adjustFirstLine) yTemp -= table.spacingBefore(); // if there's no space left, ask for new column if (yTemp < minY || yTemp > maxY) return NO_MORE_COLUMN; // mark start of table float yLineWrite = yTemp; float x1 = leftX; currentLeading = 0; // get the width of the table float tableWidth; if (table.isLockedWidth()) { tableWidth = table.getTotalWidth(); updateFilledWidth(tableWidth); } else { tableWidth = rectangularWidth * table.getWidthPercentage() / 100f; table.setTotalWidth(tableWidth); } // HEADERS / FOOTERS // how many header rows are real header rows; how many are footer rows? table.normalizeHeadersFooters(); int headerRows = table.getHeaderRows(); int footerRows = table.getFooterRows(); int realHeaderRows = headerRows - footerRows; float headerHeight = table.getHeaderHeight(); float footerHeight = table.getFooterHeight(); // do we need to skip the header? boolean skipHeader = table.isSkipFirstHeader() && rowIdx <= realHeaderRows && (table.isComplete() || rowIdx != realHeaderRows); // if not, we wan't to be able to add more than just a header and a footer if (!skipHeader) { yTemp -= headerHeight; if (yTemp < minY || yTemp > maxY) { return NO_MORE_COLUMN; } } // MEASURE NECESSARY SPACE // how many real rows (not header or footer rows) fit on a page? int k = 0; if (rowIdx < headerRows) { rowIdx = headerRows; } // if the table isn't complete, we need to be able to add a footer if (!table.isComplete()) yTemp -= footerHeight; // k will be the first row that doesn't fit for (k = rowIdx; k < table.size(); ++k) { float rowHeight = table.getRowHeight(k); if (yTemp - rowHeight <= minY) break; yTemp -= rowHeight; } LOGGER.info("Want to split at row " + k); int kTemp = k; while (kTemp > rowIdx && kTemp < table.size() && table.getRow(kTemp).isMayNotBreak()) { kTemp--; } if ((kTemp > rowIdx && kTemp < k) || (kTemp == 0 && table.getRow(0).isMayNotBreak() && table.isLoopCheck())) { yTemp = minY; k = kTemp; table.setLoopCheck(false); } LOGGER.info("Will split at row " + k); // only for incomplete tables: if (!table.isComplete()) yTemp += footerHeight; // IF ROWS MAY NOT BE SPLIT if (!table.isSplitRows()) { splittedRow = -1; if (k == rowIdx) { // drop the whole table if (k == table.size()) { compositeElements.removeFirst(); continue; } // or drop the row else { table.getRows().remove(k); return NO_MORE_COLUMN; } } } // IF ROWS SHOULD NOT BE SPLIT else if (table.isSplitLate() && !table.hasRowspan(k) && rowIdx < k) { splittedRow = -1; } // SPLIT ROWS (IF WANTED AND NECESSARY) else if (k < table.size()) { // we calculate the remaining vertical space float h = yTemp - minY; // we create a new row with the remaining content PdfPRow newRow = table.getRow(k).splitRow(table, k, h); // if the row isn't null add it as an extra row if (newRow == null) { LOGGER.info("Didn't split row!"); splittedRow = -1; if (rowIdx == k) return NO_MORE_COLUMN; } else { // if the row hasn't been split before, we duplicate (part of) the table if (k != splittedRow) { splittedRow = k + 1; table = new PdfPTable(table); compositeElements.set(0, table); ArrayList<PdfPRow> rows = table.getRows(); for (int i = headerRows; i < rowIdx; ++i) rows.set(i, null); } yTemp = minY; table.getRows().add(++k, newRow); LOGGER.info("Inserting row at position " + k); } } // We're no longer in the first pass firstPass = false; // if not in simulation mode, draw the table if (!simulate) { // set the alignment switch (table.getHorizontalAlignment()) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: x1 += rectangularWidth - tableWidth; break; default: x1 += (rectangularWidth - tableWidth) / 2f; } // copy the rows that fit on the page in a new table nt PdfPTable nt = PdfPTable.shallowCopy(table); ArrayList<PdfPRow> sub = nt.getRows(); // first we add the real header rows (if necessary) if (!skipHeader && realHeaderRows > 0) { ArrayList<PdfPRow> rows = table.getRows(0, realHeaderRows); if (isTagged(canvas)) nt.getHeader().rows = rows; sub.addAll(rows); } else nt.setHeaderRows(footerRows); // then we add the real content { ArrayList<PdfPRow> rows = table.getRows(rowIdx, k); if (isTagged(canvas)) { nt.getBody().rows = rows; } sub.addAll(rows); } // do we need to show a footer? boolean showFooter = !table.isSkipLastFooter(); boolean newPageFollows = false; if (k < table.size()) { nt.setComplete(true); showFooter = true; newPageFollows = true; } // we add the footer rows if necessary (not for incomplete tables) if (footerRows > 0 && nt.isComplete() && showFooter) { ArrayList<PdfPRow> rows = table.getRows(realHeaderRows, realHeaderRows + footerRows); if (isTagged(canvas)) { nt.getFooter().rows = rows; } sub.addAll(rows); } else { footerRows = 0; } // we need a correction if the last row needs to be extended float rowHeight = 0; int lastIdx = sub.size() - 1 - footerRows; PdfPRow last = sub.get(lastIdx); if (table.isExtendLastRow(newPageFollows)) { rowHeight = last.getMaxHeights(); last.setMaxHeights(yTemp - minY + rowHeight); yTemp = minY; } // newPageFollows indicates that this table is being split if (newPageFollows) { PdfPTableEvent tableEvent = table.getTableEvent(); if (tableEvent instanceof PdfPTableEventSplit) { ((PdfPTableEventSplit)tableEvent).splitTable(table); } } // now we render the rows of the new table if (canvases != null) { if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].openMCBlock(table); } nt.writeSelectedRows(0, -1, 0, -1, x1, yLineWrite, canvases, false); if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].closeMCBlock(table); } } else { if (isTagged(canvas)) { canvas.openMCBlock(table); } nt.writeSelectedRows(0, -1, 0, -1, x1, yLineWrite, canvas, false); if (isTagged(canvas)) { canvas.closeMCBlock(table); } } // if the row was split, we copy the content of the last row // that was consumed into the first row shown on the next page if (splittedRow == k && k < table.size()) { PdfPRow splitted = table.getRows().get(k); splitted.copyRowContent(nt, lastIdx); } // reset the row height of the last row if (table.isExtendLastRow(newPageFollows)) { last.setMaxHeights(rowHeight); } } // in simulation mode, we need to take extendLastRow into account else if (table.isExtendLastRow() && minY > PdfPRow.BOTTOM_LIMIT) { yTemp = minY; } yLine = yTemp; descender = 0; currentLeading = 0; if (!(skipHeader || table.isComplete())) yLine += footerHeight; while (k < table.size()) { if (table.getRowHeight(k) > 0 || table.hasRowspan(k)) { break; } k++; } if (k >= table.size()) { // Use up space no more than left if(yLine - table.spacingAfter() < minY) { yLine = minY; } else { yLine -= table.spacingAfter(); } compositeElements.removeFirst(); splittedRow = -1; rowIdx = 0; } else { if (splittedRow != -1) { ArrayList<PdfPRow> rows = table.getRows(); for (int i = rowIdx; i < k; ++i) rows.set(i, null); } rowIdx = k; return NO_MORE_COLUMN; } } else if (element.type() == Element.YMARK) { if (!simulate) { DrawInterface zh = (DrawInterface)element; zh.draw(canvas, leftX, minY, rightX, maxY, yLine); } compositeElements.removeFirst(); } else if (element.type() == Element.DIV) { ArrayList<Element> floatingElements = new ArrayList<Element>(); do { floatingElements.add(element); compositeElements.removeFirst(); element = !compositeElements.isEmpty() ? compositeElements.getFirst() : null; } while (element != null && element.type() == Element.DIV); FloatLayout fl = new FloatLayout(floatingElements, useAscender); fl.setSimpleColumn(leftX, minY, rightX, yLine); int status = fl.layout(canvas, simulate); //firstPass = false; yLine = fl.getYLine(); descender = 0; if ((status & NO_MORE_TEXT) == 0) { compositeElements.addAll(floatingElements); return status; } } else compositeElements.removeFirst(); } }
// 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
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/PdfPages.java
int reorderPages(int order[]) throws DocumentException { if (order == null) return pages.size(); if (parents.size() > 1) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.a.single.parent.in.the.page.tree.call.pdfwriter.setlinearmode.after.open")); if (order.length != pages.size()) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.an.array.with.the.same.size.as.the.number.of.pages")); int max = pages.size(); boolean temp[] = new boolean[max]; for (int k = 0; k < max; ++k) { int p = order[k]; if (p < 1 || p > max) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.pages.between.1.and.1.found.2", String.valueOf(max), String.valueOf(p))); if (temp[p - 1]) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.no.page.repetition.page.1.is.repeated", p)); temp[p - 1] = true; } PdfIndirectReference copy[] = pages.toArray(new PdfIndirectReference[pages.size()]); for (int k = 0; k < max; ++k) { pages.set(k, copy[order[k] - 1]); } return max; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setInitialLeading(final float leading) throws DocumentException { if (open) throw new DocumentException(MessageLocalization.getComposedMessage("you.can.t.set.the.initial.leading.if.the.document.is.already.open")); pdf.setLeading(leading); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setAdditionalAction(final PdfName actionType, final PdfAction action) throws DocumentException { if (!(actionType.equals(DOCUMENT_CLOSE) || actionType.equals(WILL_SAVE) || actionType.equals(DID_SAVE) || actionType.equals(WILL_PRINT) || actionType.equals(DID_PRINT))) { throw new DocumentException(MessageLocalization.getComposedMessage("invalid.additional.action.type.1", actionType.toString())); } pdf.addAdditionalAction(actionType, action); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final int encryptionType) throws DocumentException { if (pdf.isOpen()) throw new DocumentException(MessageLocalization.getComposedMessage("encryption.can.only.be.added.before.opening.the.document")); crypto = new PdfEncryption(); crypto.setCryptoMode(encryptionType, 0); crypto.setupAllKeys(userPassword, ownerPassword, permissions); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setEncryption(final Certificate[] certs, final int[] permissions, final int encryptionType) throws DocumentException { if (pdf.isOpen()) throw new DocumentException(MessageLocalization.getComposedMessage("encryption.can.only.be.added.before.opening.the.document")); crypto = new PdfEncryption(); if (certs != null) { for (int i=0; i < certs.length; i++) { crypto.addRecipient(certs[i], permissions[i]); } } crypto.setCryptoMode(encryptionType, 0); crypto.getEncryptionDictionary(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setPageAction(final PdfName actionType, final PdfAction action) throws DocumentException { if (!actionType.equals(PAGE_OPEN) && !actionType.equals(PAGE_CLOSE)) throw new DocumentException(MessageLocalization.getComposedMessage("invalid.page.additional.action.type.1", actionType.toString())); pdf.setPageAction(actionType, action); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setUserunit(final float userunit) throws DocumentException { if (userunit < 1f || userunit > 75000f) throw new DocumentException(MessageLocalization.getComposedMessage("userunit.should.be.a.value.between.1.and.75000")); addPageDictEntry(PdfName.USERUNIT, new PdfNumber(userunit)); setAtLeastPdfVersion(VERSION_1_6); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfName addDirectImageSimple(final Image image, final PdfIndirectReference fixedRef) throws PdfException, DocumentException { PdfName name; // if the images is already added, just retrieve the name if (images.containsKey(image.getMySerialId())) { name = images.get(image.getMySerialId()); } // if it's a new image, add it to the document else { if (image.isImgTemplate()) { name = new PdfName("img" + images.size()); if(image instanceof ImgWMF){ try { ImgWMF wmf = (ImgWMF)image; wmf.readWMF(PdfTemplate.createTemplate(this, 0, 0)); } catch (Exception e) { throw new DocumentException(e); } } } else { PdfIndirectReference dref = image.getDirectReference(); if (dref != null) { PdfName rname = new PdfName("img" + images.size()); images.put(image.getMySerialId(), rname); imageDictionary.put(rname, dref); return rname; } Image maskImage = image.getImageMask(); PdfIndirectReference maskRef = null; if (maskImage != null) { PdfName mname = images.get(maskImage.getMySerialId()); maskRef = getImageReference(mname); } PdfImage i = new PdfImage(image, "img" + images.size(), maskRef); if (image instanceof ImgJBIG2) { byte[] globals = ((ImgJBIG2) image).getGlobalBytes(); if (globals != null) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.put(PdfName.JBIG2GLOBALS, getReferenceJBIG2Globals(globals)); i.put(PdfName.DECODEPARMS, decodeparms); } } if (image.hasICCProfile()) { PdfICCBased icc = new PdfICCBased(image.getICCProfile(), image.getCompressionLevel()); PdfIndirectReference iccRef = add(icc); PdfArray iccArray = new PdfArray(); iccArray.add(PdfName.ICCBASED); iccArray.add(iccRef); PdfArray colorspace = i.getAsArray(PdfName.COLORSPACE); if (colorspace != null) { if (colorspace.size() > 1 && PdfName.INDEXED.equals(colorspace.getPdfObject(0))) colorspace.set(1, iccArray); else i.put(PdfName.COLORSPACE, iccArray); } else i.put(PdfName.COLORSPACE, iccArray); } add(i, fixedRef); name = i.name(); } images.put(image.getMySerialId(), name); } return name; }
// 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 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/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/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/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/PdfContentByte.java
public void addImage(final Image image, final boolean inlineImage) throws DocumentException { if (!image.hasAbsoluteY()) throw new DocumentException(MessageLocalization.getComposedMessage("the.image.must.have.absolute.positioning")); float matrix[] = image.matrix(); matrix[Image.CX] = image.getAbsoluteX() - matrix[Image.CX]; matrix[Image.CY] = image.getAbsoluteY() - matrix[Image.CY]; addImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], inlineImage); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final float a, final float b, final float c, final float d, final float e, final float f, final boolean inlineImage) throws DocumentException { try { if (image.getLayer() != null) beginLayer(image.getLayer()); if (inText && isTagged()) { endText(); } if (writer != null && image.isImgTemplate()) { writer.addDirectImageSimple(image); PdfTemplate template = image.getTemplateData(); float w = template.getWidth(); float h = template.getHeight(); addTemplate(template, a / w, b / w, c / h, d / h, e, f); } else { content.append("q "); content.append(a).append(' '); content.append(b).append(' '); content.append(c).append(' '); content.append(d).append(' '); content.append(e).append(' '); content.append(f).append(" cm"); if (inlineImage) { content.append("\nBI\n"); PdfImage pimage = new PdfImage(image, "", null); if (image instanceof ImgJBIG2) { byte[] globals = ((ImgJBIG2)image).getGlobalBytes(); if (globals != null) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.put(PdfName.JBIG2GLOBALS, writer.getReferenceJBIG2Globals(globals)); pimage.put(PdfName.DECODEPARMS, decodeparms); } } for (Object element : pimage.getKeys()) { PdfName key = (PdfName)element; PdfObject value = pimage.get(key); String s = abrev.get(key); if (s == null) continue; content.append(s); boolean check = true; if (key.equals(PdfName.COLORSPACE) && value.isArray()) { PdfArray ar = (PdfArray)value; if (ar.size() == 4 && PdfName.INDEXED.equals(ar.getAsName(0)) && ar.getPdfObject(1).isName() && ar.getPdfObject(2).isNumber() && ar.getPdfObject(3).isString() ) { check = false; } } if (check && key.equals(PdfName.COLORSPACE) && !value.isName()) { PdfName cs = writer.getColorspaceName(); PageResources prs = getPageResources(); prs.addColor(cs, writer.addToBody(value).getIndirectReference()); value = cs; } value.toPdf(null, content); content.append('\n'); } content.append("ID\n"); pimage.writeContent(content); content.append("\nEI\nQ").append_i(separator); } else { PdfName name; PageResources prs = getPageResources(); Image maskImage = image.getImageMask(); if (maskImage != null) { name = writer.addDirectImageSimple(maskImage); prs.addXObject(name, writer.getImageReference(name)); } name = writer.addDirectImageSimple(image); name = prs.addXObject(name, writer.getImageReference(name)); content.append(' ').append(name.getBytes()).append(" Do Q").append_i(separator); } } if (image.hasBorders()) { saveState(); float w = image.getWidth(); float h = image.getHeight(); concatCTM(a / w, b / w, c / h, d / h, e, f); rectangle(image); restoreState(); } if (image.getLayer() != null) endLayer(); Annotation annot = image.getAnnotation(); if (annot == null) return; float[] r = new float[unitRect.length]; for (int k = 0; k < unitRect.length; k += 2) { r[k] = a * unitRect[k] + c * unitRect[k + 1] + e; r[k + 1] = b * unitRect[k] + d * unitRect[k + 1] + f; } float llx = r[0]; float lly = r[1]; float urx = llx; float ury = lly; for (int k = 2; k < r.length; k += 2) { llx = Math.min(llx, r[k]); lly = Math.min(lly, r[k + 1]); urx = Math.max(urx, r[k]); ury = Math.max(ury, r[k + 1]); } annot = new Annotation(annot); annot.setDimensions(llx, lly, urx, ury); PdfAnnotation an = PdfAnnotationsImp.convertAnnotation(writer, annot, new Rectangle(llx, lly, urx, ury)); if (an == null) return; addAnnotation(an); } catch (Exception ee) { throw new DocumentException(ee); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
public void addWriter(final PdfWriter writer) throws DocumentException { if (this.writer == null) { this.writer = writer; annotationsImp = new PdfAnnotationsImp(writer); return; } throw new DocumentException(MessageLocalization.getComposedMessage("you.can.only.add.a.writer.to.a.pdfdocument.once")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public boolean add(final Element element) throws DocumentException { if (writer != null && writer.isPaused()) { return false; } try { if (element.type() != Element.DIV) { flushFloatingElements(); } // TODO refactor this uber long switch to State/Strategy or something ... switch(element.type()) { // Information (headers) case Element.HEADER: info.addkey(((Meta)element).getName(), ((Meta)element).getContent()); break; case Element.TITLE: info.addTitle(((Meta)element).getContent()); break; case Element.SUBJECT: info.addSubject(((Meta)element).getContent()); break; case Element.KEYWORDS: info.addKeywords(((Meta)element).getContent()); break; case Element.AUTHOR: info.addAuthor(((Meta)element).getContent()); break; case Element.CREATOR: info.addCreator(((Meta)element).getContent()); break; case Element.LANGUAGE: setLanguage(((Meta)element).getContent()); break; case Element.PRODUCER: // you can not change the name of the producer info.addProducer(); break; case Element.CREATIONDATE: // you can not set the creation date, only reset it info.addCreationDate(); break; // content (text) case Element.CHUNK: { // if there isn't a current line available, we make one if (line == null) { carriageReturn(); } // we cast the element to a chunk PdfChunk chunk = new PdfChunk((Chunk) element, anchorAction); // we try to add the chunk to the line, until we succeed { PdfChunk overflow; while ((overflow = line.add(chunk)) != null) { carriageReturn(); boolean newlineSplit = chunk.isNewlineSplit(); chunk = overflow; if (!newlineSplit) chunk.trimFirstSpace(); } } pageEmpty = false; if (chunk.isAttribute(Chunk.NEWPAGE)) { newPage(); } break; } case Element.ANCHOR: { leadingCount++; Anchor anchor = (Anchor) element; String url = anchor.getReference(); leading = anchor.getLeading(); if (url != null) { anchorAction = new PdfAction(url); } // we process the element element.process(this); anchorAction = null; leadingCount--; break; } case Element.ANNOTATION: { if (line == null) { carriageReturn(); } Annotation annot = (Annotation) element; Rectangle rect = new Rectangle(0, 0); if (line != null) rect = new Rectangle(annot.llx(indentRight() - line.widthLeft()), annot.ury(indentTop() - currentHeight - 20), annot.urx(indentRight() - line.widthLeft() + 20), annot.lly(indentTop() - currentHeight)); PdfAnnotation an = PdfAnnotationsImp.convertAnnotation(writer, annot, rect); annotationsImp.addPlainAnnotation(an); pageEmpty = false; break; } case Element.PHRASE: { leadingCount++; // we cast the element to a phrase and set the leading of the document leading = ((Phrase) element).getTotalLeading(); // we process the element element.process(this); leadingCount--; break; } case Element.PARAGRAPH: { leadingCount++; // we cast the element to a paragraph Paragraph paragraph = (Paragraph) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(paragraph); } addSpacing(paragraph.getSpacingBefore(), leading, paragraph.getFont()); // we adjust the parameters of the document alignment = paragraph.getAlignment(); leading = paragraph.getTotalLeading(); carriageReturn(); // we don't want to make orphans/widows if (currentHeight + line.height() + leading > indentTop() - indentBottom()) { newPage(); } indentation.indentLeft += paragraph.getIndentationLeft(); indentation.indentRight += paragraph.getIndentationRight(); carriageReturn(); PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null && !isSectionTitle) pageEvent.onParagraph(writer, this, indentTop() - currentHeight); // if a paragraph has to be kept together, we wrap it in a table object if (paragraph.getKeepTogether()) { carriageReturn(); PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100f); PdfPCell cell = new PdfPCell(); cell.addElement(paragraph); cell.setBorder(Rectangle.NO_BORDER); cell.setPadding(0); table.addCell(cell); indentation.indentLeft -= paragraph.getIndentationLeft(); indentation.indentRight -= paragraph.getIndentationRight(); this.add(table); indentation.indentLeft += paragraph.getIndentationLeft(); indentation.indentRight += paragraph.getIndentationRight(); } else { line.setExtraIndent(paragraph.getFirstLineIndent()); element.process(this); carriageReturn(); addSpacing(paragraph.getSpacingAfter(), paragraph.getTotalLeading(), paragraph.getFont()); } if (pageEvent != null && !isSectionTitle) pageEvent.onParagraphEnd(writer, this, indentTop() - currentHeight); alignment = Element.ALIGN_LEFT; indentation.indentLeft -= paragraph.getIndentationLeft(); indentation.indentRight -= paragraph.getIndentationRight(); carriageReturn(); leadingCount--; if (isTagged(writer)) { flushLines(); text.closeMCBlock(paragraph); } break; } case Element.SECTION: case Element.CHAPTER: { // Chapters and Sections only differ in their constructor // so we cast both to a Section Section section = (Section) element; PdfPageEvent pageEvent = writer.getPageEvent(); boolean hasTitle = section.isNotAddedYet() && section.getTitle() != null; // if the section is a chapter, we begin a new page if (section.isTriggerNewPage()) { newPage(); } if (hasTitle) { float fith = indentTop() - currentHeight; int rotation = pageSize.getRotation(); if (rotation == 90 || rotation == 180) fith = pageSize.getHeight() - fith; PdfDestination destination = new PdfDestination(PdfDestination.FITH, fith); while (currentOutline.level() >= section.getDepth()) { currentOutline = currentOutline.parent(); } PdfOutline outline = new PdfOutline(currentOutline, destination, section.getBookmarkTitle(), section.isBookmarkOpen()); currentOutline = outline; } // some values are set carriageReturn(); indentation.sectionIndentLeft += section.getIndentationLeft(); indentation.sectionIndentRight += section.getIndentationRight(); if (section.isNotAddedYet() && pageEvent != null) if (element.type() == Element.CHAPTER) pageEvent.onChapter(writer, this, indentTop() - currentHeight, section.getTitle()); else pageEvent.onSection(writer, this, indentTop() - currentHeight, section.getDepth(), section.getTitle()); // the title of the section (if any has to be printed) if (hasTitle) { isSectionTitle = true; add(section.getTitle()); isSectionTitle = false; } indentation.sectionIndentLeft += section.getIndentation(); // we process the section element.process(this); flushLines(); // some parameters are set back to normal again indentation.sectionIndentLeft -= section.getIndentationLeft() + section.getIndentation(); indentation.sectionIndentRight -= section.getIndentationRight(); if (section.isComplete() && pageEvent != null) if (element.type() == Element.CHAPTER) pageEvent.onChapterEnd(writer, this, indentTop() - currentHeight); else pageEvent.onSectionEnd(writer, this, indentTop() - currentHeight); break; } case Element.LIST: { // we cast the element to a List List list = (List) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(list); } if (list.isAlignindent()) { list.normalizeIndentation(); } // we adjust the document indentation.listIndentLeft += list.getIndentationLeft(); indentation.indentRight += list.getIndentationRight(); // we process the items in the list element.process(this); // some parameters are set back to normal again indentation.listIndentLeft -= list.getIndentationLeft(); indentation.indentRight -= list.getIndentationRight(); carriageReturn(); if (isTagged(writer)) { flushLines(); text.closeMCBlock(list); } break; } case Element.LISTITEM: { leadingCount++; // we cast the element to a ListItem ListItem listItem = (ListItem) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(listItem); } addSpacing(listItem.getSpacingBefore(), leading, listItem.getFont()); // we adjust the document alignment = listItem.getAlignment(); indentation.listIndentLeft += listItem.getIndentationLeft(); indentation.indentRight += listItem.getIndentationRight(); leading = listItem.getTotalLeading(); carriageReturn(); // we prepare the current line to be able to show us the listsymbol line.setListItem(listItem); // we process the item element.process(this); addSpacing(listItem.getSpacingAfter(), listItem.getTotalLeading(), listItem.getFont()); // if the last line is justified, it should be aligned to the left if (line.hasToBeJustified()) { line.resetAlignment(); } // some parameters are set back to normal again carriageReturn(); indentation.listIndentLeft -= listItem.getIndentationLeft(); indentation.indentRight -= listItem.getIndentationRight(); leadingCount--; if (isTagged(writer)) { flushLines(); text.closeMCBlock(listItem.getListBody()); text.closeMCBlock(listItem); } break; } case Element.RECTANGLE: { Rectangle rectangle = (Rectangle) element; graphics.rectangle(rectangle); pageEmpty = false; break; } case Element.PTABLE: { PdfPTable ptable = (PdfPTable)element; if (ptable.size() <= ptable.getHeaderRows()) break; //nothing to do // before every table, we add a new line and flush all lines ensureNewLine(); flushLines(); addPTable(ptable); pageEmpty = false; newLine(); break; } case Element.JPEG: case Element.JPEG2000: case Element.JBIG2: case Element.IMGRAW: case Element.IMGTEMPLATE: { //carriageReturn(); suggestion by Marc Campforts add((Image) element); break; } case Element.YMARK: { DrawInterface zh = (DrawInterface)element; zh.draw(graphics, indentLeft(), indentBottom(), indentRight(), indentTop(), indentTop() - currentHeight - (leadingCount > 0 ? leading : 0)); pageEmpty = false; break; } case Element.MARKED: { MarkedObject mo; if (element instanceof MarkedSection) { mo = ((MarkedSection)element).getTitle(); if (mo != null) { mo.process(this); } } mo = (MarkedObject)element; mo.process(this); break; } case Element.WRITABLE_DIRECT: if (null != writer) { ((WriterOperation)element).write(writer, this); } break; case Element.DIV: ensureNewLine(); flushLines(); addDiv((PdfDiv)element); pageEmpty = false; //newLine(); break; default: return false; } lastElementType = element.type(); return true; } catch(Exception e) { throw new DocumentException(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addPTable(final PdfPTable ptable) throws DocumentException { ColumnText ct = new ColumnText(isTagged(writer) ? text : writer.getDirectContent()); // if the table prefers to be on a single page, and it wouldn't //fit on the current page, start a new page. if (ptable.getKeepTogether() && !fitsPage(ptable, 0f) && currentHeight > 0) { newPage(); } if (currentHeight == 0) { ct.setAdjustFirstLine(false); } ct.addElement(ptable); boolean he = ptable.isHeadersInEvent(); ptable.setHeadersInEvent(true); int loop = 0; while (true) { ct.setSimpleColumn(indentLeft(), indentBottom(), indentRight(), indentTop() - currentHeight); int status = ct.go(); if ((status & ColumnText.NO_MORE_TEXT) != 0) { if (isTagged(writer)) { text.setTextMatrix(indentLeft(), ct.getYLine()); } else { text.moveText(0, ct.getYLine() - indentTop() + currentHeight); } currentHeight = indentTop() - ct.getYLine(); break; } if (indentTop() - currentHeight == ct.getYLine()) ++loop; else loop = 0; if (loop == 3) { throw new DocumentException(MessageLocalization.getComposedMessage("infinite.table.loop")); } newPage(); if (isTagged(writer)) { ct.setCanvas(text); } } ptable.setHeadersInEvent(he); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type3Glyph.java
public void addImage(Image image, float a, float b, float c, float d, float e, float f, boolean inlineImage) throws DocumentException { if (!colorized && (!image.isMask() || !(image.getBpc() == 1 || image.getBpc() > 0xff))) throw new DocumentException(MessageLocalization.getComposedMessage("not.colorized.typed3.fonts.only.accept.mask.images")); super.addImage(image, a, b, c, d, e, f, inlineImage); }
// 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/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/PdfCopyFormsImp.java
public void copyDocumentFields(PdfReader reader) throws DocumentException { if (!reader.isOpenedWithFullPermissions()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password")); 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()); fields.add(reader.getAcroFields()); updateCalculationOrder(reader); }
// 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 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/CJKFont.java
private void loadCMaps() throws DocumentException { try { fontDesc = allFonts.get(fontName); hMetrics = (IntHashtable)fontDesc.get("W"); vMetrics = (IntHashtable)fontDesc.get("W2"); String registry = (String)fontDesc.get("Registry"); uniMap = ""; for (String name : registryNames.get(registry + "_Uni")) { uniMap = name; if (name.endsWith("V") && vertical) break; if (!name.endsWith("V") && !vertical) break; } if (cidDirect) { cidUni = CMapCache.getCachedCMapCidUni(uniMap); } else { uniCid = CMapCache.getCachedCMapUniCid(uniMap); cidByte = CMapCache.getCachedCMapCidByte(CMap); } } catch (Exception ex) { throw new DocumentException(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setWidths(final float relativeWidths[]) throws DocumentException { if (relativeWidths.length != getNumberOfColumns()) throw new DocumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); this.relativeWidths = new float[relativeWidths.length]; System.arraycopy(relativeWidths, 0, this.relativeWidths, 0, relativeWidths.length); absoluteWidths = new float[relativeWidths.length]; totalHeight = 0; calculateWidths(); calculateHeights(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setTotalWidth(final float columnWidth[]) throws DocumentException { if (columnWidth.length != getNumberOfColumns()) throw new DocumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); totalWidth = 0; for (int k = 0; k < columnWidth.length; ++k) totalWidth += columnWidth[k]; setWidths(columnWidth); }
// 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 setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final boolean strength128Bits) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(userPassword, ownerPassword, permissions, strength128Bits ? PdfWriter.STANDARD_ENCRYPTION_128 : PdfWriter.STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final int encryptionType) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(userPassword, ownerPassword, permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final Certificate[] certs, final int[] permissions, final int encryptionType) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(certs, permissions, encryptionType); }
// 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/Document.java
public boolean add(Element element) throws DocumentException { if (close) { throw new DocumentException(MessageLocalization.getComposedMessage("the.document.has.been.closed.you.can.t.add.any.elements")); } if (!open && element.isContent()) { throw new DocumentException(MessageLocalization.getComposedMessage("the.document.is.not.open.yet.you.can.only.add.meta.information")); } boolean success = false; if (element instanceof ChapterAutoNumber) { chapternumber = ((ChapterAutoNumber)element).setAutomaticNumber(chapternumber); } for (DocListener listener : listeners) { success |= listener.add(element); } if (element instanceof LargeElement) { LargeElement e = (LargeElement)element; if (!e.isComplete()) e.flushContent(); } return success; }
7
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception ee) { throw new DocumentException(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new DocumentException(ex); }
212
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public void makeMask() throws DocumentException { if (!isMaskCandidate()) throw new DocumentException(MessageLocalization.getComposedMessage("this.image.can.not.be.an.image.mask")); mask = true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public void setImageMask(final Image mask) throws DocumentException { if (this.mask) throw new DocumentException(MessageLocalization.getComposedMessage("an.image.mask.cannot.contain.another.image.mask")); if (!mask.mask) throw new DocumentException(MessageLocalization.getComposedMessage("the.image.mask.is.not.a.mask.did.you.do.makemask")); imageMask = mask; smask = mask.bpc > 1 && mask.bpc <= 8; }
// 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/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/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/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/PdfCopyFields.java
public void setEncryption(byte userPassword[], byte ownerPassword[], int permissions, boolean strength128Bits) throws DocumentException { fc.setEncryption(userPassword, ownerPassword, permissions, strength128Bits ? PdfWriter.STANDARD_ENCRYPTION_128 : PdfWriter.STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFields.java
public void setEncryption(boolean strength, String userPassword, String ownerPassword, int permissions) throws DocumentException { setEncryption(DocWriter.getISOBytes(userPassword), DocWriter.getISOBytes(ownerPassword), permissions, strength); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFields.java
public void setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType) throws DocumentException { fc.setEncryption(userPassword, ownerPassword, permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFields.java
public void setEncryption(Certificate[] certs, int[] permissions, int encryptionType) throws DocumentException { fc.setEncryption(certs, permissions, encryptionType); }
// 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 public PdfStream getFullFontStream() throws DocumentException { if (builtinFont || !embedded) return null; RandomAccessFileOrArray rf = null; try { String filePfb = fileName.substring(0, fileName.length() - 3) + "pfb"; if (pfb == null) rf = new RandomAccessFileOrArray(filePfb, true, Document.plainRandomAccess); else rf = new RandomAccessFileOrArray(pfb); int fileLength = (int)rf.length(); byte st[] = new byte[fileLength - 18]; int lengths[] = new int[3]; int bytePtr = 0; for (int k = 0; k < 3; ++k) { if (rf.read() != 0x80) throw new DocumentException(MessageLocalization.getComposedMessage("start.marker.missing.in.1", filePfb)); if (rf.read() != PFB_TYPES[k]) throw new DocumentException(MessageLocalization.getComposedMessage("incorrect.segment.type.in.1", filePfb)); int size = rf.read(); size += rf.read() << 8; size += rf.read() << 16; size += rf.read() << 24; lengths[k] = size; while (size != 0) { int got = rf.read(st, bytePtr, size); if (got < 0) throw new DocumentException(MessageLocalization.getComposedMessage("premature.end.in.1", filePfb)); bytePtr += got; size -= got; } } return new StreamFont(st, lengths, compressionLevel); } catch (Exception e) { throw new DocumentException(e); } finally { if (rf != null) { try { rf.close(); } catch (Exception e) { // empty on purpose } } } }
// 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/ColumnText.java
public int go() throws DocumentException { return go(false); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public int go(final boolean simulate) throws DocumentException { return go(simulate, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public int go(final boolean simulate, final IAccessibleElement elementToGo) throws DocumentException { if (composite) return goComposite(simulate); ListBody lBody = null; if (isTagged(canvas) && elementToGo instanceof ListItem) { lBody = ((ListItem)elementToGo).getListBody(); } addWaitingPhrase(); if (bidiLine == null) return NO_MORE_TEXT; descender = 0; linesWritten = 0; lastX = 0; boolean dirty = false; float ratio = spaceCharRatio; Object currentValues[] = new Object[2]; PdfFont currentFont = null; Float lastBaseFactor = new Float(0); currentValues[1] = lastBaseFactor; PdfDocument pdf = null; PdfContentByte graphics = null; PdfContentByte text = null; firstLineY = Float.NaN; int localRunDirection = PdfWriter.RUN_DIRECTION_NO_BIDI; if (runDirection != PdfWriter.RUN_DIRECTION_DEFAULT) localRunDirection = runDirection; if (canvas != null) { graphics = canvas; pdf = canvas.getPdfDocument(); if (!isTagged(canvas)) text = canvas.getDuplicate(); else text = canvas; } else if (!simulate) throw new NullPointerException(MessageLocalization.getComposedMessage("columntext.go.with.simulate.eq.eq.false.and.text.eq.eq.null")); if (!simulate) { if (ratio == GLOBAL_SPACE_CHAR_RATIO) ratio = text.getPdfWriter().getSpaceCharRatio(); else if (ratio < 0.001f) ratio = 0.001f; } if (!rectangularMode) { float max = 0; for (PdfChunk c : bidiLine.chunks) { max = Math.max(max, c.font.size()); } currentLeading = fixedLeading + max * multipliedLeading; } float firstIndent = 0; PdfLine line; float x1; int status = 0; while(true) { firstIndent = lastWasNewline ? indent : followingIndent; // if (rectangularMode) { if (rectangularWidth <= firstIndent + rightIndent) { status = NO_MORE_COLUMN; if (bidiLine.isEmpty()) status |= NO_MORE_TEXT; break; } if (bidiLine.isEmpty()) { status = NO_MORE_TEXT; break; } line = bidiLine.processLine(leftX, rectangularWidth - firstIndent - rightIndent, alignment, localRunDirection, arabicOptions, minY, yLine, descender); if (line == null) { status = NO_MORE_TEXT; break; } float[] maxSize = line.getMaxSize(fixedLeading, multipliedLeading); if (isUseAscender() && Float.isNaN(firstLineY)) currentLeading = line.getAscender(); else currentLeading = Math.max(maxSize[0], maxSize[1] - descender); if (yLine > maxY || yLine - currentLeading < minY ) { status = NO_MORE_COLUMN; bidiLine.restore(); break; } yLine -= currentLeading; if (!simulate && !dirty) { text.beginText(); dirty = true; } if (Float.isNaN(firstLineY)) firstLineY = yLine; updateFilledWidth(rectangularWidth - line.widthLeft()); x1 = leftX; } else { float yTemp = yLine - currentLeading; float xx[] = findLimitsTwoLines(); if (xx == null) { status = NO_MORE_COLUMN; if (bidiLine.isEmpty()) status |= NO_MORE_TEXT; yLine = yTemp; break; } if (bidiLine.isEmpty()) { status = NO_MORE_TEXT; yLine = yTemp; break; } x1 = Math.max(xx[0], xx[2]); float x2 = Math.min(xx[1], xx[3]); if (x2 - x1 <= firstIndent + rightIndent) continue; if (!simulate && !dirty) { text.beginText(); dirty = true; } line = bidiLine.processLine(x1, x2 - x1 - firstIndent - rightIndent, alignment, localRunDirection, arabicOptions, minY, yLine, descender); if (line == null) { status = NO_MORE_TEXT; yLine = yTemp; break; } } if (isTagged(canvas) && elementToGo instanceof ListItem) { if (!Float.isNaN(firstLineY) && !firstLineYDone) { if (!simulate) { ListLabel lbl = ((ListItem)elementToGo).getListLabel(); canvas.openMCBlock(lbl); Chunk symbol = new Chunk(((ListItem)elementToGo).getListSymbol()); if (!lbl.getTagLabelContent()) { symbol.setRole(null); } ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(symbol), leftX + lbl.getIndentation(), firstLineY, 0); canvas.closeMCBlock(lbl); } firstLineYDone = true; } } if (!simulate) { if (lBody != null) { canvas.openMCBlock(lBody); lBody = null; } currentValues[0] = currentFont; text.setTextMatrix(x1 + (line.isRTL() ? rightIndent : firstIndent) + line.indentLeft(), yLine); lastX = pdf.writeLineToContent(line, text, graphics, currentValues, ratio); currentFont = (PdfFont)currentValues[0]; } lastWasNewline = repeatFirstLineIndent && line.isNewlineSplit(); yLine -= line.isNewlineSplit() ? extraParagraphSpace : 0; ++linesWritten; descender = line.getDescender(); } if (dirty) { text.endText(); if (canvas != text) canvas.add(text); } return status; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
protected int goComposite(final boolean simulate) throws DocumentException { PdfDocument pdf = null; if (canvas != null) pdf = canvas.pdf; if (!rectangularMode) throw new DocumentException(MessageLocalization.getComposedMessage("irregular.columns.are.not.supported.in.composite.mode")); linesWritten = 0; descender = 0; boolean firstPass = true; main_loop: while (true) { if (compositeElements.isEmpty()) return NO_MORE_TEXT; Element element = compositeElements.getFirst(); if (element.type() == Element.PARAGRAPH) { Paragraph para = (Paragraph)element; int status = 0; for (int keep = 0; keep < 2; ++keep) { float lastY = yLine; boolean createHere = false; if (compositeColumn == null) { compositeColumn = new ColumnText(canvas); compositeColumn.setAlignment(para.getAlignment()); compositeColumn.setIndent(para.getIndentationLeft() + para.getFirstLineIndent(), false); compositeColumn.setExtraParagraphSpace(para.getExtraParagraphSpace()); compositeColumn.setFollowingIndent(para.getIndentationLeft()); compositeColumn.setRightIndent(para.getIndentationRight()); compositeColumn.setLeading(para.getLeading(), para.getMultipliedLeading()); compositeColumn.setRunDirection(runDirection); compositeColumn.setArabicOptions(arabicOptions); compositeColumn.setSpaceCharRatio(spaceCharRatio); compositeColumn.addText(para); if (!(firstPass && adjustFirstLine)) { yLine -= para.getSpacingBefore(); } createHere = true; } compositeColumn.setUseAscender((firstPass || descender == 0) && adjustFirstLine ? useAscender : false); compositeColumn.leftX = leftX; compositeColumn.rightX = rightX; compositeColumn.yLine = yLine; compositeColumn.rectangularWidth = rectangularWidth; compositeColumn.rectangularMode = rectangularMode; compositeColumn.minY = minY; compositeColumn.maxY = maxY; boolean keepCandidate = para.getKeepTogether() && createHere && !(firstPass && adjustFirstLine); boolean s = simulate || keepCandidate && keep == 0; if (isTagged(canvas) && !s) { canvas.openMCBlock(para); } status = compositeColumn.go(s); if (isTagged(canvas) && !s) { canvas.closeMCBlock(para); } lastX = compositeColumn.getLastX(); updateFilledWidth(compositeColumn.filledWidth); if ((status & NO_MORE_TEXT) == 0 && keepCandidate) { compositeColumn = null; yLine = lastY; return NO_MORE_COLUMN; } if (simulate || !keepCandidate) break; if (keep == 0) { compositeColumn = null; yLine = lastY; } } firstPass = false; if (compositeColumn.getLinesWritten() > 0) { yLine = compositeColumn.yLine; linesWritten += compositeColumn.linesWritten; descender = compositeColumn.descender; } currentLeading = compositeColumn.currentLeading; if ((status & NO_MORE_TEXT) != 0) { compositeColumn = null; compositeElements.removeFirst(); yLine -= para.getSpacingAfter(); } if ((status & NO_MORE_COLUMN) != 0) { return NO_MORE_COLUMN; } } else if (element.type() == Element.LIST) { com.itextpdf.text.List list = (com.itextpdf.text.List)element; ArrayList<Element> items = list.getItems(); ListItem item = null; float listIndentation = list.getIndentationLeft(); int count = 0; Stack<Object[]> stack = new Stack<Object[]>(); for (int k = 0; k < items.size(); ++k) { Object obj = items.get(k); if (obj instanceof ListItem) { if (count == listIdx) { item = (ListItem)obj; break; } else ++count; } else if (obj instanceof com.itextpdf.text.List) { stack.push(new Object[]{list, Integer.valueOf(k), new Float(listIndentation)}); list = (com.itextpdf.text.List)obj; items = list.getItems(); listIndentation += list.getIndentationLeft(); k = -1; continue; } if (k == items.size() - 1) { if (!stack.isEmpty()) { Object objs[] = stack.pop(); list = (com.itextpdf.text.List)objs[0]; items = list.getItems(); k = ((Integer)objs[1]).intValue(); listIndentation = ((Float)objs[2]).floatValue(); } } } int status = 0; for (int keep = 0; keep < 2; ++keep) { float lastY = yLine; boolean createHere = false; if (compositeColumn == null) { if (item == null) { listIdx = 0; compositeElements.removeFirst(); continue main_loop; } compositeColumn = new ColumnText(canvas); compositeColumn.setUseAscender((firstPass || descender == 0) && adjustFirstLine ? useAscender : false); compositeColumn.setAlignment(item.getAlignment()); compositeColumn.setIndent(item.getIndentationLeft() + listIndentation + item.getFirstLineIndent(), false); compositeColumn.setExtraParagraphSpace(item.getExtraParagraphSpace()); compositeColumn.setFollowingIndent(compositeColumn.getIndent()); compositeColumn.setRightIndent(item.getIndentationRight() + list.getIndentationRight()); compositeColumn.setLeading(item.getLeading(), item.getMultipliedLeading()); compositeColumn.setRunDirection(runDirection); compositeColumn.setArabicOptions(arabicOptions); compositeColumn.setSpaceCharRatio(spaceCharRatio); compositeColumn.addText(item); if (!(firstPass && adjustFirstLine)) { yLine -= item.getSpacingBefore(); } createHere = true; } compositeColumn.leftX = leftX; compositeColumn.rightX = rightX; compositeColumn.yLine = yLine; compositeColumn.rectangularWidth = rectangularWidth; compositeColumn.rectangularMode = rectangularMode; compositeColumn.minY = minY; compositeColumn.maxY = maxY; boolean keepCandidate = item.getKeepTogether() && createHere && !(firstPass && adjustFirstLine); boolean s = simulate || keepCandidate && keep == 0; if (isTagged(canvas) && !s) { item.getListLabel().setIndentation(listIndentation); if (list.getFirstItem() == item || (compositeColumn != null && compositeColumn.bidiLine != null)) canvas.openMCBlock(list); canvas.openMCBlock(item); } status = compositeColumn.go(simulate || keepCandidate && keep == 0, item); if (isTagged(canvas) && !s) { canvas.closeMCBlock(item.getListBody()); canvas.closeMCBlock(item); if ((list.getLastItem() == item && (status & NO_MORE_TEXT) != 0) || (status & NO_MORE_COLUMN) != 0) canvas.closeMCBlock(list); } lastX = compositeColumn.getLastX(); updateFilledWidth(compositeColumn.filledWidth); if ((status & NO_MORE_TEXT) == 0 && keepCandidate) { compositeColumn = null; yLine = lastY; return NO_MORE_COLUMN; } if (simulate || !keepCandidate) break; if (keep == 0) { compositeColumn = null; yLine = lastY; } } firstPass = false; yLine = compositeColumn.yLine; linesWritten += compositeColumn.linesWritten; descender = compositeColumn.descender; currentLeading = compositeColumn.currentLeading; if (!isTagged(canvas)) { if (!Float.isNaN(compositeColumn.firstLineY) && !compositeColumn.firstLineYDone) { if (!simulate) { showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(item.getListSymbol()), compositeColumn.leftX + listIndentation, compositeColumn.firstLineY, 0); } compositeColumn.firstLineYDone = true; } } if ((status & NO_MORE_TEXT) != 0) { compositeColumn = null; ++listIdx; yLine -= item.getSpacingAfter(); } if ((status & NO_MORE_COLUMN) != 0) return NO_MORE_COLUMN; } else if (element.type() == Element.PTABLE) { // INITIALISATIONS // get the PdfPTable element PdfPTable table = (PdfPTable)element; // tables without a body are dismissed if (table.size() <= table.getHeaderRows()) { compositeElements.removeFirst(); continue; } // Y-offset float yTemp = yLine; yTemp += descender; if (rowIdx == 0 && adjustFirstLine) yTemp -= table.spacingBefore(); // if there's no space left, ask for new column if (yTemp < minY || yTemp > maxY) return NO_MORE_COLUMN; // mark start of table float yLineWrite = yTemp; float x1 = leftX; currentLeading = 0; // get the width of the table float tableWidth; if (table.isLockedWidth()) { tableWidth = table.getTotalWidth(); updateFilledWidth(tableWidth); } else { tableWidth = rectangularWidth * table.getWidthPercentage() / 100f; table.setTotalWidth(tableWidth); } // HEADERS / FOOTERS // how many header rows are real header rows; how many are footer rows? table.normalizeHeadersFooters(); int headerRows = table.getHeaderRows(); int footerRows = table.getFooterRows(); int realHeaderRows = headerRows - footerRows; float headerHeight = table.getHeaderHeight(); float footerHeight = table.getFooterHeight(); // do we need to skip the header? boolean skipHeader = table.isSkipFirstHeader() && rowIdx <= realHeaderRows && (table.isComplete() || rowIdx != realHeaderRows); // if not, we wan't to be able to add more than just a header and a footer if (!skipHeader) { yTemp -= headerHeight; if (yTemp < minY || yTemp > maxY) { return NO_MORE_COLUMN; } } // MEASURE NECESSARY SPACE // how many real rows (not header or footer rows) fit on a page? int k = 0; if (rowIdx < headerRows) { rowIdx = headerRows; } // if the table isn't complete, we need to be able to add a footer if (!table.isComplete()) yTemp -= footerHeight; // k will be the first row that doesn't fit for (k = rowIdx; k < table.size(); ++k) { float rowHeight = table.getRowHeight(k); if (yTemp - rowHeight <= minY) break; yTemp -= rowHeight; } LOGGER.info("Want to split at row " + k); int kTemp = k; while (kTemp > rowIdx && kTemp < table.size() && table.getRow(kTemp).isMayNotBreak()) { kTemp--; } if ((kTemp > rowIdx && kTemp < k) || (kTemp == 0 && table.getRow(0).isMayNotBreak() && table.isLoopCheck())) { yTemp = minY; k = kTemp; table.setLoopCheck(false); } LOGGER.info("Will split at row " + k); // only for incomplete tables: if (!table.isComplete()) yTemp += footerHeight; // IF ROWS MAY NOT BE SPLIT if (!table.isSplitRows()) { splittedRow = -1; if (k == rowIdx) { // drop the whole table if (k == table.size()) { compositeElements.removeFirst(); continue; } // or drop the row else { table.getRows().remove(k); return NO_MORE_COLUMN; } } } // IF ROWS SHOULD NOT BE SPLIT else if (table.isSplitLate() && !table.hasRowspan(k) && rowIdx < k) { splittedRow = -1; } // SPLIT ROWS (IF WANTED AND NECESSARY) else if (k < table.size()) { // we calculate the remaining vertical space float h = yTemp - minY; // we create a new row with the remaining content PdfPRow newRow = table.getRow(k).splitRow(table, k, h); // if the row isn't null add it as an extra row if (newRow == null) { LOGGER.info("Didn't split row!"); splittedRow = -1; if (rowIdx == k) return NO_MORE_COLUMN; } else { // if the row hasn't been split before, we duplicate (part of) the table if (k != splittedRow) { splittedRow = k + 1; table = new PdfPTable(table); compositeElements.set(0, table); ArrayList<PdfPRow> rows = table.getRows(); for (int i = headerRows; i < rowIdx; ++i) rows.set(i, null); } yTemp = minY; table.getRows().add(++k, newRow); LOGGER.info("Inserting row at position " + k); } } // We're no longer in the first pass firstPass = false; // if not in simulation mode, draw the table if (!simulate) { // set the alignment switch (table.getHorizontalAlignment()) { case Element.ALIGN_LEFT: break; case Element.ALIGN_RIGHT: x1 += rectangularWidth - tableWidth; break; default: x1 += (rectangularWidth - tableWidth) / 2f; } // copy the rows that fit on the page in a new table nt PdfPTable nt = PdfPTable.shallowCopy(table); ArrayList<PdfPRow> sub = nt.getRows(); // first we add the real header rows (if necessary) if (!skipHeader && realHeaderRows > 0) { ArrayList<PdfPRow> rows = table.getRows(0, realHeaderRows); if (isTagged(canvas)) nt.getHeader().rows = rows; sub.addAll(rows); } else nt.setHeaderRows(footerRows); // then we add the real content { ArrayList<PdfPRow> rows = table.getRows(rowIdx, k); if (isTagged(canvas)) { nt.getBody().rows = rows; } sub.addAll(rows); } // do we need to show a footer? boolean showFooter = !table.isSkipLastFooter(); boolean newPageFollows = false; if (k < table.size()) { nt.setComplete(true); showFooter = true; newPageFollows = true; } // we add the footer rows if necessary (not for incomplete tables) if (footerRows > 0 && nt.isComplete() && showFooter) { ArrayList<PdfPRow> rows = table.getRows(realHeaderRows, realHeaderRows + footerRows); if (isTagged(canvas)) { nt.getFooter().rows = rows; } sub.addAll(rows); } else { footerRows = 0; } // we need a correction if the last row needs to be extended float rowHeight = 0; int lastIdx = sub.size() - 1 - footerRows; PdfPRow last = sub.get(lastIdx); if (table.isExtendLastRow(newPageFollows)) { rowHeight = last.getMaxHeights(); last.setMaxHeights(yTemp - minY + rowHeight); yTemp = minY; } // newPageFollows indicates that this table is being split if (newPageFollows) { PdfPTableEvent tableEvent = table.getTableEvent(); if (tableEvent instanceof PdfPTableEventSplit) { ((PdfPTableEventSplit)tableEvent).splitTable(table); } } // now we render the rows of the new table if (canvases != null) { if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].openMCBlock(table); } nt.writeSelectedRows(0, -1, 0, -1, x1, yLineWrite, canvases, false); if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].closeMCBlock(table); } } else { if (isTagged(canvas)) { canvas.openMCBlock(table); } nt.writeSelectedRows(0, -1, 0, -1, x1, yLineWrite, canvas, false); if (isTagged(canvas)) { canvas.closeMCBlock(table); } } // if the row was split, we copy the content of the last row // that was consumed into the first row shown on the next page if (splittedRow == k && k < table.size()) { PdfPRow splitted = table.getRows().get(k); splitted.copyRowContent(nt, lastIdx); } // reset the row height of the last row if (table.isExtendLastRow(newPageFollows)) { last.setMaxHeights(rowHeight); } } // in simulation mode, we need to take extendLastRow into account else if (table.isExtendLastRow() && minY > PdfPRow.BOTTOM_LIMIT) { yTemp = minY; } yLine = yTemp; descender = 0; currentLeading = 0; if (!(skipHeader || table.isComplete())) yLine += footerHeight; while (k < table.size()) { if (table.getRowHeight(k) > 0 || table.hasRowspan(k)) { break; } k++; } if (k >= table.size()) { // Use up space no more than left if(yLine - table.spacingAfter() < minY) { yLine = minY; } else { yLine -= table.spacingAfter(); } compositeElements.removeFirst(); splittedRow = -1; rowIdx = 0; } else { if (splittedRow != -1) { ArrayList<PdfPRow> rows = table.getRows(); for (int i = rowIdx; i < k; ++i) rows.set(i, null); } rowIdx = k; return NO_MORE_COLUMN; } } else if (element.type() == Element.YMARK) { if (!simulate) { DrawInterface zh = (DrawInterface)element; zh.draw(canvas, leftX, minY, rightX, maxY, yLine); } compositeElements.removeFirst(); } else if (element.type() == Element.DIV) { ArrayList<Element> floatingElements = new ArrayList<Element>(); do { floatingElements.add(element); compositeElements.removeFirst(); element = !compositeElements.isEmpty() ? compositeElements.getFirst() : null; } while (element != null && element.type() == Element.DIV); FloatLayout fl = new FloatLayout(floatingElements, useAscender); fl.setSimpleColumn(leftX, minY, rightX, yLine); int status = fl.layout(canvas, simulate); //firstPass = false; yLine = fl.getYLine(); descender = 0; if ((status & NO_MORE_TEXT) == 0) { compositeElements.addAll(floatingElements); return status; } } else compositeElements.removeFirst(); } }
// 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/PdfPages.java
int reorderPages(int order[]) throws DocumentException { if (order == null) return pages.size(); if (parents.size() > 1) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.a.single.parent.in.the.page.tree.call.pdfwriter.setlinearmode.after.open")); if (order.length != pages.size()) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.an.array.with.the.same.size.as.the.number.of.pages")); int max = pages.size(); boolean temp[] = new boolean[max]; for (int k = 0; k < max; ++k) { int p = order[k]; if (p < 1 || p > max) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.pages.between.1.and.1.found.2", String.valueOf(max), String.valueOf(p))); if (temp[p - 1]) throw new DocumentException(MessageLocalization.getComposedMessage("page.reordering.requires.no.page.repetition.page.1.is.repeated", p)); temp[p - 1] = true; } PdfIndirectReference copy[] = pages.toArray(new PdfIndirectReference[pages.size()]); for (int k = 0; k < max; ++k) { pages.set(k, copy[order[k] - 1]); } return max; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public static PdfWriter getInstance(final Document document, final OutputStream os) throws DocumentException { PdfDocument pdf = new PdfDocument(); document.addDocListener(pdf); PdfWriter writer = new PdfWriter(pdf, os); pdf.addWriter(writer); return writer; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public static PdfWriter getInstance(final Document document, final OutputStream os, final DocListener listener) throws DocumentException { PdfDocument pdf = new PdfDocument(); pdf.addDocListener(listener); document.addDocListener(pdf); PdfWriter writer = new PdfWriter(pdf, os); pdf.addWriter(writer); return writer; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setInitialLeading(final float leading) throws DocumentException { if (open) throw new DocumentException(MessageLocalization.getComposedMessage("you.can.t.set.the.initial.leading.if.the.document.is.already.open")); pdf.setLeading(leading); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public int reorderPages(final int order[]) throws DocumentException { return root.reorderPages(order); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setAdditionalAction(final PdfName actionType, final PdfAction action) throws DocumentException { if (!(actionType.equals(DOCUMENT_CLOSE) || actionType.equals(WILL_SAVE) || actionType.equals(DID_SAVE) || actionType.equals(WILL_PRINT) || actionType.equals(DID_PRINT))) { throw new DocumentException(MessageLocalization.getComposedMessage("invalid.additional.action.type.1", actionType.toString())); } pdf.addAdditionalAction(actionType, action); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final int encryptionType) throws DocumentException { if (pdf.isOpen()) throw new DocumentException(MessageLocalization.getComposedMessage("encryption.can.only.be.added.before.opening.the.document")); crypto = new PdfEncryption(); crypto.setCryptoMode(encryptionType, 0); crypto.setupAllKeys(userPassword, ownerPassword, permissions); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setEncryption(final Certificate[] certs, final int[] permissions, final int encryptionType) throws DocumentException { if (pdf.isOpen()) throw new DocumentException(MessageLocalization.getComposedMessage("encryption.can.only.be.added.before.opening.the.document")); crypto = new PdfEncryption(); if (certs != null) { for (int i=0; i < certs.length; i++) { crypto.addRecipient(certs[i], permissions[i]); } } crypto.setCryptoMode(encryptionType, 0); crypto.getEncryptionDictionary(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Deprecated public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final boolean strength128Bits) throws DocumentException { setEncryption(userPassword, ownerPassword, permissions, strength128Bits ? STANDARD_ENCRYPTION_128 : STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Deprecated public void setEncryption(final boolean strength, final String userPassword, final String ownerPassword, final int permissions) throws DocumentException { setEncryption(getISOBytes(userPassword), getISOBytes(ownerPassword), permissions, strength ? STANDARD_ENCRYPTION_128 : STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Deprecated public void setEncryption(final int encryptionType, final String userPassword, final String ownerPassword, final int permissions) throws DocumentException { setEncryption(getISOBytes(userPassword), getISOBytes(ownerPassword), permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setPageAction(final PdfName actionType, final PdfAction action) throws DocumentException { if (!actionType.equals(PAGE_OPEN) && !actionType.equals(PAGE_CLOSE)) throw new DocumentException(MessageLocalization.getComposedMessage("invalid.page.additional.action.type.1", actionType.toString())); pdf.setPageAction(actionType, action); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setThumbnail(final Image image) throws PdfException, DocumentException { pdf.setThumbnail(image); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setUserunit(final float userunit) throws DocumentException { if (userunit < 1f || userunit > 75000f) throw new DocumentException(MessageLocalization.getComposedMessage("userunit.should.be.a.value.between.1.and.75000")); addPageDictEntry(PdfName.USERUNIT, new PdfNumber(userunit)); setAtLeastPdfVersion(VERSION_1_6); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void clearTextWrap() throws DocumentException { pdf.clearTextWrap(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfName addDirectImageSimple(final Image image) throws PdfException, DocumentException { return addDirectImageSimple(image, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfName addDirectImageSimple(final Image image, final PdfIndirectReference fixedRef) throws PdfException, DocumentException { PdfName name; // if the images is already added, just retrieve the name if (images.containsKey(image.getMySerialId())) { name = images.get(image.getMySerialId()); } // if it's a new image, add it to the document else { if (image.isImgTemplate()) { name = new PdfName("img" + images.size()); if(image instanceof ImgWMF){ try { ImgWMF wmf = (ImgWMF)image; wmf.readWMF(PdfTemplate.createTemplate(this, 0, 0)); } catch (Exception e) { throw new DocumentException(e); } } } else { PdfIndirectReference dref = image.getDirectReference(); if (dref != null) { PdfName rname = new PdfName("img" + images.size()); images.put(image.getMySerialId(), rname); imageDictionary.put(rname, dref); return rname; } Image maskImage = image.getImageMask(); PdfIndirectReference maskRef = null; if (maskImage != null) { PdfName mname = images.get(maskImage.getMySerialId()); maskRef = getImageReference(mname); } PdfImage i = new PdfImage(image, "img" + images.size(), maskRef); if (image instanceof ImgJBIG2) { byte[] globals = ((ImgJBIG2) image).getGlobalBytes(); if (globals != null) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.put(PdfName.JBIG2GLOBALS, getReferenceJBIG2Globals(globals)); i.put(PdfName.DECODEPARMS, decodeparms); } } if (image.hasICCProfile()) { PdfICCBased icc = new PdfICCBased(image.getICCProfile(), image.getCompressionLevel()); PdfIndirectReference iccRef = add(icc); PdfArray iccArray = new PdfArray(); iccArray.add(PdfName.ICCBASED); iccArray.add(iccRef); PdfArray colorspace = i.getAsArray(PdfName.COLORSPACE); if (colorspace != null) { if (colorspace.size() > 1 && PdfName.INDEXED.equals(colorspace.getPdfObject(0))) colorspace.set(1, iccArray); else i.put(PdfName.COLORSPACE, iccArray); } else i.put(PdfName.COLORSPACE, iccArray); } add(i, fixedRef); name = i.name(); } images.put(image.getMySerialId(), name); } return name; }
// 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/PdfCopyForms.java
public void copyDocumentFields(PdfReader reader) throws DocumentException{ fc.copyDocumentFields(reader); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyForms.java
public void setEncryption(byte userPassword[], byte ownerPassword[], int permissions, boolean strength128Bits) throws DocumentException { fc.setEncryption(userPassword, ownerPassword, permissions, strength128Bits ? PdfWriter.STANDARD_ENCRYPTION_128 : PdfWriter.STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyForms.java
public void setEncryption(boolean strength, String userPassword, String ownerPassword, int permissions) throws DocumentException { setEncryption(DocWriter.getISOBytes(userPassword), DocWriter.getISOBytes(ownerPassword), permissions, strength); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyForms.java
public void setEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType) throws DocumentException { fc.setEncryption(userPassword, ownerPassword, permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyForms.java
public void setEncryption(Certificate[] certs, int[] permissions, int encryptionType) throws DocumentException { fc.setEncryption(certs, permissions, encryptionType); }
// 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 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
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
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 void addImage(Image image, float a, float b, float c, float d, float e, float f) throws DocumentException { throwError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
public PdfTemplate getAppearance() throws DocumentException { if (isInvisible()) { PdfTemplate t = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(0, 0)); writer.addDirectTemplateSimple(t, null); return t; } if (app[0] == null) { PdfTemplate t = app[0] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n0")); t.setLiteral("% DSBlank\n"); } if (app[1] == null && !acro6Layers) { PdfTemplate t = app[1] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n1")); t.setLiteral(questionMark); } if (app[2] == null) { String text; if (layer2Text == null) { StringBuilder buf = new StringBuilder(); buf.append("Digitally signed by "); String name = null; X500Name x500name = CertificateInfo.getSubjectFields((X509Certificate)signCertificate); if (x500name != null) { name = x500name.getField("CN"); if (name == null) name = x500name.getField("E"); } if (name == null) name = ""; buf.append(name).append('\n'); SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); buf.append("Date: ").append(sd.format(signDate.getTime())); if (reason != null) buf.append('\n').append("Reason: ").append(reason); if (location != null) buf.append('\n').append("Location: ").append(location); text = buf.toString(); } else text = layer2Text; PdfTemplate t = app[2] = new PdfTemplate(writer); t.setBoundingBox(rect); writer.addDirectTemplateSimple(t, new PdfName("n2")); if (image != null) { if (imageScale == 0) { t.addImage(image, rect.getWidth(), 0, 0, rect.getHeight(), 0, 0); } else { float usableScale = imageScale; if (imageScale < 0) usableScale = Math.min(rect.getWidth() / image.getWidth(), rect.getHeight() / image.getHeight()); float w = image.getWidth() * usableScale; float h = image.getHeight() * usableScale; float x = (rect.getWidth() - w) / 2; float y = (rect.getHeight() - h) / 2; t.addImage(image, w, 0, 0, h, x, y); } } Font font; if (layer2Font == null) font = new Font(); else font = new Font(layer2Font); float size = font.getSize(); Rectangle dataRect = null; Rectangle signatureRect = null; if (renderingMode == RenderingMode.NAME_AND_DESCRIPTION || renderingMode == RenderingMode.GRAPHIC_AND_DESCRIPTION && this.signatureGraphic != null) { // origin is the bottom-left signatureRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() / 2 - MARGIN, rect.getHeight() - MARGIN); dataRect = new Rectangle( rect.getWidth() / 2 + MARGIN / 2, MARGIN, rect.getWidth() - MARGIN / 2, rect.getHeight() - MARGIN); if (rect.getHeight() > rect.getWidth()) { signatureRect = new Rectangle( MARGIN, rect.getHeight() / 2, rect.getWidth() - MARGIN, rect.getHeight()); dataRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, rect.getHeight() / 2 - MARGIN); } } else if (renderingMode == RenderingMode.GRAPHIC) { if (signatureGraphic == null) { throw new IllegalStateException(MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.only")); } signatureRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, // take all space available rect.getHeight() - MARGIN); } else { dataRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, rect.getHeight() * (1 - TOP_SECTION) - MARGIN); } switch (renderingMode) { case NAME_AND_DESCRIPTION: String signedBy = CertificateInfo.getSubjectFields((X509Certificate)signCertificate).getField("CN"); if (signedBy == null) signedBy = CertificateInfo.getSubjectFields((X509Certificate)signCertificate).getField("E"); if (signedBy == null) signedBy = ""; Rectangle sr2 = new Rectangle(signatureRect.getWidth() - MARGIN, signatureRect.getHeight() - MARGIN ); float signedSize = ColumnText.fitText(font, signedBy, sr2, -1, runDirection); ColumnText ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(new Phrase(signedBy, font), signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), signedSize, Element.ALIGN_LEFT); ct2.go(); break; case GRAPHIC_AND_DESCRIPTION: if (signatureGraphic == null) { throw new IllegalStateException(MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.and.description")); } ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), 0, Element.ALIGN_RIGHT); Image im = Image.getInstance(signatureGraphic); im.scaleToFit(signatureRect.getWidth(), signatureRect.getHeight()); Paragraph p = new Paragraph(); // must calculate the point to draw from to make image appear in middle of column float x = 0; // experimentation found this magic number to counteract Adobe's signature graphic, which // offsets the y co-ordinate by 15 units float y = -im.getScaledHeight() + 15; x = x + (signatureRect.getWidth() - im.getScaledWidth()) / 2; y = y - (signatureRect.getHeight() - im.getScaledHeight()) / 2; p.add(new Chunk(im, x + (signatureRect.getWidth() - im.getScaledWidth()) / 2, y, false)); ct2.addElement(p); ct2.go(); break; case GRAPHIC: ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), 0, Element.ALIGN_RIGHT); im = Image.getInstance(signatureGraphic); im.scaleToFit(signatureRect.getWidth(), signatureRect.getHeight()); p = new Paragraph(signatureRect.getHeight()); // must calculate the point to draw from to make image appear in middle of column x = (signatureRect.getWidth() - im.getScaledWidth()) / 2; y = (signatureRect.getHeight() - im.getScaledHeight()) / 2; p.add(new Chunk(im, x, y, false)); ct2.addElement(p); ct2.go(); break; default: } if(renderingMode != RenderingMode.GRAPHIC) { if (size <= 0) { Rectangle sr = new Rectangle(dataRect.getWidth(), dataRect.getHeight()); size = ColumnText.fitText(font, text, sr, 12, runDirection); } ColumnText ct = new ColumnText(t); ct.setRunDirection(runDirection); ct.setSimpleColumn(new Phrase(text, font), dataRect.getLeft(), dataRect.getBottom(), dataRect.getRight(), dataRect.getTop(), size, Element.ALIGN_LEFT); ct.go(); } } if (app[3] == null && !acro6Layers) { PdfTemplate t = app[3] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n3")); t.setLiteral("% DSBlank\n"); } if (app[4] == null && !acro6Layers) { PdfTemplate t = app[4] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(0, rect.getHeight() * (1 - TOP_SECTION), rect.getRight(), rect.getTop())); writer.addDirectTemplateSimple(t, new PdfName("n4")); Font font; if (layer2Font == null) font = new Font(); else font = new Font(layer2Font); //float size = font.getSize(); String text = "Signature Not Verified"; if (layer4Text != null) text = layer4Text; Rectangle sr = new Rectangle(rect.getWidth() - 2 * MARGIN, rect.getHeight() * TOP_SECTION - 2 * MARGIN); float size = ColumnText.fitText(font, text, sr, 15, runDirection); ColumnText ct = new ColumnText(t); ct.setRunDirection(runDirection); ct.setSimpleColumn(new Phrase(text, font), MARGIN, 0, rect.getWidth() - MARGIN, rect.getHeight() - MARGIN, size, Element.ALIGN_LEFT); ct.go(); } int rotation = writer.reader.getPageRotation(page); Rectangle rotated = new Rectangle(rect); int n = rotation; while (n > 0) { rotated = rotated.rotate(); n -= 90; } if (frm == null) { frm = new PdfTemplate(writer); frm.setBoundingBox(rotated); writer.addDirectTemplateSimple(frm, new PdfName("FRM")); float scale = Math.min(rect.getWidth(), rect.getHeight()) * 0.9f; float x = (rect.getWidth() - scale) / 2; float y = (rect.getHeight() - scale) / 2; scale /= 100; if (rotation == 90) frm.concatCTM(0, 1, -1, 0, rect.getHeight(), 0); else if (rotation == 180) frm.concatCTM(-1, 0, 0, -1, rect.getWidth(), rect.getHeight()); else if (rotation == 270) frm.concatCTM(0, -1, 1, 0, 0, rect.getWidth()); frm.addTemplate(app[0], 0, 0); if (!acro6Layers) frm.addTemplate(app[1], scale, 0, 0, scale, x, y); frm.addTemplate(app[2], 0, 0); if (!acro6Layers) { frm.addTemplate(app[3], scale, 0, 0, scale, x, y); frm.addTemplate(app[4], 0, 0); } } PdfTemplate napp = new PdfTemplate(writer); napp.setBoundingBox(rotated); writer.addDirectTemplateSimple(napp, null); napp.addTemplate(frm, 0, 0); return napp; }
// 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
void setThumbnail(Image image, int page) throws PdfException, DocumentException { PdfIndirectReference thumb = getImageReference(addDirectImageSimple(image)); reader.resetReleasePage(); PdfDictionary dic = reader.getPageN(page); dic.put(PdfName.THUMB, thumb); reader.resetReleasePage(); }
// 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/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/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/PdfContentByte.java
public void addImage(final Image image) throws DocumentException { addImage(image, false); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final boolean inlineImage) throws DocumentException { if (!image.hasAbsoluteY()) throw new DocumentException(MessageLocalization.getComposedMessage("the.image.must.have.absolute.positioning")); float matrix[] = image.matrix(); matrix[Image.CX] = image.getAbsoluteX() - matrix[Image.CX]; matrix[Image.CY] = image.getAbsoluteY() - matrix[Image.CY]; addImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], inlineImage); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final float a, final float b, final float c, final float d, final float e, final float f) throws DocumentException { addImage(image, a, b, c, d, e, f, false); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final AffineTransform transform) throws DocumentException { double matrix[] = new double[6]; transform.getMatrix(matrix); addImage( image, (float)matrix[0], (float)matrix[1], (float)matrix[2], (float)matrix[3], (float)matrix[4],(float) matrix[5], false ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final float a, final float b, final float c, final float d, final float e, final float f, final boolean inlineImage) throws DocumentException { try { if (image.getLayer() != null) beginLayer(image.getLayer()); if (inText && isTagged()) { endText(); } if (writer != null && image.isImgTemplate()) { writer.addDirectImageSimple(image); PdfTemplate template = image.getTemplateData(); float w = template.getWidth(); float h = template.getHeight(); addTemplate(template, a / w, b / w, c / h, d / h, e, f); } else { content.append("q "); content.append(a).append(' '); content.append(b).append(' '); content.append(c).append(' '); content.append(d).append(' '); content.append(e).append(' '); content.append(f).append(" cm"); if (inlineImage) { content.append("\nBI\n"); PdfImage pimage = new PdfImage(image, "", null); if (image instanceof ImgJBIG2) { byte[] globals = ((ImgJBIG2)image).getGlobalBytes(); if (globals != null) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.put(PdfName.JBIG2GLOBALS, writer.getReferenceJBIG2Globals(globals)); pimage.put(PdfName.DECODEPARMS, decodeparms); } } for (Object element : pimage.getKeys()) { PdfName key = (PdfName)element; PdfObject value = pimage.get(key); String s = abrev.get(key); if (s == null) continue; content.append(s); boolean check = true; if (key.equals(PdfName.COLORSPACE) && value.isArray()) { PdfArray ar = (PdfArray)value; if (ar.size() == 4 && PdfName.INDEXED.equals(ar.getAsName(0)) && ar.getPdfObject(1).isName() && ar.getPdfObject(2).isNumber() && ar.getPdfObject(3).isString() ) { check = false; } } if (check && key.equals(PdfName.COLORSPACE) && !value.isName()) { PdfName cs = writer.getColorspaceName(); PageResources prs = getPageResources(); prs.addColor(cs, writer.addToBody(value).getIndirectReference()); value = cs; } value.toPdf(null, content); content.append('\n'); } content.append("ID\n"); pimage.writeContent(content); content.append("\nEI\nQ").append_i(separator); } else { PdfName name; PageResources prs = getPageResources(); Image maskImage = image.getImageMask(); if (maskImage != null) { name = writer.addDirectImageSimple(maskImage); prs.addXObject(name, writer.getImageReference(name)); } name = writer.addDirectImageSimple(image); name = prs.addXObject(name, writer.getImageReference(name)); content.append(' ').append(name.getBytes()).append(" Do Q").append_i(separator); } } if (image.hasBorders()) { saveState(); float w = image.getWidth(); float h = image.getHeight(); concatCTM(a / w, b / w, c / h, d / h, e, f); rectangle(image); restoreState(); } if (image.getLayer() != null) endLayer(); Annotation annot = image.getAnnotation(); if (annot == null) return; float[] r = new float[unitRect.length]; for (int k = 0; k < unitRect.length; k += 2) { r[k] = a * unitRect[k] + c * unitRect[k + 1] + e; r[k + 1] = b * unitRect[k] + d * unitRect[k + 1] + f; } float llx = r[0]; float lly = r[1]; float urx = llx; float ury = lly; for (int k = 2; k < r.length; k += 2) { llx = Math.min(llx, r[k]); lly = Math.min(lly, r[k + 1]); urx = Math.max(urx, r[k]); ury = Math.max(ury, r[k + 1]); } annot = new Annotation(annot); annot.setDimensions(llx, lly, urx, ury); PdfAnnotation an = PdfAnnotationsImp.convertAnnotation(writer, annot, new Rectangle(llx, lly, urx, ury)); if (an == null) return; addAnnotation(an); } catch (Exception ee) { throw new DocumentException(ee); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void addImage(final Image image, final java.awt.geom.AffineTransform transform) throws DocumentException { double matrix[] = new double[6]; transform.getMatrix(matrix); addImage(image, new AffineTransform(matrix)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
public void addWriter(final PdfWriter writer) throws DocumentException { if (this.writer == null) { this.writer = writer; annotationsImp = new PdfAnnotationsImp(writer); return; } throw new DocumentException(MessageLocalization.getComposedMessage("you.can.only.add.a.writer.to.a.pdfdocument.once")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public boolean add(final Element element) throws DocumentException { if (writer != null && writer.isPaused()) { return false; } try { if (element.type() != Element.DIV) { flushFloatingElements(); } // TODO refactor this uber long switch to State/Strategy or something ... switch(element.type()) { // Information (headers) case Element.HEADER: info.addkey(((Meta)element).getName(), ((Meta)element).getContent()); break; case Element.TITLE: info.addTitle(((Meta)element).getContent()); break; case Element.SUBJECT: info.addSubject(((Meta)element).getContent()); break; case Element.KEYWORDS: info.addKeywords(((Meta)element).getContent()); break; case Element.AUTHOR: info.addAuthor(((Meta)element).getContent()); break; case Element.CREATOR: info.addCreator(((Meta)element).getContent()); break; case Element.LANGUAGE: setLanguage(((Meta)element).getContent()); break; case Element.PRODUCER: // you can not change the name of the producer info.addProducer(); break; case Element.CREATIONDATE: // you can not set the creation date, only reset it info.addCreationDate(); break; // content (text) case Element.CHUNK: { // if there isn't a current line available, we make one if (line == null) { carriageReturn(); } // we cast the element to a chunk PdfChunk chunk = new PdfChunk((Chunk) element, anchorAction); // we try to add the chunk to the line, until we succeed { PdfChunk overflow; while ((overflow = line.add(chunk)) != null) { carriageReturn(); boolean newlineSplit = chunk.isNewlineSplit(); chunk = overflow; if (!newlineSplit) chunk.trimFirstSpace(); } } pageEmpty = false; if (chunk.isAttribute(Chunk.NEWPAGE)) { newPage(); } break; } case Element.ANCHOR: { leadingCount++; Anchor anchor = (Anchor) element; String url = anchor.getReference(); leading = anchor.getLeading(); if (url != null) { anchorAction = new PdfAction(url); } // we process the element element.process(this); anchorAction = null; leadingCount--; break; } case Element.ANNOTATION: { if (line == null) { carriageReturn(); } Annotation annot = (Annotation) element; Rectangle rect = new Rectangle(0, 0); if (line != null) rect = new Rectangle(annot.llx(indentRight() - line.widthLeft()), annot.ury(indentTop() - currentHeight - 20), annot.urx(indentRight() - line.widthLeft() + 20), annot.lly(indentTop() - currentHeight)); PdfAnnotation an = PdfAnnotationsImp.convertAnnotation(writer, annot, rect); annotationsImp.addPlainAnnotation(an); pageEmpty = false; break; } case Element.PHRASE: { leadingCount++; // we cast the element to a phrase and set the leading of the document leading = ((Phrase) element).getTotalLeading(); // we process the element element.process(this); leadingCount--; break; } case Element.PARAGRAPH: { leadingCount++; // we cast the element to a paragraph Paragraph paragraph = (Paragraph) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(paragraph); } addSpacing(paragraph.getSpacingBefore(), leading, paragraph.getFont()); // we adjust the parameters of the document alignment = paragraph.getAlignment(); leading = paragraph.getTotalLeading(); carriageReturn(); // we don't want to make orphans/widows if (currentHeight + line.height() + leading > indentTop() - indentBottom()) { newPage(); } indentation.indentLeft += paragraph.getIndentationLeft(); indentation.indentRight += paragraph.getIndentationRight(); carriageReturn(); PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null && !isSectionTitle) pageEvent.onParagraph(writer, this, indentTop() - currentHeight); // if a paragraph has to be kept together, we wrap it in a table object if (paragraph.getKeepTogether()) { carriageReturn(); PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100f); PdfPCell cell = new PdfPCell(); cell.addElement(paragraph); cell.setBorder(Rectangle.NO_BORDER); cell.setPadding(0); table.addCell(cell); indentation.indentLeft -= paragraph.getIndentationLeft(); indentation.indentRight -= paragraph.getIndentationRight(); this.add(table); indentation.indentLeft += paragraph.getIndentationLeft(); indentation.indentRight += paragraph.getIndentationRight(); } else { line.setExtraIndent(paragraph.getFirstLineIndent()); element.process(this); carriageReturn(); addSpacing(paragraph.getSpacingAfter(), paragraph.getTotalLeading(), paragraph.getFont()); } if (pageEvent != null && !isSectionTitle) pageEvent.onParagraphEnd(writer, this, indentTop() - currentHeight); alignment = Element.ALIGN_LEFT; indentation.indentLeft -= paragraph.getIndentationLeft(); indentation.indentRight -= paragraph.getIndentationRight(); carriageReturn(); leadingCount--; if (isTagged(writer)) { flushLines(); text.closeMCBlock(paragraph); } break; } case Element.SECTION: case Element.CHAPTER: { // Chapters and Sections only differ in their constructor // so we cast both to a Section Section section = (Section) element; PdfPageEvent pageEvent = writer.getPageEvent(); boolean hasTitle = section.isNotAddedYet() && section.getTitle() != null; // if the section is a chapter, we begin a new page if (section.isTriggerNewPage()) { newPage(); } if (hasTitle) { float fith = indentTop() - currentHeight; int rotation = pageSize.getRotation(); if (rotation == 90 || rotation == 180) fith = pageSize.getHeight() - fith; PdfDestination destination = new PdfDestination(PdfDestination.FITH, fith); while (currentOutline.level() >= section.getDepth()) { currentOutline = currentOutline.parent(); } PdfOutline outline = new PdfOutline(currentOutline, destination, section.getBookmarkTitle(), section.isBookmarkOpen()); currentOutline = outline; } // some values are set carriageReturn(); indentation.sectionIndentLeft += section.getIndentationLeft(); indentation.sectionIndentRight += section.getIndentationRight(); if (section.isNotAddedYet() && pageEvent != null) if (element.type() == Element.CHAPTER) pageEvent.onChapter(writer, this, indentTop() - currentHeight, section.getTitle()); else pageEvent.onSection(writer, this, indentTop() - currentHeight, section.getDepth(), section.getTitle()); // the title of the section (if any has to be printed) if (hasTitle) { isSectionTitle = true; add(section.getTitle()); isSectionTitle = false; } indentation.sectionIndentLeft += section.getIndentation(); // we process the section element.process(this); flushLines(); // some parameters are set back to normal again indentation.sectionIndentLeft -= section.getIndentationLeft() + section.getIndentation(); indentation.sectionIndentRight -= section.getIndentationRight(); if (section.isComplete() && pageEvent != null) if (element.type() == Element.CHAPTER) pageEvent.onChapterEnd(writer, this, indentTop() - currentHeight); else pageEvent.onSectionEnd(writer, this, indentTop() - currentHeight); break; } case Element.LIST: { // we cast the element to a List List list = (List) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(list); } if (list.isAlignindent()) { list.normalizeIndentation(); } // we adjust the document indentation.listIndentLeft += list.getIndentationLeft(); indentation.indentRight += list.getIndentationRight(); // we process the items in the list element.process(this); // some parameters are set back to normal again indentation.listIndentLeft -= list.getIndentationLeft(); indentation.indentRight -= list.getIndentationRight(); carriageReturn(); if (isTagged(writer)) { flushLines(); text.closeMCBlock(list); } break; } case Element.LISTITEM: { leadingCount++; // we cast the element to a ListItem ListItem listItem = (ListItem) element; if (isTagged(writer)) { flushLines(); text.openMCBlock(listItem); } addSpacing(listItem.getSpacingBefore(), leading, listItem.getFont()); // we adjust the document alignment = listItem.getAlignment(); indentation.listIndentLeft += listItem.getIndentationLeft(); indentation.indentRight += listItem.getIndentationRight(); leading = listItem.getTotalLeading(); carriageReturn(); // we prepare the current line to be able to show us the listsymbol line.setListItem(listItem); // we process the item element.process(this); addSpacing(listItem.getSpacingAfter(), listItem.getTotalLeading(), listItem.getFont()); // if the last line is justified, it should be aligned to the left if (line.hasToBeJustified()) { line.resetAlignment(); } // some parameters are set back to normal again carriageReturn(); indentation.listIndentLeft -= listItem.getIndentationLeft(); indentation.indentRight -= listItem.getIndentationRight(); leadingCount--; if (isTagged(writer)) { flushLines(); text.closeMCBlock(listItem.getListBody()); text.closeMCBlock(listItem); } break; } case Element.RECTANGLE: { Rectangle rectangle = (Rectangle) element; graphics.rectangle(rectangle); pageEmpty = false; break; } case Element.PTABLE: { PdfPTable ptable = (PdfPTable)element; if (ptable.size() <= ptable.getHeaderRows()) break; //nothing to do // before every table, we add a new line and flush all lines ensureNewLine(); flushLines(); addPTable(ptable); pageEmpty = false; newLine(); break; } case Element.JPEG: case Element.JPEG2000: case Element.JBIG2: case Element.IMGRAW: case Element.IMGTEMPLATE: { //carriageReturn(); suggestion by Marc Campforts add((Image) element); break; } case Element.YMARK: { DrawInterface zh = (DrawInterface)element; zh.draw(graphics, indentLeft(), indentBottom(), indentRight(), indentTop(), indentTop() - currentHeight - (leadingCount > 0 ? leading : 0)); pageEmpty = false; break; } case Element.MARKED: { MarkedObject mo; if (element instanceof MarkedSection) { mo = ((MarkedSection)element).getTitle(); if (mo != null) { mo.process(this); } } mo = (MarkedObject)element; mo.process(this); break; } case Element.WRITABLE_DIRECT: if (null != writer) { ((WriterOperation)element).write(writer, this); } break; case Element.DIV: ensureNewLine(); flushLines(); addDiv((PdfDiv)element); pageEmpty = false; //newLine(); break; default: return false; } lastElementType = element.type(); return true; } catch(Exception e) { throw new DocumentException(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void initPage() throws DocumentException { // the pagenumber is incremented pageN++; // initialization of some page objects annotationsImp.resetAnnotations(); pageResources = new PageResources(); writer.resetContent(); if (isTagged(writer)) { graphics = writer.getDirectContentUnder().getDuplicate(); writer.getDirectContent().duplicatedFrom = graphics; } else { graphics = new PdfContentByte(writer); } markPoint = 0; setNewPageSizeAndMargins(); imageEnd = -1; indentation.imageIndentRight = 0; indentation.imageIndentLeft = 0; indentation.indentBottom = 0; indentation.indentTop = 0; currentHeight = 0; // backgroundcolors, etc... thisBoxSize = new HashMap<String, PdfRectangle>(boxSize); if (pageSize.getBackgroundColor() != null || pageSize.hasBorders() || pageSize.getBorderColor() != null) { add(pageSize); } float oldleading = leading; int oldAlignment = alignment; pageEmpty = true; // if there is an image waiting to be drawn, draw it try { if (imageWait != null) { add(imageWait); imageWait = null; } } catch(Exception e) { throw new ExceptionConverter(e); } leading = oldleading; alignment = oldAlignment; carriageReturn(); PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) { if (firstPageEvent) { pageEvent.onOpenDocument(writer, this); } pageEvent.onStartPage(writer, this); } firstPageEvent = false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void newLine() throws DocumentException { lastElementType = -1; carriageReturn(); if (lines != null && !lines.isEmpty()) { lines.add(line); currentHeight += line.height(); } line = new PdfLine(indentLeft(), indentRight(), alignment, leading); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected float flushLines() throws DocumentException { // checks if the ArrayList with the lines is not null if (lines == null) { return 0; } // checks if a new Line has to be made. if (line != null && line.size() > 0) { lines.add(line); line = new PdfLine(indentLeft(), indentRight(), alignment, leading); } // checks if the ArrayList with the lines is empty if (lines.isEmpty()) { return 0; } // initialization of some parameters Object currentValues[] = new Object[2]; PdfFont currentFont = null; float displacement = 0; Float lastBaseFactor = new Float(0); currentValues[1] = lastBaseFactor; // looping over all the lines for (PdfLine l: lines) { float moveTextX = l.indentLeft() - indentLeft() + indentation.indentLeft + indentation.listIndentLeft + indentation.sectionIndentLeft; text.moveText(moveTextX, -l.height()); // is the line preceded by a symbol? if (l.listSymbol() != null) { ListLabel lbl = null; Chunk symbol = l.listSymbol(); if (isTagged(writer)) { lbl = l.listItem().getListLabel(); graphics.openMCBlock(lbl); symbol = new Chunk(symbol); if (!lbl.getTagLabelContent()) symbol.setRole(null); } ColumnText.showTextAligned(graphics, Element.ALIGN_LEFT, new Phrase(symbol), text.getXTLM() - l.listIndent(), text.getYTLM(), 0); if (lbl != null) { graphics.closeMCBlock(lbl); } } currentValues[0] = currentFont; if (isTagged(writer) && l.listItem() != null) { text.openMCBlock(l.listItem().getListBody()); } writeLineToContent(l, text, graphics, currentValues, writer.getSpaceCharRatio()); currentFont = (PdfFont)currentValues[0]; displacement += l.height(); text.moveText(-moveTextX, 0); } lines = new ArrayList<PdfLine>(); return displacement; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
float writeLineToContent(final PdfLine line, final PdfContentByte text, final PdfContentByte graphics, final Object currentValues[], final float ratio) throws DocumentException { PdfFont currentFont = (PdfFont)currentValues[0]; float lastBaseFactor = ((Float)currentValues[1]).floatValue(); PdfChunk chunk; int numberOfSpaces; int lineLen; boolean isJustified; float hangingCorrection = 0; float hScale = 1; float lastHScale = Float.NaN; float baseWordSpacing = 0; float baseCharacterSpacing = 0; float glueWidth = 0; float lastX = text.getXTLM() + line.getOriginalWidth(); numberOfSpaces = line.numberOfSpaces(); lineLen = line.getLineLengthUtf32(); // does the line need to be justified? isJustified = line.hasToBeJustified() && (numberOfSpaces != 0 || lineLen > 1); int separatorCount = line.getSeparatorCount(); if (separatorCount > 0) { glueWidth = line.widthLeft() / separatorCount; } else if (isJustified && separatorCount == 0) { if (line.isNewlineSplit() && line.widthLeft() >= lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1)) { if (line.isRTL()) { text.moveText(line.widthLeft() - lastBaseFactor * (ratio * numberOfSpaces + lineLen - 1), 0); } baseWordSpacing = ratio * lastBaseFactor; baseCharacterSpacing = lastBaseFactor; } else { float width = line.widthLeft(); PdfChunk last = line.getChunk(line.size() - 1); if (last != null) { String s = last.toString(); char c; if (s.length() > 0 && hangingPunctuation.indexOf((c = s.charAt(s.length() - 1))) >= 0) { float oldWidth = width; width += last.font().width(c) * 0.4f; hangingCorrection = width - oldWidth; } } float baseFactor = width / (ratio * numberOfSpaces + lineLen - 1); baseWordSpacing = ratio * baseFactor; baseCharacterSpacing = baseFactor; lastBaseFactor = baseFactor; } } else if (line.alignment == Element.ALIGN_LEFT || line.alignment == Element.ALIGN_UNDEFINED) { lastX -= line.widthLeft(); } int lastChunkStroke = line.getLastStrokeChunk(); int chunkStrokeIdx = 0; float xMarker = text.getXTLM(); float baseXMarker = xMarker; float yMarker = text.getYTLM(); boolean adjustMatrix = false; float tabPosition = 0; // looping over all the chunks in 1 line for (Iterator<PdfChunk> j = line.iterator(); j.hasNext(); ) { chunk = j.next(); if (isTagged(writer) && chunk.accessibleElement != null) { text.openMCBlock(chunk.accessibleElement); } BaseColor color = chunk.color(); float fontSize = chunk.font().size(); float ascender = chunk.font().getFont().getFontDescriptor(BaseFont.ASCENT, fontSize); float descender = chunk.font().getFont().getFontDescriptor(BaseFont.DESCENT, fontSize); hScale = 1; if (chunkStrokeIdx <= lastChunkStroke) { float width; if (isJustified) { width = chunk.getWidthCorrected(baseCharacterSpacing, baseWordSpacing); } else { width = chunk.width(); } if (chunk.isStroked()) { PdfChunk nextChunk = line.getChunk(chunkStrokeIdx + 1); if (chunk.isSeparator()) { width = glueWidth; Object[] sep = (Object[])chunk.getAttribute(Chunk.SEPARATOR); DrawInterface di = (DrawInterface)sep[0]; Boolean vertical = (Boolean)sep[1]; if (vertical.booleanValue()) { di.draw(graphics, baseXMarker, yMarker + descender, baseXMarker + line.getOriginalWidth(), ascender - descender, yMarker); } else { di.draw(graphics, xMarker, yMarker + descender, xMarker + width, ascender - descender, yMarker); } } if (chunk.isTab()) { Object[] tab = (Object[])chunk.getAttribute(Chunk.TAB); DrawInterface di = (DrawInterface)tab[0]; tabPosition = ((Float)tab[1]).floatValue() + ((Float)tab[3]).floatValue(); if (tabPosition > xMarker) { di.draw(graphics, xMarker, yMarker + descender, tabPosition, ascender - descender, yMarker); } float tmp = xMarker; xMarker = tabPosition; tabPosition = tmp; } if (chunk.isAttribute(Chunk.BACKGROUND)) { boolean inText = graphics.getInText(); if (inText && isTagged(writer)) { graphics.endText(); } float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.BACKGROUND)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Object bgr[] = (Object[])chunk.getAttribute(Chunk.BACKGROUND); graphics.setColorFill((BaseColor)bgr[0]); float extra[] = (float[])bgr[1]; graphics.rectangle(xMarker - extra[0], yMarker + descender - extra[1] + chunk.getTextRise(), width - subtract + extra[0] + extra[2], ascender - descender + extra[1] + extra[3]); graphics.fill(); graphics.setGrayFill(0); if (inText && isTagged(writer)) { graphics.beginText(true); } } if (chunk.isAttribute(Chunk.UNDERLINE)) { boolean inText = graphics.getInText(); if (inText && isTagged(writer)) { graphics.endText(); } float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.UNDERLINE)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Object unders[][] = (Object[][])chunk.getAttribute(Chunk.UNDERLINE); BaseColor scolor = null; for (int k = 0; k < unders.length; ++k) { Object obj[] = unders[k]; scolor = (BaseColor)obj[0]; float ps[] = (float[])obj[1]; if (scolor == null) scolor = color; if (scolor != null) graphics.setColorStroke(scolor); graphics.setLineWidth(ps[0] + fontSize * ps[1]); float shift = ps[2] + fontSize * ps[3]; int cap2 = (int)ps[4]; if (cap2 != 0) graphics.setLineCap(cap2); graphics.moveTo(xMarker, yMarker + shift); graphics.lineTo(xMarker + width - subtract, yMarker + shift); graphics.stroke(); if (scolor != null) graphics.resetGrayStroke(); if (cap2 != 0) graphics.setLineCap(0); } graphics.setLineWidth(1); if (inText && isTagged(writer)) { graphics.beginText(true); } } if (chunk.isAttribute(Chunk.ACTION)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.ACTION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; PdfAnnotation annot = null; if (chunk.isImage()) { annot = new PdfAnnotation(writer, xMarker, yMarker + chunk.getImageOffsetY(), xMarker + width - subtract, yMarker + chunk.getImageHeight() + chunk.getImageOffsetY(), (PdfAction)chunk.getAttribute(Chunk.ACTION)); } else { annot = new PdfAnnotation(writer, xMarker, yMarker + descender + chunk.getTextRise(), xMarker + width - subtract, yMarker + ascender + chunk.getTextRise(), (PdfAction)chunk.getAttribute(Chunk.ACTION)); } text.addAnnotation(annot); if (isTagged(writer) && chunk.accessibleElement != null) { PdfStructureElement strucElem = structElements.get(chunk.accessibleElement.getId()); if (strucElem != null) { PdfArray kArray = strucElem.getAsArray(PdfName.K); if (kArray == null) { kArray = new PdfArray(); PdfObject k = strucElem.get(PdfName.K); if (k != null) { kArray.add(k); } strucElem.put(PdfName.K, kArray); } PdfDictionary dict = new PdfDictionary(); dict.put(PdfName.TYPE, PdfName.OBJR); dict.put(PdfName.OBJ, annot.getIndirectReference()); kArray.add(dict); } } } if (chunk.isAttribute(Chunk.REMOTEGOTO)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.REMOTEGOTO)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Object obj[] = (Object[])chunk.getAttribute(Chunk.REMOTEGOTO); String filename = (String)obj[0]; if (obj[1] instanceof String) remoteGoto(filename, (String)obj[1], xMarker, yMarker + descender + chunk.getTextRise(), xMarker + width - subtract, yMarker + ascender + chunk.getTextRise()); else remoteGoto(filename, ((Integer)obj[1]).intValue(), xMarker, yMarker + descender + chunk.getTextRise(), xMarker + width - subtract, yMarker + ascender + chunk.getTextRise()); } if (chunk.isAttribute(Chunk.LOCALGOTO)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.LOCALGOTO)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; localGoto((String)chunk.getAttribute(Chunk.LOCALGOTO), xMarker, yMarker, xMarker + width - subtract, yMarker + fontSize); } if (chunk.isAttribute(Chunk.LOCALDESTINATION)) { /*float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.LOCALDESTINATION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection;*/ localDestination((String)chunk.getAttribute(Chunk.LOCALDESTINATION), new PdfDestination(PdfDestination.XYZ, xMarker, yMarker + fontSize, 0)); } if (chunk.isAttribute(Chunk.GENERICTAG)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.GENERICTAG)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; Rectangle rect = new Rectangle(xMarker, yMarker, xMarker + width - subtract, yMarker + fontSize); PdfPageEvent pev = writer.getPageEvent(); if (pev != null) pev.onGenericTag(writer, this, rect, (String)chunk.getAttribute(Chunk.GENERICTAG)); } if (chunk.isAttribute(Chunk.PDFANNOTATION)) { float subtract = lastBaseFactor; if (nextChunk != null && nextChunk.isAttribute(Chunk.PDFANNOTATION)) subtract = 0; if (nextChunk == null) subtract += hangingCorrection; PdfAnnotation annot = PdfFormField.shallowDuplicate((PdfAnnotation)chunk.getAttribute(Chunk.PDFANNOTATION)); annot.put(PdfName.RECT, new PdfRectangle(xMarker, yMarker + descender, xMarker + width - subtract, yMarker + ascender)); text.addAnnotation(annot); } float params[] = (float[])chunk.getAttribute(Chunk.SKEW); Float hs = (Float)chunk.getAttribute(Chunk.HSCALE); if (params != null || hs != null) { float b = 0, c = 0; if (params != null) { b = params[0]; c = params[1]; } if (hs != null) hScale = hs.floatValue(); text.setTextMatrix(hScale, b, c, 1, xMarker, yMarker); } if (chunk.isAttribute(Chunk.CHAR_SPACING)) { Float cs = (Float) chunk.getAttribute(Chunk.CHAR_SPACING); text.setCharacterSpacing(cs.floatValue()); } if (chunk.isImage()) { Image image = chunk.getImage(); float matrix[] = image.matrix(chunk.getImageScalePercentage()); matrix[Image.CX] = xMarker + chunk.getImageOffsetX() - matrix[Image.CX]; matrix[Image.CY] = yMarker + chunk.getImageOffsetY() - matrix[Image.CY]; graphics.addImage(image, matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); text.moveText(xMarker + lastBaseFactor + chunk.getImageWidth() - text.getXTLM(), 0); } } if (!chunk.isTabSpace()) xMarker += width; ++chunkStrokeIdx; } if (chunk.font().compareTo(currentFont) != 0) { currentFont = chunk.font(); text.setFontAndSize(currentFont.getFont(), currentFont.size()); } float rise = 0; Object textRender[] = (Object[])chunk.getAttribute(Chunk.TEXTRENDERMODE); int tr = 0; float strokeWidth = 1; BaseColor strokeColor = null; Float fr = (Float)chunk.getAttribute(Chunk.SUBSUPSCRIPT); if (textRender != null) { tr = ((Integer)textRender[0]).intValue() & 3; if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL) text.setTextRenderingMode(tr); if (tr == PdfContentByte.TEXT_RENDER_MODE_STROKE || tr == PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE) { strokeWidth = ((Float)textRender[1]).floatValue(); if (strokeWidth != 1) text.setLineWidth(strokeWidth); strokeColor = (BaseColor)textRender[2]; if (strokeColor == null) strokeColor = color; if (strokeColor != null) text.setColorStroke(strokeColor); } } if (fr != null) rise = fr.floatValue(); if (color != null) text.setColorFill(color); if (rise != 0) text.setTextRise(rise); if (chunk.isImage()) { adjustMatrix = true; } else if (chunk.isHorizontalSeparator()) { PdfTextArray array = new PdfTextArray(); array.add(-glueWidth * 1000f / chunk.font.size() / hScale); text.showText(array); } else if (chunk.isTab()) { PdfTextArray array = new PdfTextArray(); array.add((tabPosition - xMarker) * 1000f / chunk.font.size() / hScale); text.showText(array); } else if (chunk.isTabSpace()) { Float module = (Float)chunk.getAttribute(Chunk.TABSPACE); float increment = module - ((xMarker - text.getXTLM()) % module); xMarker += increment; PdfTextArray array = new PdfTextArray(); array.add(-(increment * 1000f / chunk.font.size() / hScale)); text.showText(array); } // If it is a CJK chunk or Unicode TTF we will have to simulate the // space adjustment. else if (isJustified && numberOfSpaces > 0 && chunk.isSpecialEncoding()) { if (hScale != lastHScale) { lastHScale = hScale; text.setWordSpacing(baseWordSpacing / hScale); text.setCharacterSpacing(baseCharacterSpacing / hScale + text.getCharacterSpacing()); } String s = chunk.toString(); int idx = s.indexOf(' '); if (idx < 0) text.showText(s); else { float spaceCorrection = - baseWordSpacing * 1000f / chunk.font.size() / hScale; PdfTextArray textArray = new PdfTextArray(s.substring(0, idx)); int lastIdx = idx; while ((idx = s.indexOf(' ', lastIdx + 1)) >= 0) { textArray.add(spaceCorrection); textArray.add(s.substring(lastIdx, idx)); lastIdx = idx; } textArray.add(spaceCorrection); textArray.add(s.substring(lastIdx)); text.showText(textArray); } } else { if (isJustified && hScale != lastHScale) { lastHScale = hScale; text.setWordSpacing(baseWordSpacing / hScale); text.setCharacterSpacing(baseCharacterSpacing / hScale + text.getCharacterSpacing()); } text.showText(chunk.toString()); } if (rise != 0) text.setTextRise(0); if (color != null) text.resetRGBColorFill(); if (tr != PdfContentByte.TEXT_RENDER_MODE_FILL) text.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL); if (strokeColor != null) text.resetRGBColorStroke(); if (strokeWidth != 1) text.setLineWidth(1); if (chunk.isAttribute(Chunk.SKEW) || chunk.isAttribute(Chunk.HSCALE)) { adjustMatrix = true; text.setTextMatrix(xMarker, yMarker); } if (chunk.isAttribute(Chunk.CHAR_SPACING)) { text.setCharacterSpacing(baseCharacterSpacing); } if (isTagged(writer) && chunk.accessibleElement != null) { text.closeMCBlock(chunk.accessibleElement); } } if (isJustified) { text.setWordSpacing(0); text.setCharacterSpacing(0); if (line.isNewlineSplit()) lastBaseFactor = 0; } if (adjustMatrix) text.moveText(baseXMarker - text.getXTLM(), 0); currentValues[0] = currentFont; currentValues[1] = new Float(lastBaseFactor); return lastX; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void setThumbnail(final Image image) throws PdfException, DocumentException { writer.addPageDictEntry(PdfName.THUMB, writer.getImageReference(writer.addDirectImageSimple(image))); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void add(final Image image) throws PdfException, DocumentException { if (image.hasAbsoluteY()) { graphics.addImage(image); pageEmpty = false; return; } // if there isn't enough room for the image on this page, save it for the next page if (currentHeight != 0 && indentTop() - currentHeight - image.getScaledHeight() < indentBottom()) { if (!strictImageSequence && imageWait == null) { imageWait = image; return; } newPage(); if (currentHeight != 0 && indentTop() - currentHeight - image.getScaledHeight() < indentBottom()) { imageWait = image; return; } } pageEmpty = false; // avoid endless loops if (image == imageWait) imageWait = null; boolean textwrap = (image.getAlignment() & Image.TEXTWRAP) == Image.TEXTWRAP && !((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE); boolean underlying = (image.getAlignment() & Image.UNDERLYING) == Image.UNDERLYING; float diff = leading / 2; if (textwrap) { diff += leading; } float lowerleft = indentTop() - currentHeight - image.getScaledHeight() -diff; float mt[] = image.matrix(); float startPosition = indentLeft() - mt[4]; if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) startPosition = indentRight() - image.getScaledWidth() - mt[4]; if ((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE) startPosition = indentLeft() + (indentRight() - indentLeft() - image.getScaledWidth()) / 2 - mt[4]; if (image.hasAbsoluteX()) startPosition = image.getAbsoluteX(); if (textwrap) { if (imageEnd < 0 || imageEnd < currentHeight + image.getScaledHeight() + diff) { imageEnd = currentHeight + image.getScaledHeight() + diff; } if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) { // indentation suggested by Pelikan Stephan indentation.imageIndentRight += image.getScaledWidth() + image.getIndentationLeft(); } else { // indentation suggested by Pelikan Stephan indentation.imageIndentLeft += image.getScaledWidth() + image.getIndentationRight(); } } else { if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) startPosition -= image.getIndentationRight(); else if ((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE) startPosition += image.getIndentationLeft() - image.getIndentationRight(); else startPosition += image.getIndentationLeft(); } graphics.addImage(image, mt[0], mt[1], mt[2], mt[3], startPosition, lowerleft - mt[5]); if (!(textwrap || underlying)) { currentHeight += image.getScaledHeight() + diff; flushLines(); text.moveText(0, - (image.getScaledHeight() + diff)); newLine(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addPTable(final PdfPTable ptable) throws DocumentException { ColumnText ct = new ColumnText(isTagged(writer) ? text : writer.getDirectContent()); // if the table prefers to be on a single page, and it wouldn't //fit on the current page, start a new page. if (ptable.getKeepTogether() && !fitsPage(ptable, 0f) && currentHeight > 0) { newPage(); } if (currentHeight == 0) { ct.setAdjustFirstLine(false); } ct.addElement(ptable); boolean he = ptable.isHeadersInEvent(); ptable.setHeadersInEvent(true); int loop = 0; while (true) { ct.setSimpleColumn(indentLeft(), indentBottom(), indentRight(), indentTop() - currentHeight); int status = ct.go(); if ((status & ColumnText.NO_MORE_TEXT) != 0) { if (isTagged(writer)) { text.setTextMatrix(indentLeft(), ct.getYLine()); } else { text.moveText(0, ct.getYLine() - indentTop() + currentHeight); } currentHeight = indentTop() - ct.getYLine(); break; } if (indentTop() - currentHeight == ct.getYLine()) ++loop; else loop = 0; if (loop == 3) { throw new DocumentException(MessageLocalization.getComposedMessage("infinite.table.loop")); } newPage(); if (isTagged(writer)) { ct.setCanvas(text); } } ptable.setHeadersInEvent(he); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
private void addDiv(final PdfDiv div) throws DocumentException { if (floatingElements == null) { floatingElements = new ArrayList<Element>(); } floatingElements.add(div); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
private void flushFloatingElements() throws DocumentException { if (floatingElements != null && !floatingElements.isEmpty()) { ArrayList<Element> cachedFloatingElements = floatingElements; floatingElements = null; FloatLayout fl = new FloatLayout(cachedFloatingElements, false); int loop = 0; while (true) { fl.setSimpleColumn(indentLeft(), indentBottom(), indentRight(), indentTop() - currentHeight); try { int status = fl.layout(isTagged(writer) ? text : writer.getDirectContent(), false); if ((status & ColumnText.NO_MORE_TEXT) != 0) { if (isTagged(writer)) { text.setTextMatrix(indentLeft(), fl.getYLine()); } else { text.moveText(0, fl.getYLine() - indentTop() + currentHeight); } currentHeight = indentTop() - fl.getYLine(); break; } } catch (Exception exc) { return; } if (indentTop() - currentHeight == fl.getYLine() || isPageEmpty()) ++loop; else { loop = 0; } if (loop == 2) { return; } newPage(); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type3Glyph.java
public void addImage(Image image, float a, float b, float c, float d, float e, float f, boolean inlineImage) throws DocumentException { if (!colorized && (!image.isMask() || !(image.getBpc() == 1 || image.getBpc() > 0xff))) throw new DocumentException(MessageLocalization.getComposedMessage("not.colorized.typed3.fonts.only.accept.mask.images")); super.addImage(image, a, b, c, d, e, f, inlineImage); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
public void addPage(Rectangle rect, int rotation) throws DocumentException { PdfRectangle mediabox = new PdfRectangle(rect, rotation); PageResources resources = new PageResources(); PdfPage page = new PdfPage(mediabox, new HashMap<String, PdfRectangle>(), resources.getResources(), 0); page.put(PdfName.TABS, getTabs()); root.addPage(page); ++currentPageNumber; }
// 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/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/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/PdfPatternPainter.java
public void addImage(Image image, float a, float b, float c, float d, float e, float f) throws DocumentException { if (stencil && !image.isMask()) checkNoColor(); super.addImage(image, a, b, c, d, e, f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFormsImp.java
public void copyDocumentFields(PdfReader reader) throws DocumentException { if (!reader.isOpenedWithFullPermissions()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password")); 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()); fields.add(reader.getAcroFields()); updateCalculationOrder(reader); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDiv.java
public int layout(final PdfContentByte canvas, boolean useAscender, boolean simulate, final float llx, final float lly, final float urx, final float ury) throws DocumentException { float leftX = Math.min(llx, urx); float maxY = Math.max(lly, ury); float minY = Math.min(lly, ury); float rightX = Math.max(llx, urx); float yLine = maxY; boolean contentCutByFixedHeight = false; if (width != null && width > 0) { if (width < rightX - leftX) { rightX = leftX + width; } else if (width > rightX - leftX) { return ColumnText.NO_MORE_COLUMN; } } else if (percentageWidth != null) { contentWidth = (rightX - leftX) * percentageWidth; rightX = leftX + contentWidth; } if (height != null && height > 0) { if (height < maxY - minY) { minY = maxY - height; contentCutByFixedHeight = true; } else if (height > maxY - minY) { return ColumnText.NO_MORE_COLUMN; } } else if (percentageHeight != null) { if (percentageHeight < 1.0) { contentCutByFixedHeight = true; } contentHeight = (maxY - minY) * percentageHeight; minY = maxY - contentHeight; } if (!simulate && position == PdfDiv.PositionType.RELATIVE) { Float translationX = null; if (left != null) { translationX = left; } else if (right != null) { translationX = -right; } else { translationX = 0f; } Float translationY = null; if (top != null) { translationY = -top; } else if (bottom != null) { translationY = bottom; } else { translationY = 0f; } canvas.saveState(); canvas.transform(new AffineTransform(1f, 0, 0, 1f, translationX, translationY)); } if (!simulate) { if (backgroundColor != null && getActualWidth() > 0 && getActualHeight() > 0) { float backgroundWidth = getActualWidth(); float backgroundHeight = getActualHeight(); if (width != null) { backgroundWidth = width > 0 ? width : 0; } if (height != null) { backgroundHeight = height > 0 ? height : 0; } if (backgroundWidth > 0 && backgroundHeight > 0) { Rectangle background = new Rectangle(leftX, maxY - backgroundHeight, leftX + backgroundWidth, maxY); background.setBackgroundColor(backgroundColor); canvas.rectangle(background); } } } if (percentageWidth == null) { contentWidth = 0; } if (percentageHeight == null) { contentHeight = 0; } minY += paddingBottom; leftX += paddingLeft; rightX -= paddingRight; yLine -= paddingTop; int status = ColumnText.NO_MORE_TEXT; if (!content.isEmpty()) { FloatLayout floatLayout = null; if (this.floatLayout == null) { ArrayList<Element> floatingElements = new ArrayList<Element>(); floatingElements.addAll(content); if (simulate) { floatLayout = new FloatLayout(floatingElements, useAscender); } else { floatLayout = this.floatLayout = new FloatLayout(floatingElements, useAscender); } } else { if (simulate) { ArrayList<Element> floatingElements = new ArrayList<Element>(); floatingElements.addAll(this.floatLayout.content); floatLayout = new FloatLayout(floatingElements, useAscender); } else { floatLayout = this.floatLayout; } } floatLayout.setSimpleColumn(leftX, minY, rightX, yLine); status = floatLayout.layout(canvas, simulate); yLine = floatLayout.getYLine(); if (percentageWidth == null && contentWidth < floatLayout.getFilledWidth()) { contentWidth = floatLayout.getFilledWidth(); } } if (!simulate && position == PdfDiv.PositionType.RELATIVE) { canvas.restoreState(); } yLine -= paddingBottom; if (percentageHeight == null) { contentHeight = maxY - yLine; } if (percentageWidth == null) { contentWidth += paddingLeft + paddingRight; } return contentCutByFixedHeight ? ColumnText.NO_MORE_TEXT : status; }
// 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/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 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 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/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 void loadCMaps() throws DocumentException { try { fontDesc = allFonts.get(fontName); hMetrics = (IntHashtable)fontDesc.get("W"); vMetrics = (IntHashtable)fontDesc.get("W2"); String registry = (String)fontDesc.get("Registry"); uniMap = ""; for (String name : registryNames.get(registry + "_Uni")) { uniMap = name; if (name.endsWith("V") && vertical) break; if (!name.endsWith("V") && !vertical) break; } if (cidDirect) { cidUni = CMapCache.getCachedCMapCidUni(uniMap); } else { uniCid = CMapCache.getCachedCMapUniCid(uniMap); cidByte = CMapCache.getCachedCMapCidByte(CMap); } } catch (Exception ex) { throw new DocumentException(ex); } }
// 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/PdfPTable.java
public void setWidths(final float relativeWidths[]) throws DocumentException { if (relativeWidths.length != getNumberOfColumns()) throw new DocumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); this.relativeWidths = new float[relativeWidths.length]; System.arraycopy(relativeWidths, 0, this.relativeWidths, 0, relativeWidths.length); absoluteWidths = new float[relativeWidths.length]; totalHeight = 0; calculateWidths(); calculateHeights(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setWidths(final int relativeWidths[]) throws DocumentException { float tb[] = new float[relativeWidths.length]; for (int k = 0; k < relativeWidths.length; ++k) tb[k] = relativeWidths[k]; setWidths(tb); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setTotalWidth(final float columnWidth[]) throws DocumentException { if (columnWidth.length != getNumberOfColumns()) throw new DocumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); totalWidth = 0; for (int k = 0; k < columnWidth.length; ++k) totalWidth += columnWidth[k]; setWidths(columnWidth); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setWidthPercentage(final float columnWidth[], final Rectangle pageSize) throws DocumentException { if (columnWidth.length != getNumberOfColumns()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); float totalWidth = 0; for (int k = 0; k < columnWidth.length; ++k) totalWidth += columnWidth[k]; widthPercentage = totalWidth / (pageSize.getRight() - pageSize.getLeft()) * 100f; setWidths(columnWidth); }
// 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/FloatLayout.java
public int layout(PdfContentByte canvas, boolean simulate) throws DocumentException { compositeColumn.setCanvas(canvas); int status = ColumnText.NO_MORE_TEXT; filledWidth = 0; ArrayList<Element> floatingElements = new ArrayList<Element>(); List<Element> content = simulate ? new ArrayList<Element>(this.content) : this.content; while (!content.isEmpty()) { if (content.get(0) instanceof PdfDiv) { PdfDiv floatingElement = (PdfDiv)content.get(0); if (floatingElement.getFloatType() == PdfDiv.FloatType.LEFT || floatingElement.getFloatType() == PdfDiv.FloatType.RIGHT) { floatingElements.add(floatingElement); content.remove(0); } else { if (!floatingElements.isEmpty()) { status = floatingLayout(floatingElements, simulate); if ((status & ColumnText.NO_MORE_TEXT) == 0) { break; } } content.remove(0); status = floatingElement.layout(canvas, useAscender, true, floatLeftX, minY, floatRightX, yLine); if (!simulate) { canvas.openMCBlock(floatingElement); status = floatingElement.layout(canvas, useAscender, simulate, floatLeftX, minY, floatRightX, yLine); canvas.closeMCBlock(floatingElement); } yLine -= floatingElement.getActualHeight(); if (floatingElement.getActualWidth() > filledWidth) { filledWidth = floatingElement.getActualWidth(); } if ((status & ColumnText.NO_MORE_TEXT) == 0) { content.add(0, floatingElement); break; } } } else { floatingElements.add(content.get(0)); content.remove(0); } } if ((status & ColumnText.NO_MORE_TEXT) != 0 && !floatingElements.isEmpty()) { status = floatingLayout(floatingElements, simulate); } content.addAll(0, floatingElements); return status; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FloatLayout.java
private int floatingLayout(List<Element> floatingElements, boolean simulate) throws DocumentException { int status = ColumnText.NO_MORE_TEXT; float minYLine = yLine; float leftWidth = 0; float rightWidth = 0; ColumnText currentCompositeColumn = compositeColumn; if (simulate) { currentCompositeColumn = ColumnText.duplicate(compositeColumn); } while (!floatingElements.isEmpty()) { Element nextElement = floatingElements.get(0); floatingElements.remove(0); if (nextElement instanceof PdfDiv) { PdfDiv floatingElement = (PdfDiv) nextElement; status = floatingElement.layout(compositeColumn.getCanvas(), useAscender, true, floatLeftX, minY, floatRightX, yLine); if ((status & ColumnText.NO_MORE_TEXT) == 0) { yLine = minYLine; floatLeftX = leftX; floatRightX = rightX; status = floatingElement.layout(compositeColumn.getCanvas(), useAscender, true, floatLeftX, minY, floatRightX, yLine); if ((status & ColumnText.NO_MORE_TEXT) == 0) { floatingElements.add(0, floatingElement); break; } } if (floatingElement.getFloatType() == PdfDiv.FloatType.LEFT) { status = floatingElement.layout(compositeColumn.getCanvas(), useAscender, simulate, floatLeftX, minY, floatRightX, yLine); floatLeftX += floatingElement.getActualWidth(); leftWidth += floatingElement.getActualWidth(); } else if (floatingElement.getFloatType() == PdfDiv.FloatType.RIGHT) { status = floatingElement.layout(compositeColumn.getCanvas(), useAscender, simulate, floatRightX - floatingElement.getActualWidth() - 0.01f, minY, floatRightX, yLine); floatRightX -= floatingElement.getActualWidth(); rightWidth += floatingElement.getActualWidth(); } minYLine = Math.min(minYLine, yLine - floatingElement.getActualHeight()); } else { if (nextElement instanceof Spaceable) { yLine -= ((Spaceable) nextElement).getSpacingBefore(); } if (simulate) { if (nextElement instanceof PdfPTable) currentCompositeColumn.addElement(new PdfPTable((PdfPTable)nextElement)); else currentCompositeColumn.addElement(nextElement); } else { currentCompositeColumn.addElement(nextElement); } if (yLine > minYLine) currentCompositeColumn.setSimpleColumn(floatLeftX, yLine, floatRightX, minYLine); else currentCompositeColumn.setSimpleColumn(floatLeftX, yLine, floatRightX, minY); currentCompositeColumn.setFilledWidth(0); status = currentCompositeColumn.go(simulate); if (yLine > minYLine && (floatLeftX > leftX || floatRightX < rightX) && (status & ColumnText.NO_MORE_TEXT) == 0) { yLine = minYLine; floatLeftX = leftX; floatRightX = rightX; if (leftWidth != 0 && rightWidth != 0) { filledWidth = rightX - leftX; } else { if (leftWidth > filledWidth) { filledWidth = leftWidth; } if (rightWidth > filledWidth) { filledWidth = rightWidth; } } leftWidth = 0; rightWidth = 0; if (simulate && nextElement instanceof PdfPTable) { currentCompositeColumn.addElement(new PdfPTable((PdfPTable)nextElement)); } currentCompositeColumn.setSimpleColumn(floatLeftX, yLine, floatRightX, minY); status = currentCompositeColumn.go(simulate); minYLine = currentCompositeColumn.getYLine() + currentCompositeColumn.getDescender(); yLine = minYLine; if (currentCompositeColumn.getFilledWidth() > filledWidth) { filledWidth = currentCompositeColumn.getFilledWidth(); } } else { if (rightWidth > 0) { rightWidth += currentCompositeColumn.getFilledWidth(); } else if (leftWidth > 0) { leftWidth += currentCompositeColumn.getFilledWidth(); } else if (currentCompositeColumn.getFilledWidth() > filledWidth) { filledWidth = currentCompositeColumn.getFilledWidth(); } minYLine = Math.min(currentCompositeColumn.getYLine() + currentCompositeColumn.getDescender(), minYLine); yLine = currentCompositeColumn.getYLine() + currentCompositeColumn.getDescender(); } if ((status & ColumnText.NO_MORE_TEXT) == 0) { if (!simulate) { floatingElements.addAll(0, currentCompositeColumn.getCompositeElements()); currentCompositeColumn.getCompositeElements().clear(); } else { floatingElements.add(0, nextElement); currentCompositeColumn.setText(null); } break; } else { currentCompositeColumn.setText(null); } } } if (leftWidth != 0 && rightWidth != 0) { filledWidth = rightX - leftX; } else { if (leftWidth > filledWidth) { filledWidth = leftWidth; } if (rightWidth > filledWidth) { filledWidth = rightWidth; } } yLine = minYLine; floatLeftX = leftX; floatRightX = rightX; return status; }
// 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 setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final boolean strength128Bits) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(userPassword, ownerPassword, permissions, strength128Bits ? PdfWriter.STANDARD_ENCRYPTION_128 : PdfWriter.STANDARD_ENCRYPTION_40); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final byte userPassword[], final byte ownerPassword[], final int permissions, final int encryptionType) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(userPassword, ownerPassword, permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final boolean strength, final String userPassword, final String ownerPassword, final int permissions) throws DocumentException { setEncryption(DocWriter.getISOBytes(userPassword), DocWriter.getISOBytes(ownerPassword), permissions, strength); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final int encryptionType, final String userPassword, final String ownerPassword, final int permissions) throws DocumentException { setEncryption(DocWriter.getISOBytes(userPassword), DocWriter.getISOBytes(ownerPassword), permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setEncryption(final Certificate[] certs, final int[] permissions, final int encryptionType) throws DocumentException { if (stamper.isAppend()) throw new DocumentException(MessageLocalization.getComposedMessage("append.mode.does.not.support.changing.the.encryption.status")); if (stamper.isContentWritten()) throw new DocumentException(MessageLocalization.getComposedMessage("content.was.already.written.to.the.output")); stamper.setEncryption(certs, permissions, encryptionType); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setThumbnail(final Image image, final int page) throws PdfException, DocumentException { stamper.setThumbnail(image, page); }
// 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/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/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/Document.java
public boolean add(Element element) throws DocumentException { if (close) { throw new DocumentException(MessageLocalization.getComposedMessage("the.document.has.been.closed.you.can.t.add.any.elements")); } if (!open && element.isContent()) { throw new DocumentException(MessageLocalization.getComposedMessage("the.document.is.not.open.yet.you.can.only.add.meta.information")); } boolean success = false; if (element instanceof ChapterAutoNumber) { chapternumber = ((ChapterAutoNumber)element).setAutomaticNumber(chapternumber); } for (DocListener listener : listeners) { success |= listener.add(element); } if (element instanceof LargeElement) { LargeElement e = (LargeElement)element; if (!e.isComplete()) e.flushContent(); } return success; }
// 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 { worker.carriageReturn(); if (worker.isPendingLI()) worker.endElement(HtmlTags.LI); worker.setSkipText(true); worker.updateChain(tag, attrs);; worker.pushToStack(worker.createList(tag)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); if (worker.isPendingLI()) worker.endElement(HtmlTags.LI); worker.setSkipText(false); worker.updateChain(tag); worker.processList(); }
// 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 { worker.carriageReturn(); worker.pushToStack(worker.createLineSeparator(attrs)); }
// 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 { worker.carriageReturn(); if (!attrs.containsKey(HtmlTags.SIZE)) { int v = 7 - Integer.parseInt(tag.substring(1)); attrs.put(HtmlTags.SIZE, Integer.toString(v)); } worker.updateChain(tag, attrs); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); worker.updateChain(tag); }
// 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 { worker.carriageReturn(); if (worker.isPendingLI()) worker.endElement(tag); worker.setSkipText(false); worker.setPendingLI(true); worker.updateChain(tag, attrs); worker.pushToStack(worker.createListItem()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); worker.setPendingLI(false); worker.setSkipText(true); worker.updateChain(tag); worker.processListItem(); }
// 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 { worker.carriageReturn(); if (!attrs.containsKey(HtmlTags.FACE)) { attrs.put(HtmlTags.FACE, "Courier"); } worker.updateChain(tag, attrs); worker.setInsidePRE(true); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); worker.updateChain(tag); worker.setInsidePRE(false); }
// 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 { worker.carriageReturn(); worker.updateChain(tag, attrs); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); worker.updateChain(tag); }
// 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 { worker.carriageReturn(); TableWrapper table = new TableWrapper(attrs); worker.pushToStack(table); worker.pushTableState(); worker.setPendingTD(false); worker.setPendingTR(false); worker.setSkipText(true); // Table alignment should not affect children elements, thus remove attrs.remove(HtmlTags.ALIGN); // In case this is a nested table reset colspan and rowspan attrs.put(HtmlTags.COLSPAN, "1"); attrs.put(HtmlTags.ROWSPAN, "1"); worker.updateChain(tag, attrs); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); if (worker.isPendingTR()) worker.endElement(HtmlTags.TR); worker.updateChain(tag); worker.processTable(); worker.popTableState(); worker.setSkipText(false); }
// 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 { worker.carriageReturn(); if (worker.isPendingTR()) worker.endElement(tag); worker.setSkipText(true); worker.setPendingTR(true); worker.updateChain(tag, attrs); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); if (worker.isPendingTD()) worker.endElement(HtmlTags.TD); worker.setPendingTR(false); worker.updateChain(tag); worker.processRow(); worker.setSkipText(true); }
// 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 { worker.carriageReturn(); if (worker.isPendingTD()) worker.endElement(tag); worker.setSkipText(false); worker.setPendingTD(true); worker.updateChain(HtmlTags.TD, attrs); worker.pushToStack(worker.createCell(tag)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLTagProcessors.java
public void endElement(HTMLWorker worker, String tag) throws DocumentException { worker.carriageReturn(); worker.setPendingTD(false); worker.updateChain(HtmlTags.TD); worker.setSkipText(true); }
// 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 carriageReturn() throws DocumentException { if (currentParagraph == null) return; if (stack.empty()) document.add(currentParagraph); else { Element obj = stack.pop(); if (obj instanceof TextElementArray) { TextElementArray current = (TextElementArray) obj; current.add(currentParagraph); } stack.push(obj); } currentParagraph = null; }
// 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 void processList() throws DocumentException { if (stack.empty()) return; Element obj = stack.pop(); if (!(obj instanceof com.itextpdf.text.List)) { stack.push(obj); return; } if (stack.empty()) document.add(obj); else ((TextElementArray) stack.peek()).add(obj); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void processListItem() throws DocumentException { if (stack.empty()) return; Element obj = stack.pop(); if (!(obj instanceof ListItem)) { stack.push(obj); return; } if (stack.empty()) { document.add(obj); return; } ListItem item = (ListItem) obj; Element list = stack.pop(); if (!(list instanceof com.itextpdf.text.List)) { stack.push(list); return; } ((com.itextpdf.text.List) list).add(item); item.adjustListSymbolFont(); stack.push(list); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void processImage(final Image img, final Map<String, String> attrs) throws DocumentException { ImageProcessor processor = (ImageProcessor)providers.get(HTMLWorker.IMG_PROCESSOR); if (processor == null || !processor.process(img, attrs, chain, document)) { String align = attrs.get(HtmlTags.ALIGN); if (align != null) { carriageReturn(); } if (currentParagraph == null) { currentParagraph = createParagraph(); } currentParagraph.add(new Chunk(img, 0, 0, true)); currentParagraph.setAlignment(HtmlUtilities.alignmentValue(align)); if (align != null) { carriageReturn(); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void processTable() throws DocumentException{ TableWrapper table = (TableWrapper) stack.pop(); PdfPTable tb = table.createTable(); tb.setSplitRows(true); if (stack.empty()) document.add(tb); else ((TextElementArray) stack.peek()).add(tb); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public boolean add(final Element element) throws DocumentException { objectList.add(element); return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
public boolean add(Element element) throws DocumentException { return false; }
40
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Meta.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Chunk.java
catch (DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Rectangle.java
catch (DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/draw/VerticalPositionMark.java
catch (DocumentException e) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch (DocumentException de) { // do nothing }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPCell.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDiv.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
catch (DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/List.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Annotation.java
catch (DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/MarkedSection.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Anchor.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/MarkedObject.java
catch(DocumentException de) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Phrase.java
catch(DocumentException de) { return false; }
25
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPCell.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
25
unknown (Lib) EOFException 16
            
// 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/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/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 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)); }
0 0 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
catch(EOFException eof) { numDirectories--; break; }
0 0
unknown (Lib) EmptyStackException 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public T peek() { if (size() == 0) throw new EmptyStackException(); return get(size() - 1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
public T pop() { if (size() == 0) throw new EmptyStackException(); T ret = get(size() - 1); remove(size() - 1); return ret; }
0 0 0 0 0
runtime (Lib) Error 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
private String decodeSingleCID(byte[] bytes, int offset, int len){ if (toUnicodeCmap != null){ if (offset + len > bytes.length) throw new ArrayIndexOutOfBoundsException(MessageLocalization.getComposedMessage("invalid.index.1", offset + len)); String s = toUnicodeCmap.lookup(bytes, offset, len); if (s != null) return s; if (len != 1 || cidbyte2uni == null) return null; } if (len == 1){ if (cidbyte2uni == null) return ""; else return new String(cidbyte2uni, 0xff & bytes[offset], 1); } throw new Error("Multi-byte glyphs not implemented yet"); }
// 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; } }
0 0 0 0 0
checked (Lib) Exception 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Version.java
public static Version getInstance() { if (version == null) { version = new Version(); try { Class<?> klass = Class.forName("com.itextpdf.license.LicenseKey"); Method m = klass.getMethod("getLicenseeInfo"); String[] info = (String[])m.invoke(klass.newInstance()); if (info[3] != null && info[3].trim().length() > 0) { version.key = info[3]; } else { version.key = "Trial version "; if (info[5] == null) { version.key += "unauthorised"; } else { version.key += info[5]; } } if (info[4] != null && info[4].trim().length() > 0) { version.iTextVersion = info[4]; } else if (info[2] != null && info[2].trim().length() > 0) { version.iTextVersion += " (" + info[2]; if (!version.key.toLowerCase().startsWith("trial")) { version.iTextVersion += "; licensed version)"; } else { version.iTextVersion += "; " + version.key + ")"; } } // fall back to contact name, if company name is unavailable else if (info[0] != null && info[0].trim().length() > 0) { version.iTextVersion += " (" + info[0]; if (!version.key.toLowerCase().startsWith("trial")) { // we shouldn't have a licensed version without company name, // but let's account for it anyway version.iTextVersion += "; licensed version)"; } else { version.iTextVersion += "; " + version.key + ")"; } } else { throw new Exception(); } } catch (Exception e) { version.iTextVersion += " (AGPL-version)"; } } return version; }
0 4
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
private void invokeOperator(PdfLiteral operator, ArrayList<PdfObject> operands) throws Exception{ ContentOperator op = operators.get(operator.toString()); if (op == null) op = operators.get(DEFAULTOPERATOR); op.invoke(this, operator, operands); }
// 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 Exception { processor.beginMarkedContent((PdfName)operands.get(0), new PdfDictionary()); }
// 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 Exception { PdfObject properties = operands.get(1); processor.beginMarkedContent((PdfName)operands.get(0), getPropertiesDictionary(properties, processor.resources)); }
// 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 Exception { processor.endMarkedContent(); }
246
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/AsianFontMapper.java
catch (Exception e) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/DefaultFontMapper.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/DefaultFontMapper.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { throw new IllegalArgumentException(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { if (fill) cb.setColorFill(BaseColor.GRAY); else cb.setColorStroke(BaseColor.GRAY); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { if (fill) cb.setColorFill(BaseColor.GRAY); else cb.setColorStroke(BaseColor.GRAY); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Utilities.java
catch (Exception e) { return new File(filename).toURI().toURL(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/EntitiesToSymbol.java
catch(Exception exception) { return new Chunk(e, font); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/ByteBufferRandomAccessSource.java
catch (Exception e) { // This really is a show stopper on windows //e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ImgJBIG2.java
catch (Exception e) { //ignore }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Version.java
catch (Exception e) { version.iTextVersion += " (AGPL-version)"; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/error_messages/MessageLocalization.java
catch (Exception ex) { // do nothing }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/error_messages/MessageLocalization.java
catch (Exception exx) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e){ System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); return -1; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e) {}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception e) {}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception ex ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( Exception ex ){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (Exception eofe) { throw new RuntimeException("No reference line present."); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (Exception eofe) { ++fails; break; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (Exception eofe) { return; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFDirectory.java
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/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { // do nothing }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception ex) { if (--maxExc < 0) break; continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { cmapRet = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
catch (Exception e) { //empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEAN.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FdfReader.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FdfReader.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/SimplePatternParser.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/Hyphenator.java
catch (Exception e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/Hyphenator.java
catch (Exception e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { ret[k] = ""; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { // empty }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfICCBased.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRTokeniser.java
catch (Exception ioe) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAcroForm.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAction.java
catch (Exception e) { js.put(PdfName.JS, new PdfString(code)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new RuntimeException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/crypto/AESCipher.java
catch (Exception ex) { return outp; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
catch (Exception e) {}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFont.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPattern.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfName.java
catch (Exception e) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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
catch(Exception ee){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
catch(Exception ee){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
catch(Exception ee){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
catch(Exception ee){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/events/FieldPositioningEvents.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/GlyphList.java
catch (Exception e) { System.err.println("glyphlist.txt loading error: " + e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/GlyphList.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/GlyphList.java
catch (Exception ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { acroForm = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne){ throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()), ne); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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
catch(Exception ee){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { obj = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { obj = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) {}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { tokens.seek(pos); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { return fout.toByteArray(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { if (strict) return null; return out.toByteArray(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFontSubset.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDate.java
catch (Exception e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception ee) { throw new DocumentException(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw ExceptionConverter.convertException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (Exception exc) { return; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFileSpecification.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfdfReader.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReaderInstance.java
catch (Exception e) { //Empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentReaderTool.java
catch (Exception e){ e.printStackTrace(System.err); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontUnicode.java
catch (Exception e) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch(Exception x){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContents.java
catch (Exception e) { throw new BadPdfFormatException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeCodabar.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapParserEx.java
catch (Exception ex) { if (--maxExc < 0) break; continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapParserEx.java
catch (Exception ex) {}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
catch (Exception e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RadioCheckField.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new DocumentException(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFont.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeInter25.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
catch (Exception e) { //empty }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
catch (Exception ee) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOffline.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { return e.getMessage(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateVerification.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvTimestamp.java
catch(Exception e) { throw new GeneralSecurityException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception ex) { // ignore }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception ex) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
catch(Exception ex){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerification.java
catch (Exception e) { // do nothing }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OcspClientBouncyCastle.java
catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (Exception e) { LOGGER.info("Skipped CRL url: " + e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (Exception e) { LOGGER.info("Skipped CRL: " + e.getMessage() + " for " + urlt); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (Exception e) { // This really is a show stopper on windows //e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Font.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch (Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch(Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { // default leading paragraph.setLeading(0, 1.5f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/ElementFactory.java
catch (Exception e) { list.setAutoindent(true); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/TableWrapper.java
catch (Exception e) { // fail silently }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Jpeg2000.java
catch(Exception e){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch (Exception e) { //empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch (Exception e) { //empty on purpose }
107
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/DefaultFontMapper.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { throw new IllegalArgumentException(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (Exception eofe) { throw new RuntimeException("No reference line present."); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEAN.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type1Font.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfICCBased.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAcroForm.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new RuntimeException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPattern.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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/events/FieldPositioningEvents.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne){ throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()), ne); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception ee) { throw new DocumentException(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new DocumentException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw ExceptionConverter.convertException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContents.java
catch (Exception e) { throw new BadPdfFormatException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeCodabar.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RadioCheckField.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new DocumentException(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFont.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeInter25.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOffline.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvTimestamp.java
catch(Exception e) { throw new GeneralSecurityException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Font.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch (Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch(Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (Exception e) { throw new ExceptionConverter(e); }
92
runtime (Domain) ExceptionConverter
public class ExceptionConverter extends RuntimeException {
    private static final long serialVersionUID = 8657630363395849399L;
	/** we keep a handle to the wrapped exception */
    private Exception ex;
    /** prefix for the exception */
    private String prefix;

    /**
     * Construct a RuntimeException based on another Exception
     * @param ex the exception that has to be turned into a RuntimeException
     */
    public ExceptionConverter(Exception ex) {
        super(ex);
        this.ex = ex;
        prefix = (ex instanceof RuntimeException) ? "" : "ExceptionConverter: ";
    }

    /**
     * Convert an Exception into an unchecked exception. Return the exception if it is
     * already an unchecked exception or return an ExceptionConverter wrapper otherwise
     *
     * @param ex the exception to convert
     * @return an unchecked exception 
     * @since 2.1.6
     */
    public static final RuntimeException convertException(Exception ex) {
        if (ex instanceof RuntimeException) {
            return (RuntimeException) ex;
        }
        return new ExceptionConverter(ex);
    }

    /**
     * and allow the user of ExceptionConverter to get a handle to it. 
     * @return the original exception
     */
    public Exception getException() {
        return ex;
    }

    /**
     * We print the message of the checked exception 
     * @return message of the original exception
     */
    public String getMessage() {
        return ex.getMessage();
    }

    /**
     * and make sure we also produce a localized version
     * @return localized version of the message
     */
    public String getLocalizedMessage() {
        return ex.getLocalizedMessage();
    }

    /**
     * The toString() is changed to be prefixed with ExceptionConverter 
     * @return String version of the exception
     */
    public String toString() {
        return prefix + ex;
    }

    /** we have to override this as well */
    public void printStackTrace() {
        printStackTrace(System.err);
    }

    /**
     * here we prefix, with s.print(), not s.println(), the stack
     * trace with "ExceptionConverter:" 
     * @param s
     */
    public void printStackTrace(java.io.PrintStream s) {
        synchronized (s) {
            s.print(prefix);
            ex.printStackTrace(s);
        }
    }

    /**
     * Again, we prefix the stack trace with "ExceptionConverter:" 
     * @param s
     */
    public void printStackTrace(java.io.PrintWriter s) {
        synchronized (s) {
            s.print(prefix);
            ex.printStackTrace(s);
        }
    }

    /**
     * requests to fill in the stack trace we will have to ignore.
     * We can't throw an exception here, because this method
     * is called by the constructor of Throwable 
     * @return a Throwable
     */
    public Throwable fillInStackTrace() {
        return this;
    }
}
161
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/DefaultFontMapper.java
public BaseFont awtToPdf(Font font) { try { BaseFontParameters p = getBaseFontParameters(font.getFontName()); if (p != null) return BaseFont.createFont(p.fontName, p.encoding, p.embedded, p.cached, p.ttfAfm, p.pfb); String fontKey = null; String logicalName = font.getName(); if (logicalName.equalsIgnoreCase("DialogInput") || logicalName.equalsIgnoreCase("Monospaced") || logicalName.equalsIgnoreCase("Courier")) { if (font.isItalic()) { if (font.isBold()) { fontKey = BaseFont.COURIER_BOLDOBLIQUE; } else { fontKey = BaseFont.COURIER_OBLIQUE; } } else { if (font.isBold()) { fontKey = BaseFont.COURIER_BOLD; } else { fontKey = BaseFont.COURIER; } } } else if (logicalName.equalsIgnoreCase("Serif") || logicalName.equalsIgnoreCase("TimesRoman")) { if (font.isItalic()) { if (font.isBold()) { fontKey = BaseFont.TIMES_BOLDITALIC; } else { fontKey = BaseFont.TIMES_ITALIC; } } else { if (font.isBold()) { fontKey = BaseFont.TIMES_BOLD; } else { fontKey = BaseFont.TIMES_ROMAN; } } } else { // default, this catches Dialog and SansSerif if (font.isItalic()) { if (font.isBold()) { fontKey = BaseFont.HELVETICA_BOLDOBLIQUE; } else { fontKey = BaseFont.HELVETICA_OBLIQUE; } } else { if (font.isBold()) { fontKey = BaseFont.HELVETICA_BOLD; } else { fontKey = BaseFont.HELVETICA; } } } return BaseFont.createFont(fontKey, BaseFont.CP1252, false); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
public static Image getInstance(final Image image) { if (image == null) return null; try { Class<? extends Image> cs = image.getClass(); Constructor<? extends Image> constructor = cs .getDeclaredConstructor(new Class[] { Image.class }); return constructor.newInstance(new Object[] { image }); } catch (Exception e) { throw new ExceptionConverter(e); } }
// 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/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
private void read24Bit(byte[] bdata) { // Padding bytes at the end of each scanline int padding = 0; // width * bitsPerPixel should be divisible by 32 int bitsPerScanline = width * 24; if ( bitsPerScanline%32 != 0) { padding = (bitsPerScanline/32 + 1)*32 - bitsPerScanline; padding = (int)Math.ceil(padding/8.0); } int imSize = (width * 3 + 3) / 4 * 4 * height; // Read till we have the whole image byte values[] = new byte[imSize]; try { int bytesRead = 0; while (bytesRead < imSize) { int r = inputStream.read(values, bytesRead, imSize - bytesRead); if (r < 0) break; bytesRead += r; } } catch (IOException ioe) { throw new ExceptionConverter(ioe); } int l=0, count; if (isBottomUp) { int max = width*height*3-1; count = -padding; for (int i=0; i<height; i++) { l = max - (i+1)*width*3 + 1; count += padding; for (int j=0; j<width; j++) { bdata[l + 2] = values[count++]; bdata[l + 1] = values[count++]; bdata[l] = values[count++]; l += 3; } } } else { count = -padding; for (int i=0; i<height; i++) { count += padding; for (int j=0; j<width; j++) { bdata[l + 2] = values[count++]; bdata[l + 1] = values[count++]; bdata[l] = values[count++]; l += 3; } } } }
// 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/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/JBIG2Image.java
public static Image getJbig2Image(RandomAccessFileOrArray ra, int page) { if (page < 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.page.number.must.be.gt.eq.1")); try { JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.read(); JBIG2SegmentReader.JBIG2Page p = sr.getPage(page); Image img = new ImgJBIG2(p.pageBitmapWidth, p.pageBitmapHeight, p.getData(true), sr.getGlobal(true)); return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
public static int getNumberOfPages(RandomAccessFileOrArray ra) { try { JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.read(); return sr.numberOfPages(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
public BaseFont getFont() { if (font != null) return font; Font ff2 = FontFactory.getFont(faceName, BaseFont.CP1252, true, 10, ((italic != 0) ? Font.ITALIC : 0) | ((bold != 0) ? Font.BOLD : 0)); font = ff2.getBaseFont(); if (font != null) return font; String fontName; if (faceName.indexOf("courier") != -1 || faceName.indexOf("terminal") != -1 || faceName.indexOf("fixedsys") != -1) { fontName = fontNames[MARKER_COURIER + italic + bold]; } else if (faceName.indexOf("ms sans serif") != -1 || faceName.indexOf("arial") != -1 || faceName.indexOf("system") != -1) { fontName = fontNames[MARKER_HELVETICA + italic + bold]; } else if (faceName.indexOf("arial black") != -1) { fontName = fontNames[MARKER_HELVETICA + italic + MARKER_BOLD]; } else if (faceName.indexOf("times") != -1 || faceName.indexOf("ms serif") != -1 || faceName.indexOf("roman") != -1) { fontName = fontNames[MARKER_TIMES + italic + bold]; } else if (faceName.indexOf("symbol") != -1) { fontName = fontNames[MARKER_SYMBOL]; } else { int pitch = pitchAndFamily & 3; int family = (pitchAndFamily >> 4) & 7; switch (family) { case FF_MODERN: fontName = fontNames[MARKER_COURIER + italic + bold]; break; case FF_ROMAN: fontName = fontNames[MARKER_TIMES + italic + bold]; break; case FF_SWISS: case FF_SCRIPT: case FF_DECORATIVE: fontName = fontNames[MARKER_HELVETICA + italic + bold]; break; default: { switch (pitch) { case FIXED_PITCH: fontName = fontNames[MARKER_COURIER + italic + bold]; break; default: fontName = fontNames[MARKER_HELVETICA + italic + bold]; break; } } } } try { font = BaseFont.createFont(fontName, "Cp1252", false); } catch (Exception e) { throw new ExceptionConverter(e); } return font; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
public static int getNumberOfPages(RandomAccessFileOrArray s) { try { return TIFFDirectory.getNumDirectories(s); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
public static Image getTiffImage(RandomAccessFileOrArray s, int page, boolean direct) { if (page < 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.page.number.must.be.gt.eq.1")); try { TIFFDirectory dir = new TIFFDirectory(s, page - 1); if (dir.isTagPresent(TIFFConstants.TIFFTAG_TILEWIDTH)) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("tiles.are.not.supported")); int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: case TIFFConstants.COMPRESSION_CCITTFAX3: case TIFFConstants.COMPRESSION_CCITTFAX4: break; default: return getTiffImageColor(dir, s); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } Image img = null; long tiffT4Options = 0; long tiffT6Options = 0; int fillOrder = 1; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; float XYRatio = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); if (resolutionUnit == TIFFConstants.RESUNIT_NONE) { if (dpiY != 0) XYRatio = (float)dpiX / (float)dpiY; dpiX = 0; dpiY = 0; } int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int params = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_PHOTOMETRIC)) { long photo = dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); if (photo == TIFFConstants.PHOTOMETRIC_MINISBLACK) params |= Image.CCITT_BLACKIS1; } int imagecomp = 0; switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: imagecomp = Image.CCITTG3_1D; params |= Image.CCITT_ENCODEDBYTEALIGN | Image.CCITT_ENDOFBLOCK; break; case TIFFConstants.COMPRESSION_CCITTFAX3: imagecomp = Image.CCITTG3_1D; params |= Image.CCITT_ENDOFLINE | Image.CCITT_ENDOFBLOCK; TIFFField t4OptionsField = dir.getField(TIFFConstants.TIFFTAG_GROUP3OPTIONS); if (t4OptionsField != null) { tiffT4Options = t4OptionsField.getAsLong(0); if ((tiffT4Options & TIFFConstants.GROUP3OPT_2DENCODING) != 0) imagecomp = Image.CCITTG3_2D; if ((tiffT4Options & TIFFConstants.GROUP3OPT_FILLBITS) != 0) params |= Image.CCITT_ENCODEDBYTEALIGN; } break; case TIFFConstants.COMPRESSION_CCITTFAX4: imagecomp = Image.CCITTG4; TIFFField t6OptionsField = dir.getField(TIFFConstants.TIFFTAG_GROUP4OPTIONS); if (t6OptionsField != null) tiffT6Options = t6OptionsField.getAsLong(0); break; } if (direct && rowsStrip == h) { //single strip, direct byte im[] = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(im); img = Image.getInstance(w, h, false, imagecomp, params, im); img.setInverted(true); } else { int rowsLeft = h; CCITTG4Encoder g4 = new CCITTG4Encoder(w); for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); TIFFFaxDecoder decoder = new TIFFFaxDecoder(fillOrder, w, height); byte outBuf[] = new byte[(w + 7) / 8 * height]; switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: decoder.decode1D(outBuf, im, 0, height); g4.fax4Encode(outBuf,height); break; case TIFFConstants.COMPRESSION_CCITTFAX3: try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e) { // let's flip the fill bits and try again... tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS; try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e2) { throw e; } } g4.fax4Encode(outBuf, height); break; case TIFFConstants.COMPRESSION_CCITTFAX4: decoder.decodeT6(outBuf, im, 0, height, tiffT6Options); g4.fax4Encode(outBuf, height); break; } rowsLeft -= rowsStrip; } byte g4pic[] = g4.close(); img = Image.getInstance(w, h, false, Image.CCITTG4, params & Image.CCITT_BLACKIS1, g4pic); } img.setDpi(dpiX, dpiY); img.setXYRatio(XYRatio); if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (icc_prof.getNumComponents() == 1) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } img.setOriginalType(Image.ORIGINAL_TIFF); if (rotation != 0) img.setInitialRotation(rotation); return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
protected static Image getTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s) { try { int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); int predictor = 1; TIFFLZWDecoder lzwDecoder = null; switch (compression) { case TIFFConstants.COMPRESSION_NONE: case TIFFConstants.COMPRESSION_LZW: case TIFFConstants.COMPRESSION_PACKBITS: case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: case TIFFConstants.COMPRESSION_OJPEG: case TIFFConstants.COMPRESSION_JPEG: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.compression.1.is.not.supported", compression)); } int photometric = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); switch (photometric) { case TIFFConstants.PHOTOMETRIC_MINISWHITE: case TIFFConstants.PHOTOMETRIC_MINISBLACK: case TIFFConstants.PHOTOMETRIC_RGB: case TIFFConstants.PHOTOMETRIC_SEPARATED: case TIFFConstants.PHOTOMETRIC_PALETTE: break; default: if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.photometric.1.is.not.supported", photometric)); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } if (dir.isTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) && dir.getFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("planar.images.are.not.supported")); int extraSamples = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES)) extraSamples = 1; int samplePerPixel = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4 samplePerPixel = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL); int bitsPerSample = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE)) bitsPerSample = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE); switch (bitsPerSample) { case 1: case 2: case 4: case 8: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample)); } Image img = null; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); int fillOrder = 1; boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE) { TIFFField predictorField = dir.getField(TIFFConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.getAsInt(0); if (predictor != 1 && predictor != 2) { throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.value.for.predictor.in.tiff.file")); } if (predictor == 2 && bitsPerSample != 8) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample)); } } } if (compression == TIFFConstants.COMPRESSION_LZW) { lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel); } int rowsLeft = h; ByteArrayOutputStream stream = null; ByteArrayOutputStream mstream = null; DeflaterOutputStream zip = null; DeflaterOutputStream mzip = null; if (extraSamples > 0) { mstream = new ByteArrayOutputStream(); mzip = new DeflaterOutputStream(mstream); } CCITTG4Encoder g4 = null; if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4 = new CCITTG4Encoder(w); } else { stream = new ByteArrayOutputStream(); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) zip = new DeflaterOutputStream(stream); } if (compression == TIFFConstants.COMPRESSION_OJPEG) { // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and // is often missing if ((!dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET))) { throw new IOException(MessageLocalization.getComposedMessage("missing.tag.s.for.ojpeg.compression")); } int jpegOffset = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET); int jpegLength = (int)s.length() - jpegOffset; if (dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT)) { jpegLength = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0]; } byte[] jpeg = new byte[Math.min(jpegLength, (int)s.length() - jpegOffset)]; int posFilePointer = (int)s.getFilePointer(); posFilePointer += jpegOffset; s.seek(posFilePointer); s.readFully(jpeg); img = new Jpeg(jpeg); } else if (compression == TIFFConstants.COMPRESSION_JPEG) { if (size.length > 1) throw new IOException(MessageLocalization.getComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.length)); byte[] jpeg = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(jpeg); // if quantization and/or Huffman tables are stored separately in the tiff, // we need to add them to the jpeg data TIFFField jpegtables = dir.getField(TIFFConstants.TIFFTAG_JPEGTABLES); if (jpegtables != null) { byte[] temp = jpegtables.getAsBytes(); int tableoffset = 0; int tablelength = temp.length; // remove FFD8 from start if (temp[0] == (byte) 0xFF && temp[1] == (byte) 0xD8) { tableoffset = 2; tablelength -= 2; } // remove FFD9 from end if (temp[temp.length-2] == (byte) 0xFF && temp[temp.length-1] == (byte) 0xD9) tablelength -= 2; byte[] tables = new byte[tablelength]; System.arraycopy(temp, tableoffset, tables, 0, tablelength); // TODO insert after JFIF header, instead of at the start byte[] jpegwithtables = new byte[jpeg.length + tables.length]; System.arraycopy(jpeg, 0, jpegwithtables, 0, 2); System.arraycopy(tables, 0, jpegwithtables, 2, tables.length); System.arraycopy(jpeg, 2, jpegwithtables, tables.length+2, jpeg.length-2); jpeg = jpegwithtables; } img = new Jpeg(jpeg); } else { for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); byte outBuf[] = null; if (compression != TIFFConstants.COMPRESSION_NONE) outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height]; if (reverse) TIFFFaxDecoder.reverseBits(im); switch (compression) { case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: inflate(im, outBuf); applyPredictor(outBuf, predictor, w, height, samplePerPixel); break; case TIFFConstants.COMPRESSION_NONE: outBuf = im; break; case TIFFConstants.COMPRESSION_PACKBITS: decodePackbits(im, outBuf); break; case TIFFConstants.COMPRESSION_LZW: lzwDecoder.decode(im, outBuf, height); break; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4.fax4Encode(outBuf, height); } else { if (extraSamples > 0) ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height); else zip.write(outBuf); } rowsLeft -= rowsStrip; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { img = Image.getInstance(w, h, false, Image.CCITTG4, photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.close()); } else { zip.close(); img = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.toByteArray()); img.setDeflated(true); } } img.setDpi(dpiX, dpiY); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) { if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (samplePerPixel - extraSamples == icc_prof.getNumComponents()) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } if (dir.isTagPresent(TIFFConstants.TIFFTAG_COLORMAP)) { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_COLORMAP); char rgb[] = fd.getAsChars(); byte palette[] = new byte[rgb.length]; int gColor = rgb.length / 3; int bColor = gColor * 2; for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)(rgb[k] >>> 8); palette[k * 3 + 1] = (byte)(rgb[k + gColor] >>> 8); palette[k * 3 + 2] = (byte)(rgb[k + bColor] >>> 8); } // Colormap components are supposed to go from 0 to 655535 but, // as usually, some tiff producers just put values from 0 to 255. // Let's check for these broken tiffs. boolean colormapBroken = true; for (int k = 0; k < palette.length; ++k) { if (palette[k] != 0) { colormapBroken = false; break; } } if (colormapBroken) { for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)rgb[k]; palette[k * 3 + 1] = (byte)rgb[k + gColor]; palette[k * 3 + 2] = (byte)rgb[k + bColor]; } } PdfArray indexed = new PdfArray(); indexed.add(PdfName.INDEXED); indexed.add(PdfName.DEVICERGB); indexed.add(new PdfNumber(gColor - 1)); indexed.add(new PdfString(palette)); PdfDictionary additional = new PdfDictionary(); additional.put(PdfName.COLORSPACE, indexed); img.setAdditional(additional); } img.setOriginalType(Image.ORIGINAL_TIFF); } if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE) img.setInverted(true); if (rotation != 0) img.setInitialRotation(rotation); if (extraSamples > 0) { mzip.close(); Image mimg = Image.getInstance(w, h, 1, bitsPerSample, mstream.toByteArray()); mimg.makeMask(); mimg.setDeflated(true); img.setImageMask(mimg); } return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
public static void inflate(byte[] deflated, byte[] inflated) { Inflater inflater = new Inflater(); inflater.setInput(deflated); try { inflater.inflate(inflated); } catch(DataFormatException dfe) { throw new ExceptionConverter(dfe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
private void init() { encoding = ""; fontSpecific = false; fontType = FONT_TYPE_DOCUMENT; PdfName baseFont = font.getAsName(PdfName.BASEFONT); fontName = baseFont != null ? PdfName.decodeName(baseFont.toString()) : "Unspecified Font Name"; PdfName subType = font.getAsName(PdfName.SUBTYPE); if (PdfName.TYPE1.equals(subType) || PdfName.TRUETYPE.equals(subType)) doType1TT(); else { PdfName encodingName = font.getAsName(PdfName.ENCODING); if (encodingName != null){ String enc = PdfName.decodeName(encodingName.toString()); String ffontname = CJKFont.GetCompatibleFont(enc); if (ffontname != null) { try { cjkMirror = BaseFont.createFont(ffontname, enc, false); } catch (Exception e) { throw new ExceptionConverter(e); } cjkEncoding = enc; uniMap = ((CJKFont)cjkMirror).getUniMap(); return; } if (PdfName.TYPE0.equals(subType) && enc.equals("Identity-H")) { processType0(font); isType0 = true; } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
private void processType0(PdfDictionary font) { try { PdfObject toUniObject = PdfReader.getPdfObjectRelease(font.get(PdfName.TOUNICODE)); PdfArray df = (PdfArray)PdfReader.getPdfObjectRelease(font.get(PdfName.DESCENDANTFONTS)); PdfDictionary cidft = (PdfDictionary)PdfReader.getPdfObjectRelease(df.getPdfObject(0)); PdfNumber dwo = (PdfNumber)PdfReader.getPdfObjectRelease(cidft.get(PdfName.DW)); int dw = 1000; if (dwo != null) dw = dwo.intValue(); IntHashtable widths = readWidths((PdfArray)PdfReader.getPdfObjectRelease(cidft.get(PdfName.W))); PdfDictionary fontDesc = (PdfDictionary)PdfReader.getPdfObjectRelease(cidft.get(PdfName.FONTDESCRIPTOR)); fillFontDesc(fontDesc); if (toUniObject instanceof PRStream){ fillMetrics(PdfReader.getStreamBytes((PRStream)toUniObject), widths, dw); } } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
private void fillMetrics(byte[] touni, IntHashtable widths, int dw) { try { PdfContentParser ps = new PdfContentParser(new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(touni)))); PdfObject ob = null; boolean notFound = true; int nestLevel = 0; int maxExc = 50; while ((notFound || nestLevel > 0)) { try { ob = ps.readPRObject(); } catch (Exception ex) { if (--maxExc < 0) break; continue; } if (ob == null) break; if (ob.type() == PdfContentParser.COMMAND_TYPE) { if (ob.toString().equals("begin")) { notFound = false; nestLevel++; } else if (ob.toString().equals("end")) { nestLevel--; } else if (ob.toString().equals("beginbfchar")) { while (true) { PdfObject nx = ps.readPRObject(); if (nx.toString().equals("endbfchar")) break; String cid = decodeString((PdfString)nx); String uni = decodeString((PdfString)ps.readPRObject()); if (uni.length() == 1) { int cidc = cid.charAt(0); int unic = uni.charAt(uni.length() - 1); int w = dw; if (widths.containsKey(cidc)) w = widths.get(cidc); metrics.put(Integer.valueOf(unic), new int[]{cidc, w}); } } } else if (ob.toString().equals("beginbfrange")) { while (true) { PdfObject nx = ps.readPRObject(); if (nx.toString().equals("endbfrange")) break; String cid1 = decodeString((PdfString)nx); String cid2 = decodeString((PdfString)ps.readPRObject()); int cid1c = cid1.charAt(0); int cid2c = cid2.charAt(0); PdfObject ob2 = ps.readPRObject(); if (ob2.isString()) { String uni = decodeString((PdfString)ob2); if (uni.length() == 1) { int unic = uni.charAt(uni.length() - 1); for (; cid1c <= cid2c; cid1c++, unic++) { int w = dw; if (widths.containsKey(cid1c)) w = widths.get(cid1c); metrics.put(Integer.valueOf(unic), new int[]{cid1c, w}); } } } else { PdfArray a = (PdfArray)ob2; for (int j = 0; j < a.size(); ++j, ++cid1c) { String uni = decodeString(a.getAsString(j)); if (uni.length() == 1) { int unic = uni.charAt(uni.length() - 1); int w = dw; if (widths.containsKey(cid1c)) w = widths.get(cid1c); metrics.put(Integer.valueOf(unic), new int[]{cid1c, w}); } } } } } } } } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
private void doType1TT() { CMapToUnicode toUnicode = null; PdfObject enc = PdfReader.getPdfObject(font.get(PdfName.ENCODING)); if (enc == null) { fillEncoding(null); try { toUnicode = processToUnicode(); if (toUnicode != null) { Map<Integer, Integer> rm = toUnicode.createReverseMapping(); for (Map.Entry<Integer, Integer> kv : rm.entrySet()) { uni2byte.put(kv.getKey().intValue(), kv.getValue().intValue()); byte2uni.put(kv.getValue().intValue(), kv.getKey().intValue()); } } } catch (Exception ex) { throw new ExceptionConverter(ex); } } else { if (enc.isName()) fillEncoding((PdfName)enc); else if (enc.isDictionary()) { PdfDictionary encDic = (PdfDictionary)enc; enc = PdfReader.getPdfObject(encDic.get(PdfName.BASEENCODING)); if (enc == null) fillEncoding(null); else fillEncoding((PdfName)enc); PdfArray diffs = encDic.getAsArray(PdfName.DIFFERENCES); if (diffs != null) { diffmap = new IntHashtable(); int currentNumber = 0; for (int k = 0; k < diffs.size(); ++k) { PdfObject obj = diffs.getPdfObject(k); if (obj.isNumber()) currentNumber = ((PdfNumber)obj).intValue(); else { int c[] = GlyphList.nameToUnicode(PdfName.decodeName(((PdfName)obj).toString())); if (c != null && c.length > 0) { uni2byte.put(c[0], currentNumber); byte2uni.put(currentNumber, c[0]); diffmap.put(c[0], currentNumber); } else { if (toUnicode == null) { toUnicode = processToUnicode(); if (toUnicode == null) { toUnicode = new CMapToUnicode(); } } final String unicode = toUnicode.lookup(new byte[]{(byte) currentNumber}, 0, 1); if ((unicode != null) && (unicode.length() == 1)) { this.uni2byte.put(unicode.charAt(0), currentNumber); this.byte2uni.put(currentNumber, unicode.charAt(0)); this.diffmap.put(unicode.charAt(0), currentNumber); } } ++currentNumber; } } } } } PdfArray newWidths = font.getAsArray(PdfName.WIDTHS); PdfNumber first = font.getAsNumber(PdfName.FIRSTCHAR); PdfNumber last = font.getAsNumber(PdfName.LASTCHAR); if (BuiltinFonts14.containsKey(fontName)) { BaseFont bf; try { bf = BaseFont.createFont(fontName, WINANSI, false); } catch (Exception e) { throw new ExceptionConverter(e); } int e[] = uni2byte.toOrderedKeys(); for (int k = 0; k < e.length; ++k) { updateWidths(e[k], bf); } if (diffmap != null) { //widths for diffmap must override existing ones e = diffmap.toOrderedKeys(); for (int k = 0; k < e.length; ++k) { updateWidths(e[k], bf); } diffmap = null; } ascender = bf.getFontDescriptor(ASCENT, 1000); capHeight = bf.getFontDescriptor(CAPHEIGHT, 1000); descender = bf.getFontDescriptor(DESCENT, 1000); italicAngle = bf.getFontDescriptor(ITALICANGLE, 1000); fontWeight = bf.getFontDescriptor(FONT_WEIGHT, 1000); llx = bf.getFontDescriptor(BBOXLLX, 1000); lly = bf.getFontDescriptor(BBOXLLY, 1000); urx = bf.getFontDescriptor(BBOXURX, 1000); ury = bf.getFontDescriptor(BBOXURY, 1000); } if (first != null && last != null && newWidths != null) { int f = first.intValue(); int nSize = f + newWidths.size(); if (widths.length < nSize) { int[] tmp = new int[nSize]; System.arraycopy(widths, 0, tmp, 0, f); widths = tmp; } for (int k = 0; k < newWidths.size(); ++k) { widths[f + k] = newWidths.getAsNumber(k).intValue(); } } fillFontDesc(font.getAsDict(PdfName.FONTDESCRIPTOR)); }
// 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/hyphenation/SimplePatternParser.java
public void parse(InputStream stream, PatternConsumer consumer) { this.consumer = consumer; try { SimpleXMLParser.parse(this, stream); } catch (IOException e) { throw new ExceptionConverter(e); } finally { try { stream.close(); } catch (Exception e) { } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public static void showTextAligned(final PdfContentByte canvas, int alignment, final Phrase phrase, final float x, final float y, final float rotation, final int runDirection, final int arabicOptions) { if (alignment != Element.ALIGN_LEFT && alignment != Element.ALIGN_CENTER && alignment != Element.ALIGN_RIGHT) alignment = Element.ALIGN_LEFT; canvas.saveState(); ColumnText ct = new ColumnText(canvas); float lly = -1; float ury = 2; float llx; float urx; switch (alignment) { case Element.ALIGN_LEFT: llx = 0; urx = 20000; break; case Element.ALIGN_RIGHT: llx = -20000; urx = 0; break; default: llx = -20000; urx = 20000; break; } if (rotation == 0) { llx += x; lly += y; urx += x; ury += y; } else { double alpha = rotation * Math.PI / 180.0; float cos = (float)Math.cos(alpha); float sin = (float)Math.sin(alpha); canvas.concatCTM(cos, sin, -sin, cos, x, y); } ct.setSimpleColumn(phrase, llx, lly, urx, ury, 2, alignment); if (runDirection == PdfWriter.RUN_DIRECTION_RTL) { if (alignment == Element.ALIGN_LEFT) alignment = Element.ALIGN_RIGHT; else if (alignment == Element.ALIGN_RIGHT) alignment = Element.ALIGN_LEFT; } ct.setAlignment(alignment); ct.setArabicOptions(arabicOptions); ct.setRunDirection(runDirection); try { ct.go(); } catch (DocumentException e) { throw new ExceptionConverter(e); } canvas.restoreState(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public static float fitText(Font font, String text, Rectangle rect, float maxFontSize, int runDirection) { try { ColumnText ct = null; int status = 0; if (maxFontSize <= 0) { int cr = 0; int lf = 0; char t[] = text.toCharArray(); for (int k = 0; k < t.length; ++k) { if (t[k] == '\n') ++lf; else if (t[k] == '\r') ++cr; } int minLines = Math.max(cr, lf) + 1; maxFontSize = Math.abs(rect.getHeight()) / minLines - 0.001f; } font.setSize(maxFontSize); Phrase ph = new Phrase(text, font); ct = new ColumnText(null); ct.setSimpleColumn(ph, rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop(), maxFontSize, Element.ALIGN_LEFT); ct.setRunDirection(runDirection); status = ct.go(true); if ((status & NO_MORE_TEXT) != 0) return maxFontSize; float precision = 0.1f; float min = 0; float max = maxFontSize; float size = maxFontSize; for (int k = 0; k < 50; ++k) { //just in case it doesn't converge size = (min + max) / 2; ct = new ColumnText(null); font.setSize(size); ct.setSimpleColumn(new Phrase(text, font), rect.getLeft(), rect.getBottom(), rect.getRight(), rect.getTop(), size, Element.ALIGN_LEFT); ct.setRunDirection(runDirection); status = ct.go(true); if ((status & NO_MORE_TEXT) != 0) { if (max - min < size * precision) return size; min = size; } else max = size; } return size; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public static Object[] splitDAelements(String da) { try { PRTokeniser tk = new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(PdfEncodings.convertToBytes(da, null)))); ArrayList<String> stack = new ArrayList<String>(); Object ret[] = new Object[3]; while (tk.nextToken()) { if (tk.getTokenType() == TokenType.COMMENT) continue; if (tk.getTokenType() == TokenType.OTHER) { String operator = tk.getStringValue(); if (operator.equals("Tf")) { if (stack.size() >= 2) { ret[DA_FONT] = stack.get(stack.size() - 2); ret[DA_SIZE] = new Float(stack.get(stack.size() - 1)); } } else if (operator.equals("g")) { if (stack.size() >= 1) { float gray = new Float(stack.get(stack.size() - 1)).floatValue(); if (gray != 0) ret[DA_COLOR] = new GrayColor(gray); } } else if (operator.equals("rg")) { if (stack.size() >= 3) { float red = new Float(stack.get(stack.size() - 3)).floatValue(); float green = new Float(stack.get(stack.size() - 2)).floatValue(); float blue = new Float(stack.get(stack.size() - 1)).floatValue(); ret[DA_COLOR] = new BaseColor(red, green, blue); } } else if (operator.equals("k")) { if (stack.size() >= 4) { float cyan = new Float(stack.get(stack.size() - 4)).floatValue(); float magenta = new Float(stack.get(stack.size() - 3)).floatValue(); float yellow = new Float(stack.get(stack.size() - 2)).floatValue(); float black = new Float(stack.get(stack.size() - 1)).floatValue(); ret[DA_COLOR] = new CMYKColor(cyan, magenta, yellow, black); } } stack.clear(); } else stack.add(tk.getStringValue()); } return ret; } catch (IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public String getField(String name) { if (xfa.isXfaPresent()) { name = xfa.findFieldName(name, this); if (name == null) return null; name = XfaForm.Xml2Som.getShortName(name); return XfaForm.getNodeText(xfa.findDatasetsNode(name)); } Item item = fields.get(name); if (item == null) return null; lastWasString = false; PdfDictionary mergedDict = item.getMerged( 0 ); // Jose A. Rodriguez posted a fix to the mailing list (May 11, 2009) // explaining that the value can also be a stream value // the fix was made against an old iText version. Bruno adapted it. PdfObject v = PdfReader.getPdfObject(mergedDict.get(PdfName.V)); if (v == null) return ""; if (v instanceof PRStream) { byte[] valBytes; try { valBytes = PdfReader.getStreamBytes((PRStream)v); return new String(valBytes); } catch (IOException e) { throw new ExceptionConverter(e); } } PdfName type = mergedDict.getAsName(PdfName.FT); if (PdfName.BTN.equals(type)) { PdfNumber ff = mergedDict.getAsNumber(PdfName.FF); int flags = 0; if (ff != null) flags = ff.intValue(); if ((flags & PdfFormField.FF_PUSHBUTTON) != 0) return ""; String value = ""; if (v instanceof PdfName) value = PdfName.decodeName(v.toString()); else if (v instanceof PdfString) value = ((PdfString)v).toUnicodeString(); PdfArray opts = item.getValue(0).getAsArray(PdfName.OPT); if (opts != null) { int idx = 0; try { idx = Integer.parseInt(value); PdfString ps = opts.getAsString(idx); value = ps.toUnicodeString(); lastWasString = true; } catch (Exception e) { } } return value; } if (v instanceof PdfString) { lastWasString = true; return ((PdfString)v).toUnicodeString(); } else if (v instanceof PdfName) { return PdfName.decodeName(v.toString()); } else return ""; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setFieldProperty(String field, String name, Object value, int inst[]) { if (writer == null) throw new RuntimeException(MessageLocalization.getComposedMessage("this.acrofields.instance.is.read.only")); try { Item item = fields.get(field); if (item == null) return false; InstHit hit = new InstHit(inst); PdfDictionary merged; PdfString da; if (name.equalsIgnoreCase("textfont")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); PdfDictionary dr = merged.getAsDict(PdfName.DR); if (da != null) { if (dr == null) { dr = new PdfDictionary(); merged.put(PdfName.DR, dr); } Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { BaseFont bf = (BaseFont)value; PdfName psn = PdfAppearance.stdFieldFontNames.get(bf.getPostscriptFontName()); if (psn == null) { psn = new PdfName(bf.getPostscriptFontName()); } PdfDictionary fonts = dr.getAsDict(PdfName.FONT); if (fonts == null) { fonts = new PdfDictionary(); dr.put(PdfName.FONT, fonts); } PdfIndirectReference fref = (PdfIndirectReference)fonts.get(psn); PdfDictionary top = reader.getCatalog().getAsDict(PdfName.ACROFORM); markUsed(top); dr = top.getAsDict(PdfName.DR); if (dr == null) { dr = new PdfDictionary(); top.put(PdfName.DR, dr); } markUsed(dr); PdfDictionary fontsTop = dr.getAsDict(PdfName.FONT); if (fontsTop == null) { fontsTop = new PdfDictionary(); dr.put(PdfName.FONT, fontsTop); } markUsed(fontsTop); PdfIndirectReference frefTop = (PdfIndirectReference)fontsTop.get(psn); if (frefTop != null) { if (fref == null) fonts.put(psn, frefTop); } else if (fref == null) { FontDetails fd; if (bf.getFontType() == BaseFont.FONT_TYPE_DOCUMENT) { fd = new FontDetails(null, ((DocumentFont)bf).getIndirectReference(), bf); } else { bf.setSubset(false); fd = writer.addSimple(bf); localFonts.put(psn.toString().substring(1), bf); } fontsTop.put(psn, fd.getIndirectReference()); fonts.put(psn, fd.getIndirectReference()); } ByteBuffer buf = cb.getInternalBuffer(); buf.append(psn.getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf "); if (dao[DA_COLOR] != null) cb.setColorFill((BaseColor)dao[DA_COLOR]); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("textcolor")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); if (da != null) { Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { ByteBuffer buf = cb.getInternalBuffer(); buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf "); cb.setColorFill((BaseColor)value); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("textsize")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); if (da != null) { Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { ByteBuffer buf = cb.getInternalBuffer(); buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)value).floatValue()).append(" Tf "); if (dao[DA_COLOR] != null) cb.setColorFill((BaseColor)dao[DA_COLOR]); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("bgcolor") || name.equalsIgnoreCase("bordercolor")) { PdfName dname = name.equalsIgnoreCase("bgcolor") ? PdfName.BG : PdfName.BC; for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); PdfDictionary mk = merged.getAsDict(PdfName.MK); if (mk == null) { if (value == null) return true; mk = new PdfDictionary(); item.getMerged(k).put(PdfName.MK, mk); item.getWidget(k).put(PdfName.MK, mk); markUsed(item.getWidget(k)); } else { markUsed( mk ); } if (value == null) mk.remove(dname); else mk.put(dname, PdfFormField.getMKColor((BaseColor)value)); } } } else return false; return true; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public PdfPKCS7 verifySignature(String name, String provider) { PdfDictionary v = getSignatureDictionary(name); if (v == null) return null; try { PdfName sub = v.getAsName(PdfName.SUBFILTER); PdfString contents = v.getAsString(PdfName.CONTENTS); PdfPKCS7 pk = null; if (sub.equals(PdfName.ADBE_X509_RSA_SHA1)) { PdfString cert = v.getAsString(PdfName.CERT); if (cert == null) cert = v.getAsArray(PdfName.CERT).getAsString(0); pk = new PdfPKCS7(contents.getOriginalBytes(), cert.getBytes(), provider); } else pk = new PdfPKCS7(contents.getOriginalBytes(), sub, provider); updateByteRange(pk, v); PdfString str = v.getAsString(PdfName.M); if (str != null) pk.setSignDate(PdfDate.decode(str.toString())); PdfObject obj = PdfReader.getPdfObject(v.get(PdfName.NAME)); if (obj != null) { if (obj.isString()) pk.setSignName(((PdfString)obj).toUnicodeString()); else if(obj.isName()) pk.setSignName(PdfName.decodeName(obj.toString())); } str = v.getAsString(PdfName.REASON); if (str != null) pk.setReason(str.toUnicodeString()); str = v.getAsString(PdfName.LOCATION); if (str != null) pk.setLocation(str.toUnicodeString()); return pk; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
private void updateByteRange(PdfPKCS7 pkcs7, PdfDictionary v) { PdfArray b = v.getAsArray(PdfName.BYTERANGE); RandomAccessFileOrArray rf = reader.getSafeFile(); InputStream rg = null; try { rg = new RASInputStream(new RandomAccessSourceFactory().createRanged(rf.createSourceView(), b.asLongArray())); byte buf[] = new byte[8192]; int rd; while ((rd = rg.read(buf, 0, buf.length)) > 0) { pkcs7.update(buf, 0, rd); } } catch (Exception e) { throw new ExceptionConverter(e); } finally { try { if (rg != null) rg.close(); } catch (IOException e) { // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway throw new ExceptionConverter(e); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public void removeXfa() { PdfDictionary root = reader.getCatalog(); PdfDictionary acroform = root.getAsDict(PdfName.ACROFORM); acroform.remove(PdfName.XFA); try { xfa = new XfaForm(reader); } catch(Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public PushbuttonField getNewPushbuttonFromField(String field, int order) { try { if (getFieldType(field) != FIELD_TYPE_PUSHBUTTON) return null; Item item = getFieldItem(field); if (order >= item.size()) return null; List<FieldPosition> pos = getFieldPositions(field); Rectangle box = pos.get(order).position; PushbuttonField newButton = new PushbuttonField(writer, box, null); PdfDictionary dic = item.getMerged(order); decodeGenericDictionary(dic, newButton); PdfDictionary mk = dic.getAsDict(PdfName.MK); if (mk != null) { PdfString text = mk.getAsString(PdfName.CA); if (text != null) newButton.setText(text.toUnicodeString()); PdfNumber tp = mk.getAsNumber(PdfName.TP); if (tp != null) newButton.setLayout(tp.intValue() + 1); PdfDictionary ifit = mk.getAsDict(PdfName.IF); if (ifit != null) { PdfName sw = ifit.getAsName(PdfName.SW); if (sw != null) { int scale = PushbuttonField.SCALE_ICON_ALWAYS; if (sw.equals(PdfName.B)) scale = PushbuttonField.SCALE_ICON_IS_TOO_BIG; else if (sw.equals(PdfName.S)) scale = PushbuttonField.SCALE_ICON_IS_TOO_SMALL; else if (sw.equals(PdfName.N)) scale = PushbuttonField.SCALE_ICON_NEVER; newButton.setScaleIcon(scale); } sw = ifit.getAsName(PdfName.S); if (sw != null) { if (sw.equals(PdfName.A)) newButton.setProportionalIcon(false); } PdfArray aj = ifit.getAsArray(PdfName.A); if (aj != null && aj.size() == 2) { float left = aj.getAsNumber(0).floatValue(); float bottom = aj.getAsNumber(1).floatValue(); newButton.setIconHorizontalAdjustment(left); newButton.setIconVerticalAdjustment(bottom); } PdfBoolean fb = ifit.getAsBoolean(PdfName.FB); if (fb != null && fb.booleanValue()) newButton.setIconFitToBounds(true); } PdfObject i = mk.get(PdfName.I); if (i != null && i.isIndirect()) newButton.setIconReference((PRIndirectReference)i); } return newButton; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
public void writeCells(int colStart, int colEnd, float xPos, float yPos, PdfContentByte[] canvases, boolean reusable) { if (!calculated) calculateHeights(); if (colEnd < 0) colEnd = cells.length; else colEnd = Math.min(colEnd, cells.length); if (colStart < 0) colStart = 0; if (colStart >= colEnd) return; int newStart; for (newStart = colStart; newStart >= 0; --newStart) { if (cells[newStart] != null) break; if (newStart > 0) xPos -= widths[newStart - 1]; } if (newStart < 0) newStart = 0; if (cells[newStart] != null) xPos -= cells[newStart].getLeft(); if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].openMCBlock(this); } for (int k = newStart; k < colEnd; ++k) { PdfPCell cell = cells[k]; if (cell == null) continue; if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].openMCBlock(cell); } float currentMaxHeight = maxHeight + extraHeights[k]; writeBorderAndBackground(xPos, yPos, currentMaxHeight, cell, canvases); Image img = cell.getImage(); float tly = cell.getTop() + yPos - cell.getEffectivePaddingTop(); if (cell.getHeight() <= currentMaxHeight) { switch (cell.getVerticalAlignment()) { case Element.ALIGN_BOTTOM: tly = cell.getTop() + yPos - currentMaxHeight + cell.getHeight() - cell.getEffectivePaddingTop(); break; case Element.ALIGN_MIDDLE: tly = cell.getTop() + yPos + (cell.getHeight() - currentMaxHeight) / 2 - cell.getEffectivePaddingTop(); break; default: break; } } if (img != null) { if (cell.getRotation() != 0) { img = Image.getInstance(img); img.setRotation(img.getImageRotation() + (float)(cell.getRotation() * Math.PI / 180.0)); } boolean vf = false; if (cell.getHeight() > currentMaxHeight) { if (!img.isScaleToFitLineWhenOverflow()) { continue; } img.scalePercent(100); float scale = (currentMaxHeight - cell.getEffectivePaddingTop() - cell .getEffectivePaddingBottom()) / img.getScaledHeight(); img.scalePercent(scale * 100); vf = true; } float left = cell.getLeft() + xPos + cell.getEffectivePaddingLeft(); if (vf) { switch (cell.getHorizontalAlignment()) { case Element.ALIGN_CENTER: left = xPos + (cell.getLeft() + cell.getEffectivePaddingLeft() + cell.getRight() - cell.getEffectivePaddingRight() - img .getScaledWidth()) / 2; break; case Element.ALIGN_RIGHT: left = xPos + cell.getRight() - cell.getEffectivePaddingRight() - img.getScaledWidth(); break; default: break; } tly = cell.getTop() + yPos - cell.getEffectivePaddingTop(); } img.setAbsolutePosition(left, tly - img.getScaledHeight()); try { if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].openMCBlock(img); } canvases[PdfPTable.TEXTCANVAS].addImage(img); if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].closeMCBlock(img); } } catch (DocumentException e) { throw new ExceptionConverter(e); } } else { // rotation sponsored by Connection GmbH if (cell.getRotation() == 90 || cell.getRotation() == 270) { float netWidth = currentMaxHeight - cell.getEffectivePaddingTop() - cell.getEffectivePaddingBottom(); float netHeight = cell.getWidth() - cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight(); ColumnText ct = ColumnText.duplicate(cell.getColumn()); ct.setCanvases(canvases); ct.setSimpleColumn(0, 0, netWidth + 0.001f, -netHeight); try { ct.go(true); } catch (DocumentException e) { throw new ExceptionConverter(e); } float calcHeight = -ct.getYLine(); if (netWidth <= 0 || netHeight <= 0) calcHeight = 0; if (calcHeight > 0) { if (cell.isUseDescender()) calcHeight -= ct.getDescender(); if (reusable) ct = ColumnText.duplicate(cell.getColumn()); else ct = cell.getColumn(); ct.setCanvases(canvases); ct.setSimpleColumn(-0.003f, -0.001f, netWidth + 0.003f, calcHeight); float pivotX; float pivotY; if (cell.getRotation() == 90) { pivotY = cell.getTop() + yPos - currentMaxHeight + cell.getEffectivePaddingBottom(); switch (cell.getVerticalAlignment()) { case Element.ALIGN_BOTTOM: pivotX = cell.getLeft() + xPos + cell.getWidth() - cell.getEffectivePaddingRight(); break; case Element.ALIGN_MIDDLE: pivotX = cell.getLeft() + xPos + (cell.getWidth() + cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight() + calcHeight) / 2; break; default: //top pivotX = cell.getLeft() + xPos + cell.getEffectivePaddingLeft() + calcHeight; break; } saveAndRotateCanvases(canvases, 0,1,-1,0,pivotX,pivotY); } else { pivotY = cell.getTop() + yPos - cell.getEffectivePaddingTop(); switch (cell.getVerticalAlignment()) { case Element.ALIGN_BOTTOM: pivotX = cell.getLeft() + xPos + cell.getEffectivePaddingLeft(); break; case Element.ALIGN_MIDDLE: pivotX = cell.getLeft() + xPos + (cell.getWidth() + cell.getEffectivePaddingLeft() - cell.getEffectivePaddingRight() - calcHeight) / 2; break; default: //top pivotX = cell.getLeft() + xPos + cell.getWidth() - cell.getEffectivePaddingRight() - calcHeight; break; } saveAndRotateCanvases(canvases, 0,-1,1,0,pivotX,pivotY); } try { ct.go(); } catch (DocumentException e) { throw new ExceptionConverter(e); } finally { restoreCanvases(canvases); } } } else { float fixedHeight = cell.getFixedHeight(); float rightLimit = cell.getRight() + xPos - cell.getEffectivePaddingRight(); float leftLimit = cell.getLeft() + xPos + cell.getEffectivePaddingLeft(); if (cell.isNoWrap()) { switch (cell.getHorizontalAlignment()) { case Element.ALIGN_CENTER: rightLimit += 10000; leftLimit -= 10000; break; case Element.ALIGN_RIGHT: if (cell.getRotation() == 180) { rightLimit += RIGHT_LIMIT; } else { leftLimit -= RIGHT_LIMIT; } break; default: if (cell.getRotation() == 180) { leftLimit -= RIGHT_LIMIT; } else { rightLimit += RIGHT_LIMIT; } break; } } ColumnText ct; if (reusable) ct = ColumnText.duplicate(cell.getColumn()); else ct = cell.getColumn(); ct.setCanvases(canvases); float bry = tly - (currentMaxHeight - cell.getEffectivePaddingTop() - cell.getEffectivePaddingBottom()); if (fixedHeight > 0) { if (cell.getHeight() > currentMaxHeight) { tly = cell.getTop() + yPos - cell.getEffectivePaddingTop(); bry = cell.getTop() + yPos - currentMaxHeight + cell.getEffectivePaddingBottom(); } } if ((tly > bry || ct.zeroHeightElement()) && leftLimit < rightLimit) { ct.setSimpleColumn(leftLimit, bry - 0.001f, rightLimit, tly); if (cell.getRotation() == 180) { float shx = leftLimit + rightLimit; float shy = yPos + yPos - currentMaxHeight + cell.getEffectivePaddingBottom() - cell.getEffectivePaddingTop(); saveAndRotateCanvases(canvases, -1,0,0,-1,shx,shy); } try { ct.go(); } catch (DocumentException e) { throw new ExceptionConverter(e); } finally { if (cell.getRotation() == 180) { restoreCanvases(canvases); } } } } } PdfPCellEvent evt = cell.getCellEvent(); if (evt != null) { Rectangle rect = new Rectangle(cell.getLeft() + xPos, cell.getTop() + yPos - currentMaxHeight, cell.getRight() + xPos, cell.getTop() + yPos); evt.cellLayout(cell, rect, canvases); } if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].closeMCBlock(cell); } } if (isTagged(canvases[PdfPTable.TEXTCANVAS])) { canvases[PdfPTable.TEXTCANVAS].closeMCBlock(this); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
public PdfPRow splitRow(PdfPTable table, int rowIndex, float new_height) { LOGGER.info("Splitting " + rowIndex + " " + new_height); // second part of the row PdfPCell newCells[] = new PdfPCell[cells.length]; float fixHs[] = new float[cells.length]; float minHs[] = new float[cells.length]; boolean allEmpty = true; // loop over all the cells for (int k = 0; k < cells.length; ++k) { float newHeight = new_height; PdfPCell cell = cells[k]; if (cell == null) { int index = rowIndex; if (table.rowSpanAbove(index, k)) { while (table.rowSpanAbove(--index, k)) { newHeight += table.getRow(index).getMaxHeights(); } PdfPRow row = table.getRow(index); if (row != null && row.getCells()[k] != null) { newCells[k] = new PdfPCell(row.getCells()[k]); newCells[k].setColumn(null); newCells[k].setRowspan(row.getCells()[k].getRowspan() - rowIndex + index); allEmpty = false; } } continue; } fixHs[k] = cell.getFixedHeight(); minHs[k] = cell.getMinimumHeight(); Image img = cell.getImage(); PdfPCell newCell = new PdfPCell(cell); if (img != null) { float padding = cell.getEffectivePaddingBottom() + cell.getEffectivePaddingTop() + 2; if ((img.isScaleToFitLineWhenOverflow() || img.getScaledHeight() + padding < newHeight) && newHeight > padding) { newCell.setPhrase(null); allEmpty = false; } } else { float y; ColumnText ct = ColumnText.duplicate(cell.getColumn()); float left = cell.getLeft() + cell.getEffectivePaddingLeft(); float bottom = cell.getTop() + cell.getEffectivePaddingBottom() - newHeight; float right = cell.getRight() - cell.getEffectivePaddingRight(); float top = cell.getTop() - cell.getEffectivePaddingTop(); switch (cell.getRotation()) { case 90: case 270: y = setColumn(ct, bottom, left, top, right); break; default: y = setColumn(ct, left, bottom + 0.00001f, cell.isNoWrap() ? RIGHT_LIMIT : right, top); break; } int status; try { status = ct.go(true); } catch (DocumentException e) { throw new ExceptionConverter(e); } boolean thisEmpty = (ct.getYLine() == y); if (thisEmpty) { newCell.setColumn(ColumnText.duplicate(cell.getColumn())); ct.setFilledWidth(0); } else if ((status & ColumnText.NO_MORE_TEXT) == 0) { newCell.setColumn(ct); ct.setFilledWidth(0); } else newCell.setPhrase(null); allEmpty = (allEmpty && thisEmpty); } newCells[k] = newCell; cell.setFixedHeight(newHeight); } if (allEmpty) { for (int k = 0; k < cells.length; ++k) { PdfPCell cell = cells[k]; if (cell == null) continue; if (fixHs[k] > 0) cell.setFixedHeight(fixHs[k]); else cell.setMinimumHeight(minHs[k]); } return null; } calculateHeights(); PdfPRow split = new PdfPRow(newCells, this); split.widths = (float[]) widths.clone(); return split; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAcroForm.java
public void drawCheckBoxAppearences(PdfFormField field, String value, float llx, float lly, float urx, float ury) { BaseFont font = null; try { font = BaseFont.createFont(BaseFont.ZAPFDINGBATS, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); } catch(Exception e) { throw new ExceptionConverter(e); } float size = ury - lly; PdfAppearance tpOn = PdfAppearance.createAppearance(writer, urx - llx, ury - lly); PdfAppearance tp2 = (PdfAppearance)tpOn.getDuplicate(); tp2.setFontAndSize(font, size); tp2.resetRGBColorFill(); field.setDefaultAppearanceString(tp2); tpOn.drawTextField(0f, 0f, urx - llx, ury - lly); tpOn.saveState(); tpOn.resetRGBColorFill(); tpOn.beginText(); tpOn.setFontAndSize(font, size); tpOn.showTextAligned(PdfContentByte.ALIGN_CENTER, "4", (urx - llx) / 2, (ury - lly) / 2 - size * 0.3f, 0); tpOn.endText(); tpOn.restoreState(); field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, value, tpOn); PdfAppearance tpOff = PdfAppearance.createAppearance(writer, urx - llx, ury - lly); tpOff.drawTextField(0f, 0f, urx - llx, ury - lly); field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, "Off", tpOff); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
public static final byte[] convertToBytes(String text, String encoding) { if (text == null) return new byte[0]; if (encoding == null || encoding.length() == 0) { int len = text.length(); byte b[] = new byte[len]; for (int k = 0; k < len; ++k) b[k] = (byte)text.charAt(k); return b; } ExtraEncoding extra = extraEncodings.get(encoding.toLowerCase()); if (extra != null) { byte b[] = extra.charToByte(text, encoding); if (b != null) return b; } IntHashtable hash = null; if (encoding.equals(BaseFont.WINANSI)) hash = winansi; else if (encoding.equals(PdfObject.TEXT_PDFDOCENCODING)) hash = pdfEncoding; if (hash != null) { char cc[] = text.toCharArray(); int len = cc.length; int ptr = 0; byte b[] = new byte[len]; int c = 0; for (int k = 0; k < len; ++k) { char char1 = cc[k]; if (char1 < 128 || char1 > 160 && char1 <= 255) c = char1; else c = hash.get(char1); if (c != 0) b[ptr++] = (byte)c; } if (ptr == len) return b; byte b2[] = new byte[ptr]; System.arraycopy(b, 0, b2, 0, ptr); return b2; } if (encoding.equals(PdfObject.TEXT_UNICODE)) { // workaround for jdk 1.2.2 bug char cc[] = text.toCharArray(); int len = cc.length; byte b[] = new byte[cc.length * 2 + 2]; b[0] = -2; b[1] = -1; int bptr = 2; for (int k = 0; k < len; ++k) { char c = cc[k]; b[bptr++] = (byte)(c >> 8); b[bptr++] = (byte)(c & 0xff); } return b; } try { Charset cc = Charset.forName(encoding); CharsetEncoder ce = cc.newEncoder(); ce.onUnmappableCharacter(CodingErrorAction.IGNORE); CharBuffer cb = CharBuffer.wrap(text.toCharArray()); java.nio.ByteBuffer bb = ce.encode(cb); bb.rewind(); int lim = bb.limit(); byte[] br = new byte[lim]; bb.get(br); return br; } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
public static final byte[] convertToBytes(char char1, String encoding) { if (encoding == null || encoding.length() == 0) return new byte[]{(byte)char1}; ExtraEncoding extra = extraEncodings.get(encoding.toLowerCase()); if (extra != null) { byte b[] = extra.charToByte(char1, encoding); if (b != null) return b; } IntHashtable hash = null; if (encoding.equals(BaseFont.WINANSI)) hash = winansi; else if (encoding.equals(PdfObject.TEXT_PDFDOCENCODING)) hash = pdfEncoding; if (hash != null) { int c = 0; if (char1 < 128 || char1 > 160 && char1 <= 255) c = char1; else c = hash.get(char1); if (c != 0) return new byte[]{(byte)c}; else return new byte[0]; } if (encoding.equals(PdfObject.TEXT_UNICODE)) { // workaround for jdk 1.2.2 bug byte b[] = new byte[4]; b[0] = -2; b[1] = -1; b[2] = (byte)(char1 >> 8); b[3] = (byte)(char1 & 0xff); return b; } try { Charset cc = Charset.forName(encoding); CharsetEncoder ce = cc.newEncoder(); ce.onUnmappableCharacter(CodingErrorAction.IGNORE); CharBuffer cb = CharBuffer.wrap(new char[]{char1}); java.nio.ByteBuffer bb = ce.encode(cb); bb.rewind(); int lim = bb.limit(); byte[] br = new byte[lim]; bb.get(br); return br; } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
public static final String convertToString(byte bytes[], String encoding) { if (bytes == null) return PdfObject.NOTHING; if (encoding == null || encoding.length() == 0) { char c[] = new char[bytes.length]; for (int k = 0; k < bytes.length; ++k) c[k] = (char)(bytes[k] & 0xff); return new String(c); } ExtraEncoding extra = extraEncodings.get(encoding.toLowerCase()); if (extra != null) { String text = extra.byteToChar(bytes, encoding); if (text != null) return text; } char ch[] = null; if (encoding.equals(BaseFont.WINANSI)) ch = winansiByteToChar; else if (encoding.equals(PdfObject.TEXT_PDFDOCENCODING)) ch = pdfEncodingByteToChar; if (ch != null) { int len = bytes.length; char c[] = new char[len]; for (int k = 0; k < len; ++k) { c[k] = ch[bytes[k] & 0xff]; } return new String(c); } try { return new String(bytes, encoding); } catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
public void flateCompress(int compressionLevel) { if (!Document.compress) return; // check if the flateCompress-method has already been if (compressed) { return; } this.compressionLevel = compressionLevel; if (inputStream != null) { compressed = true; return; } // check if a filter already exists PdfObject filter = PdfReader.getPdfObject(get(PdfName.FILTER)); if (filter != null) { if (filter.isName()) { if (PdfName.FLATEDECODE.equals(filter)) return; } else if (filter.isArray()) { if (((PdfArray) filter).contains(PdfName.FLATEDECODE)) return; } else { throw new RuntimeException(MessageLocalization.getComposedMessage("stream.could.not.be.compressed.filter.is.not.a.name.or.array")); } } try { // compress ByteArrayOutputStream stream = new ByteArrayOutputStream(); Deflater deflater = new Deflater(compressionLevel); DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater); if (streamBytes != null) streamBytes.writeTo(zip); else zip.write(bytes); zip.close(); deflater.end(); // update the object streamBytes = stream; bytes = null; put(PdfName.LENGTH, new PdfNumber(streamBytes.size())); if (filter == null) { put(PdfName.FILTER, PdfName.FLATEDECODE); } else { PdfArray filters = new PdfArray(filter); filters.add(PdfName.FLATEDECODE); put(PdfName.FILTER, filters); } compressed = true; } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
void addPage(PdfDictionary page) { try { if (pages.size() % leafSize == 0) parents.add(writer.getPdfIndirectReference()); PdfIndirectReference parent = parents.get(parents.size() - 1); page.put(PdfName.PARENT, parent); PdfIndirectReference current = writer.getCurrentPage(); writer.addToBody(page, current); pages.add(current); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
PdfIndirectReference addPageRef(PdfIndirectReference pageRef) { try { if (pages.size() % leafSize == 0) parents.add(writer.getPdfIndirectReference()); pages.add(pageRef); return parents.get(parents.size() - 1); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected void buildStructTreeRootForTagged(PdfDictionary catalog) { if (tagged) { try { getStructureTreeRoot().buildTree(); } catch (Exception e) { throw new ExceptionConverter(e); } catalog.put(PdfName.STRUCTTREEROOT, structureTreeRoot.getReference()); PdfDictionary mi = new PdfDictionary(); mi.put(PdfName.MARKED, PdfBoolean.PDFTRUE); if (userProperties) mi.put(PdfName.USERPROPERTIES, PdfBoolean.PDFTRUE); catalog.put(PdfName.MARKINFO, mi); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectReference add(final PdfPage page, final PdfContents contents) throws PdfException { if (!open) { throw new PdfException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfIndirectObject object; try { object = addToBody(contents); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } page.add(object.getIndirectReference()); // [U5] if (group != null) { page.put(PdfName.GROUP, group); group = null; } else if (rgbTransparencyBlending) { PdfDictionary pp = new PdfDictionary(); pp.put(PdfName.TYPE, PdfName.GROUP); pp.put(PdfName.S, PdfName.TRANSPARENCY); pp.put(PdfName.CS, PdfName.DEVICERGB); page.put(PdfName.GROUP, pp); } root.addPage(page); currentPageNumber++; return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Override public void open() { super.open(); try { pdf_version.writeHeader(os); body = new PdfBody(this); if (isPdfX() && ((PdfXConformanceImp)pdfIsoConformance).isPdfX32002()) { PdfDictionary sec = new PdfDictionary(); sec.put(PdfName.GAMMA, new PdfArray(new float[]{2.2f,2.2f,2.2f})); sec.put(PdfName.MATRIX, new PdfArray(new float[]{0.4124f,0.2126f,0.0193f,0.3576f,0.7152f,0.1192f,0.1805f,0.0722f,0.9505f})); sec.put(PdfName.WHITEPOINT, new PdfArray(new float[]{0.9505f,1f,1.089f})); PdfArray arr = new PdfArray(PdfName.CALRGB); arr.add(sec); setDefaultColorspace(PdfName.DEFAULTRGB, addToBody(arr).getIndirectReference()); } } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Override public void close() { if (open) { if (currentPageNumber - 1 != pageReferences.size()) throw new RuntimeException("The page " + pageReferences.size() + " was requested but the document has only " + (currentPageNumber - 1) + " pages."); pdf.close(); try { addSharedObjectsToBody(); for (PdfOCG layer : documentOCG) { addToBody(layer.getPdfObject(), layer.getRef()); } // add the root to the body PdfIndirectReference rootRef = root.writePageTree(); // make the catalog-object and add it to the body PdfDictionary catalog = getCatalog(rootRef); // [C9] if there is XMP data to add: add it if (xmpMetadata != null) { PdfStream xmp = new PdfStream(xmpMetadata); 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); } catalog.put(PdfName.METADATA, body.add(xmp).getIndirectReference()); } // [C10] make pdfx conformant if (isPdfX()) { completeInfoDictionary(getInfo()); completeExtraCatalog(getExtraCatalog()); } // [C11] Output Intents if (extraCatalog != null) { catalog.mergeDifferent(extraCatalog); } writeOutlines(catalog, false); // add the Catalog to the body PdfIndirectObject indirectCatalog = addToBody(catalog, false); // add the info-object to the body PdfIndirectObject infoObj = addToBody(getInfo(), false); // [F1] encryption PdfIndirectReference encryption = null; PdfObject fileID = null; body.flushObjStm(); if (crypto != null) { PdfIndirectObject encryptionObject = addToBody(crypto.getEncryptionDictionary(), false); encryption = encryptionObject.getIndirectReference(); fileID = crypto.getFileID(); } else fileID = PdfEncryption.createInfoId(PdfEncryption.createDocumentId()); // write the cross-reference table of the body body.writeCrossReferenceTable(os, indirectCatalog.getIndirectReference(), infoObj.getIndirectReference(), encryption, fileID, prevxref); // make the trailer // [F2] full compression 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(), indirectCatalog.getIndirectReference(), infoObj.getIndirectReference(), encryption, fileID, prevxref); trailer.toPdf(this, os); } super.close(); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfName addDirectTemplateSimple(PdfTemplate template, final PdfName forcedName) { PdfIndirectReference ref = template.getIndirectReference(); Object obj[] = formXObjects.get(ref); PdfName name = null; try { if (obj == null) { if (forcedName == null) { name = new PdfName("Xf" + formXObjectsCounter); ++formXObjectsCounter; } else name = forcedName; if (template.getType() == PdfTemplate.TYPE_IMPORTED) { // If we got here from PdfCopy we'll have to fill importedPages PdfImportedPage ip = (PdfImportedPage)template; PdfReader r = ip.getPdfReaderInstance().getReader(); if (!readerInstances.containsKey(r)) { readerInstances.put(r, ip.getPdfReaderInstance()); } template = null; } formXObjects.put(ref, new Object[]{name, template}); } else name = (PdfName)obj[0]; } catch (Exception e) { throw new ExceptionConverter(e); } return name; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfName addSimplePattern(final PdfPatternPainter painter) { PdfName name = documentPatterns.get(painter); try { if ( name == null ) { name = new PdfName("P" + patternNumber); ++patternNumber; documentPatterns.put(painter, name); } } catch (Exception e) { throw new ExceptionConverter(e); } return name; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectReference add(final PdfImage pdfImage, PdfIndirectReference fixedRef) throws PdfException { if (! imageDictionary.contains(pdfImage.name())) { PdfWriter.checkPdfIsoConformance(this, PdfIsoKeys.PDFISOKEY_IMAGE, pdfImage); if (fixedRef instanceof PRIndirectReference) { PRIndirectReference r2 = (PRIndirectReference)fixedRef; fixedRef = new PdfIndirectReference(0, getNewObjectNumber(r2.getReader(), r2.getNumber(), r2.getGeneration())); } try { if (fixedRef == null) fixedRef = addToBody(pdfImage).getIndirectReference(); else addToBody(pdfImage, fixedRef); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } imageDictionary.put(pdfImage.name(), fixedRef); return fixedRef; } return (PdfIndirectReference) imageDictionary.get(pdfImage.name()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
protected PdfIndirectReference add(final PdfICCBased icc) { PdfIndirectObject object; try { object = addToBody(icc); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } return object.getIndirectReference(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void addAnnotation(PdfAnnotation annot, PdfDictionary pageN) { try { ArrayList<PdfAnnotation> allAnnots = new ArrayList<PdfAnnotation>(); if (annot.isForm()) { fieldsAdded = true; getAcroFields(); PdfFormField field = (PdfFormField)annot; if (field.getParent() != null) return; expandFields(field, allAnnots); } else allAnnots.add(annot); for (int k = 0; k < allAnnots.size(); ++k) { annot = allAnnots.get(k); if (annot.getPlaceInPage() > 0) pageN = reader.getPageN(annot.getPlaceInPage()); if (annot.isForm()) { if (!annot.isUsed()) { HashSet<PdfTemplate> templates = annot.getTemplates(); if (templates != null) fieldTemplates.addAll(templates); } PdfFormField field = (PdfFormField)annot; if (field.getParent() == null) addDocumentField(field.getIndirectReference()); } if (annot.isAnnotation()) { PdfObject pdfobj = PdfReader.getPdfObject(pageN.get(PdfName.ANNOTS), pageN); PdfArray annots = null; if (pdfobj == null || !pdfobj.isArray()) { annots = new PdfArray(); pageN.put(PdfName.ANNOTS, annots); markUsed(pageN); } else annots = (PdfArray)pdfobj; annots.add(annot.getIndirectReference()); markUsed(annots); if (!annot.isUsed()) { PdfRectangle rect = (PdfRectangle)annot.get(PdfName.RECT); if (rect != null && (rect.left() != 0 || rect.right() != 0 || rect.top() != 0 || rect.bottom() != 0)) { int rotation = reader.getPageRotation(pageN); Rectangle pageSize = reader.getPageSizeWithRotation(pageN); switch (rotation) { case 90: annot.put(PdfName.RECT, new PdfRectangle( pageSize.getTop() - rect.top(), rect.right(), pageSize.getTop() - rect.bottom(), rect.left())); break; case 180: annot.put(PdfName.RECT, new PdfRectangle( pageSize.getRight() - rect.left(), pageSize.getTop() - rect.bottom(), pageSize.getRight() - rect.right(), pageSize.getTop() - rect.top())); break; case 270: annot.put(PdfName.RECT, new PdfRectangle( rect.bottom(), pageSize.getRight() - rect.left(), rect.top(), pageSize.getRight() - rect.right())); break; } } } } if (!annot.isUsed()) { annot.setUsed(); addToBody(annot, annot.getIndirectReference()); } } } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPCell.java
public float getMaxHeight() { boolean pivoted = getRotation() == 90 || getRotation() == 270; Image img = getImage(); if (img != null) { img.scalePercent(100); float refWidth = pivoted ? img.getScaledHeight() : img.getScaledWidth(); float scale = (getRight() - getEffectivePaddingRight() - getEffectivePaddingLeft() - getLeft()) / refWidth; img.scalePercent(scale * 100); float refHeight = pivoted ? img.getScaledWidth() : img.getScaledHeight(); setBottom(getTop() - getEffectivePaddingTop() - getEffectivePaddingBottom() - refHeight); } else { if ((pivoted && hasFixedHeight()) || getColumn() == null) setBottom(getTop() - getFixedHeight()); else { ColumnText ct = ColumnText.duplicate(getColumn()); float right, top, left, bottom; if (pivoted) { right = PdfPRow.RIGHT_LIMIT; top = getRight() - getEffectivePaddingRight(); left = 0; bottom = getLeft() + getEffectivePaddingLeft(); } else { right = isNoWrap() ? PdfPRow.RIGHT_LIMIT : getRight() - getEffectivePaddingRight(); top = getTop() - getEffectivePaddingTop(); left = getLeft() + getEffectivePaddingLeft(); bottom = hasFixedHeight() ? getTop() + getEffectivePaddingBottom() - getFixedHeight() : PdfPRow.BOTTOM_LIMIT; } PdfPRow.setColumn(ct, left, bottom, right, top); try { ct.go(true); } catch (DocumentException e) { throw new ExceptionConverter(e); } if (pivoted) setBottom(getTop() - getEffectivePaddingTop() - getEffectivePaddingBottom() - ct.getFilledWidth()); else { float yLine = ct.getYLine(); if (isUseDescender()) yLine += ct.getDescender(); setBottom(yLine - getEffectivePaddingBottom()); } } } float height = getHeight(); if (height == getEffectivePaddingTop() + getEffectivePaddingBottom()) height = 0; if (hasFixedHeight()) height = getFixedHeight(); else if (hasMinimumHeight() && height < getMinimumHeight()) height = getMinimumHeight(); return height; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/events/FieldPositioningEvents.java
Override public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) { rect.setBottom(rect.getBottom() - 3); PdfFormField field = genericChunkFields.get(text); if (field == null) { TextField tf = new TextField(writer, new Rectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding), rect.getTop(padding)), text); tf.setFontSize(14); try { field = tf.getTextField(); } catch (Exception e) { throw new ExceptionConverter(e); } } else { field.put(PdfName.RECT, new PdfRectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding), rect.getTop(padding))); } if (parent == null) writer.addAnnotation(field); else parent.addKid(field); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
Override public void close() { if (closing) { super.close(); return; } closing = true; try { closeIt(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
Override protected PdfDictionary getCatalog(PdfIndirectReference rootObj) { try { PdfDictionary cat = pdf.getCatalog(rootObj); if (form != null) { PdfIndirectReference ref = addToBody(form).getIndirectReference(); cat.put(PdfName.ACROFORM, ref); } return cat; } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LZWDecoder.java
public void writeString(byte string[]) { try { uncompData.write(string); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
byte[] convertToBytes(String text) { byte b[] = null; switch (fontType) { case BaseFont.FONT_TYPE_T3: return baseFont.convertToBytes(text); case BaseFont.FONT_TYPE_T1: case BaseFont.FONT_TYPE_TT: { b = baseFont.convertToBytes(text); int len = b.length; for (int k = 0; k < len; ++k) shortTag[b[k] & 0xff] = 1; break; } case BaseFont.FONT_TYPE_CJK: { int len = text.length(); if (cjkFont.isIdentity()) { for (int k = 0; k < len; ++k) { cjkTag.put(text.charAt(k), 0); } } else { for (int k = 0; k < len; ++k) { int val; if (Utilities.isSurrogatePair(text, k)) { val = Utilities.convertToUtf32(text, k); k++; } else { val = text.charAt(k); } cjkTag.put(cjkFont.getCidCode(val), 0); } } b = cjkFont.convertToBytes(text); break; } case BaseFont.FONT_TYPE_DOCUMENT: { b = baseFont.convertToBytes(text); break; } case BaseFont.FONT_TYPE_TTUNI: { try { int len = text.length(); int metrics[] = null; char glyph[] = new char[len]; int i = 0; if (symbolic) { b = PdfEncodings.convertToBytes(text, "symboltt"); len = b.length; for (int k = 0; k < len; ++k) { metrics = ttu.getMetricsTT(b[k] & 0xff); if (metrics == null) continue; longTag.put(Integer.valueOf(metrics[0]), new int[]{metrics[0], metrics[1], ttu.getUnicodeDifferences(b[k] & 0xff)}); glyph[i++] = (char)metrics[0]; } } else if (canApplyGlyphSubstitution()) { return convertToBytesAfterGlyphSubstitution(text); } else { for (int k = 0; k < len; ++k) { int val; if (Utilities.isSurrogatePair(text, k)) { val = Utilities.convertToUtf32(text, k); k++; } else { val = text.charAt(k); } metrics = ttu.getMetricsTT(val); if (metrics == null) continue; int m0 = metrics[0]; Integer gl = Integer.valueOf(m0); if (!longTag.containsKey(gl)) longTag.put(gl, new int[]{m0, metrics[1], val}); glyph[i++] = (char)m0; } } String s = new String(glyph, 0, i); b = s.getBytes(CJKFont.CJK_ENCODING); } catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); } break; } } return b; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
public void writeFont(PdfWriter writer) { try { switch (fontType) { case BaseFont.FONT_TYPE_T3: baseFont.writeFont(writer, indirectReference, null); break; case BaseFont.FONT_TYPE_T1: case BaseFont.FONT_TYPE_TT: { int firstChar; int lastChar; for (firstChar = 0; firstChar < 256; ++firstChar) { if (shortTag[firstChar] != 0) break; } for (lastChar = 255; lastChar >= firstChar; --lastChar) { if (shortTag[lastChar] != 0) break; } if (firstChar > 255) { firstChar = 255; lastChar = 255; } baseFont.writeFont(writer, indirectReference, new Object[]{Integer.valueOf(firstChar), Integer.valueOf(lastChar), shortTag, Boolean.valueOf(subset)}); break; } case BaseFont.FONT_TYPE_CJK: baseFont.writeFont(writer, indirectReference, new Object[]{cjkTag}); break; case BaseFont.FONT_TYPE_TTUNI: baseFont.writeFont(writer, indirectReference, new Object[]{longTag, Boolean.valueOf(subset)}); break; } } catch(Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFunction.java
PdfIndirectReference getReference() { try { if (reference == null) { reference = writer.addToBody(dictionary).getIndirectReference(); } } catch (IOException ioe) { throw new ExceptionConverter(ioe); } return reference; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfAnnotationsImp.java
public PdfArray rotateAnnotations(PdfWriter writer, Rectangle pageSize) { PdfArray array = new PdfArray(); int rotation = pageSize.getRotation() % 360; int currentPage = writer.getCurrentPageNumber(); for (int k = 0; k < annotations.size(); ++k) { PdfAnnotation dic = annotations.get(k); int page = dic.getPlaceInPage(); if (page > currentPage) { delayedAnnotations.add(dic); continue; } if (dic.isForm()) { if (!dic.isUsed()) { HashSet<PdfTemplate> templates = dic.getTemplates(); if (templates != null) acroForm.addFieldTemplates(templates); } PdfFormField field = (PdfFormField)dic; if (field.getParent() == null) acroForm.addDocumentField(field.getIndirectReference()); } if (dic.isAnnotation()) { array.add(dic.getIndirectReference()); if (!dic.isUsed()) { PdfArray tmp = dic.getAsArray(PdfName.RECT); PdfRectangle rect; if (tmp.size() == 4) { rect = new PdfRectangle(tmp.getAsNumber(0).floatValue(), tmp.getAsNumber(1).floatValue(), tmp.getAsNumber(2).floatValue(), tmp.getAsNumber(3).floatValue()); } else { rect = new PdfRectangle(tmp.getAsNumber(0).floatValue(), tmp.getAsNumber(1).floatValue()); } if (rect != null) { switch (rotation) { case 90: dic.put(PdfName.RECT, new PdfRectangle( pageSize.getTop() - rect.bottom(), rect.left(), pageSize.getTop() - rect.top(), rect.right())); break; case 180: dic.put(PdfName.RECT, new PdfRectangle( pageSize.getRight() - rect.left(), pageSize.getTop() - rect.bottom(), pageSize.getRight() - rect.right(), pageSize.getTop() - rect.top())); break; case 270: dic.put(PdfName.RECT, new PdfRectangle( rect.bottom(), pageSize.getRight() - rect.left(), rect.top(), pageSize.getRight() - rect.right())); break; } } } } if (!dic.isUsed()) { dic.setUsed(); try { writer.addToBody(dic, dic.getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } } } return array; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static PdfObject getPdfObject(PdfObject obj) { if (obj == null) return null; if (!obj.isIndirect()) return obj; try { PRIndirectReference ref = (PRIndirectReference)obj; int idx = ref.getNumber(); boolean appendable = ref.getReader().appendable; obj = ref.getReader().getPdfObject(idx); if (obj == null) { return null; } else { if (appendable) { switch (obj.type()) { case PdfObject.NULL: obj = new PdfNull(); break; case PdfObject.BOOLEAN: obj = new PdfBoolean(((PdfBoolean)obj).booleanValue()); break; case PdfObject.NAME: obj = new PdfName(obj.getBytes()); break; } obj.setIndRef(ref); } return obj; } } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public PdfObject getPdfObject(final int idx) { try { lastXrefPartial = -1; if (idx < 0 || idx >= xrefObj.size()) return null; PdfObject obj = xrefObj.get(idx); if (!partial || obj != null) return obj; if (idx * 2 >= xref.length) return null; obj = readSingleObject(idx); lastXrefPartial = -1; if (obj != null) lastXrefPartial = idx; return obj; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public void close() { try { tokens.close(); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public PRIndirectReference getPageOrigRef(int pageNum) { try { --pageNum; if (pageNum < 0 || pageNum >= size()) return null; if (refsn != null) return refsn.get(pageNum); else { int n = refsp.get(pageNum); if (n == 0) { PRIndirectReference ref = getSinglePage(pageNum); if (reader.lastXrefPartial == -1) lastPageRead = -1; else lastPageRead = pageNum; reader.lastXrefPartial = -1; refsp.put(pageNum, ref.getNumber()); if (keepPages) lastPageRead = -1; return ref; } else { if (lastPageRead != pageNum) lastPageRead = -1; if (keepPages) lastPageRead = -1; return new PRIndirectReference(reader, n); } } } catch (Exception e) { throw new ExceptionConverter(e); } }
// 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/CFFFont.java
char getCard8() { try { byte i = buf.readByte(); return (char)(i & 0xff); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
char getCard16() { try { return buf.readChar(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
void seek(int offset) { try { buf.seek(offset); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
short getShort() { try { return buf.readShort(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
int getInt() { try { return buf.readInt(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
int getPosition() { try { return (int)buf.getFilePointer(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
Override public void emit(byte[] buffer) { //System.err.println("range emit offset "+offset+" size="+length); try { buf.seek(offset); for (int i=myOffset; i<myOffset+length; i++) buffer[i] = buf.readByte(); } catch (Exception e) { throw new ExceptionConverter(e); } //System.err.println("finished range emit"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void beginMarkedContentSequence(final PdfName tag, final PdfDictionary property, final boolean inline) { int contentSize = content.size(); if (property == null) { content.append(tag.getBytes()).append(" BMC").append_i(separator); setMcDepth(getMcDepth() + 1); } else { content.append(tag.getBytes()).append(' '); if (inline) try { property.toPdf(writer, content); } catch (Exception e) { throw new ExceptionConverter(e); } else { PdfObject[] objs; if (writer.propertyExists(property)) objs = writer.addSimpleProperty(property, null); else objs = writer.addSimpleProperty(property, writer.getPdfIndirectReference()); PdfName name = (PdfName)objs[0]; PageResources prs = getPageResources(); name = prs.addProperty(name, (PdfIndirectReference)objs[1]); content.append(name.getBytes()); } content.append(" BDC").append_i(separator); setMcDepth(getMcDepth() + 1); } markedContentSize += content.size() - contentSize; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addNames(final TreeMap<String, Destination> localDestinations, final HashMap<String, PdfObject> documentLevelJS, final HashMap<String, PdfObject> documentFileAttachment, final PdfWriter writer) { if (localDestinations.isEmpty() && documentLevelJS.isEmpty() && documentFileAttachment.isEmpty()) return; try { PdfDictionary names = new PdfDictionary(); if (!localDestinations.isEmpty()) { PdfArray ar = new PdfArray(); for (Map.Entry<String, Destination> entry : localDestinations.entrySet()) { String name = entry.getKey(); Destination dest = entry.getValue(); if (dest.destination == null) //no destination continue; PdfIndirectReference ref = dest.reference; ar.add(new PdfString(name, null)); ar.add(ref); } if (ar.size() > 0) { PdfDictionary dests = new PdfDictionary(); dests.put(PdfName.NAMES, ar); names.put(PdfName.DESTS, writer.addToBody(dests).getIndirectReference()); } } if (!documentLevelJS.isEmpty()) { PdfDictionary tree = PdfNameTree.writeTree(documentLevelJS, writer); names.put(PdfName.JAVASCRIPT, writer.addToBody(tree).getIndirectReference()); } if (!documentFileAttachment.isEmpty()) { names.put(PdfName.EMBEDDEDFILES, writer.addToBody(PdfNameTree.writeTree(documentFileAttachment, writer)).getIndirectReference()); } if (names.size() > 0) put(PdfName.NAMES, writer.addToBody(names).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void setAdditionalActions(final PdfDictionary actions) { try { put(PdfName.AA, writer.addToBody(actions).getIndirectReference()); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public void open() { if (!open) { super.open(); writer.open(); rootOutline = new PdfOutline(writer); currentOutline = rootOutline; } try { initPage(); if (isTagged(writer)) { openMCDocument = true; } } catch(DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public boolean newPage() { try { flushFloatingElements(); } catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } lastElementType = -1; if (isPageEmpty()) { setNewPageSizeAndMargins(); return false; } if (!open || close) { throw new RuntimeException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) pageEvent.onEndPage(writer, this); //Added to inform any listeners that we are moving to a new page (added by David Freels) super.newPage(); // the following 2 lines were added by Pelikan Stephan indentation.imageIndentLeft = 0; indentation.imageIndentRight = 0; try { // we flush the arraylist with recently written lines flushLines(); // we prepare the elements of the page dictionary // [U1] page size and rotation int rotation = pageSize.getRotation(); // [C10] if (writer.isPdfIso()) { if (thisBoxSize.containsKey("art") && thisBoxSize.containsKey("trim")) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("only.one.of.artbox.or.trimbox.can.exist.in.the.page")); if (!thisBoxSize.containsKey("art") && !thisBoxSize.containsKey("trim")) { if (thisBoxSize.containsKey("crop")) thisBoxSize.put("trim", thisBoxSize.get("crop")); else thisBoxSize.put("trim", new PdfRectangle(pageSize, pageSize.getRotation())); } } // [M1] pageResources.addDefaultColorDiff(writer.getDefaultColorspace()); if (writer.isRgbTransparencyBlending()) { PdfDictionary dcs = new PdfDictionary(); dcs.put(PdfName.CS, PdfName.DEVICERGB); pageResources.addDefaultColorDiff(dcs); } PdfDictionary resources = pageResources.getResources(); // we create the page dictionary PdfPage page = new PdfPage(new PdfRectangle(pageSize, rotation), thisBoxSize, resources, rotation); if (isTagged(writer)) { page.put(PdfName.TABS, PdfName.S); } else { page.put(PdfName.TABS, writer.getTabs()); } page.putAll(writer.getPageDictEntries()); writer.resetPageDictEntries(); // we complete the page dictionary // [U3] page actions: additional actions if (pageAA != null) { page.put(PdfName.AA, writer.addToBody(pageAA).getIndirectReference()); pageAA = null; } // [C5] and [C8] we add the annotations if (annotationsImp.hasUnusedAnnotations()) { PdfArray array = annotationsImp.rotateAnnotations(writer, pageSize); if (array.size() != 0) page.put(PdfName.ANNOTS, array); } // [F12] we add tag info if (isTagged(writer)) page.put(PdfName.STRUCTPARENTS, new PdfNumber(writer.getCurrentPageNumber() - 1)); if (text.size() > textEmptySize || isTagged(writer)) text.endText(); else text = null; ArrayList<IAccessibleElement> mcBlocks = null; if (isTagged(writer)) { mcBlocks = writer.getDirectContent().saveMCBlocks(); } writer.add(page, new PdfContents(writer.getDirectContentUnder(), graphics, !isTagged(writer) ? text : null, writer.getDirectContent(), pageSize)); // we initialize the new page initPage(); if (isTagged(writer)) { writer.getDirectContentUnder().restoreMCBlocks(mcBlocks); } } catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } catch (IOException ioe) { throw new ExceptionConverter(ioe); } return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void initPage() throws DocumentException { // the pagenumber is incremented pageN++; // initialization of some page objects annotationsImp.resetAnnotations(); pageResources = new PageResources(); writer.resetContent(); if (isTagged(writer)) { graphics = writer.getDirectContentUnder().getDuplicate(); writer.getDirectContent().duplicatedFrom = graphics; } else { graphics = new PdfContentByte(writer); } markPoint = 0; setNewPageSizeAndMargins(); imageEnd = -1; indentation.imageIndentRight = 0; indentation.imageIndentLeft = 0; indentation.indentBottom = 0; indentation.indentTop = 0; currentHeight = 0; // backgroundcolors, etc... thisBoxSize = new HashMap<String, PdfRectangle>(boxSize); if (pageSize.getBackgroundColor() != null || pageSize.hasBorders() || pageSize.getBorderColor() != null) { add(pageSize); } float oldleading = leading; int oldAlignment = alignment; pageEmpty = true; // if there is an image waiting to be drawn, draw it try { if (imageWait != null) { add(imageWait); imageWait = null; } } catch(Exception e) { throw new ExceptionConverter(e); } leading = oldleading; alignment = oldAlignment; carriageReturn(); PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) { if (firstPageEvent) { pageEvent.onOpenDocument(writer, this); } pageEvent.onStartPage(writer, this); } firstPageEvent = false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void ensureNewLine() { try { if (lastElementType == Element.PHRASE || lastElementType == Element.CHUNK) { newLine(); flushLines(); } } catch (DocumentException ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
PdfCatalog getCatalog(final PdfIndirectReference pages) { PdfCatalog catalog = new PdfCatalog(pages, writer); // [C1] outlines if (rootOutline.getKids().size() > 0) { catalog.put(PdfName.PAGEMODE, PdfName.USEOUTLINES); catalog.put(PdfName.OUTLINES, rootOutline.indirectReference()); } // [C2] version writer.getPdfVersion().addToCatalog(catalog); // [C3] preferences viewerPreferences.addToCatalog(catalog); // [C4] pagelabels if (pageLabels != null) { catalog.put(PdfName.PAGELABELS, pageLabels.getDictionary(writer)); } // [C5] named objects catalog.addNames(localDestinations, getDocumentLevelJS(), documentFileAttachment, writer); // [C6] actions if (openActionName != null) { PdfAction action = getLocalGotoAction(openActionName); catalog.setOpenAction(action); } else if (openActionAction != null) catalog.setOpenAction(openActionAction); if (additionalActions != null) { catalog.setAdditionalActions(additionalActions); } // [C7] portable collections if (collection != null) { catalog.put(PdfName.COLLECTION, collection); } // [C8] AcroForm if (annotationsImp.hasValidAcroForm()) { try { catalog.put(PdfName.ACROFORM, writer.addToBody(annotationsImp.getAcroForm()).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } } if (language != null) { catalog.put(PdfName.LANG, language); } return catalog; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addJavaScript(final PdfAction js) { if (js.get(PdfName.JS) == null) throw new RuntimeException(MessageLocalization.getComposedMessage("only.javascript.actions.are.allowed")); try { documentLevelJS.put(SIXTEEN_DIGITS.format(jsCounter++), writer.addToBody(js).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addJavaScript(final String name, final PdfAction js) { if (js.get(PdfName.JS) == null) throw new RuntimeException(MessageLocalization.getComposedMessage("only.javascript.actions.are.allowed")); try { documentLevelJS.put(name, writer.addToBody(js).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
Override protected PdfDictionary getCatalog(PdfIndirectReference rootObj) { try { PdfDictionary theCat = pdf.getCatalog(rootObj); buildStructTreeRootForTagged(theCat); if (fieldArray == null) { if (acroForm != null) theCat.put(PdfName.ACROFORM, acroForm); } else addFieldResources(theCat); return theCat; } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
public void addAnnotation(PdfAnnotation annot) { try { ArrayList<PdfAnnotation> allAnnots = new ArrayList<PdfAnnotation>(); if (annot.isForm()) { PdfFormField field = (PdfFormField)annot; if (field.getParent() != null) return; expandFields(field, allAnnots); if (cstp.fieldTemplates == null) cstp.fieldTemplates = new HashSet<PdfTemplate>(); } else allAnnots.add(annot); for (int k = 0; k < allAnnots.size(); ++k) { annot = allAnnots.get(k); if (annot.isForm()) { if (!annot.isUsed()) { HashSet<PdfTemplate> templates = annot.getTemplates(); if (templates != null) cstp.fieldTemplates.addAll(templates); } PdfFormField field = (PdfFormField)annot; if (field.getParent() == null) addDocumentField(field.getIndirectReference()); } if (annot.isAnnotation()) { PdfObject pdfobj = PdfReader.getPdfObject(pageN.get(PdfName.ANNOTS), pageN); PdfArray annots = null; if (pdfobj == null || !pdfobj.isArray()) { annots = new PdfArray(); pageN.put(PdfName.ANNOTS, annots); } else annots = (PdfArray)pdfobj; annots.add(annot.getIndirectReference()); if (!annot.isUsed()) { PdfRectangle rect = (PdfRectangle)annot.get(PdfName.RECT); if (rect != null && (rect.left() != 0 || rect.right() != 0 || rect.top() != 0 || rect.bottom() != 0)) { int rotation = reader.getPageRotation(pageN); Rectangle pageSize = reader.getPageSizeWithRotation(pageN); switch (rotation) { case 90: annot.put(PdfName.RECT, new PdfRectangle( pageSize.getTop() - rect.bottom(), rect.left(), pageSize.getTop() - rect.top(), rect.right())); break; case 180: annot.put(PdfName.RECT, new PdfRectangle( pageSize.getRight() - rect.left(), pageSize.getTop() - rect.bottom(), pageSize.getRight() - rect.right(), pageSize.getTop() - rect.top())); break; case 270: annot.put(PdfName.RECT, new PdfRectangle( rect.bottom(), pageSize.getRight() - rect.left(), rect.top(), pageSize.getRight() - rect.right())); break; } } } } if (!annot.isUsed()) { annot.setUsed(); cstp.addToBody(annot, annot.getIndirectReference()); } } } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
public void setData(byte[] data, boolean compress, int compressionLevel) { remove(PdfName.FILTER); this.offset = -1; if (Document.compress && compress) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); Deflater deflater = new Deflater(compressionLevel); DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater); zip.write(data); zip.close(); deflater.end(); bytes = stream.toByteArray(); this.compressionLevel = compressionLevel; } catch (IOException ioe) { throw new ExceptionConverter(ioe); } put(PdfName.FILTER, PdfName.FLATEDECODE); } else bytes = data; setLength(bytes.length); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
public void processContent(byte[] contentBytes, PdfDictionary resources){ this.resources.push(resources); try { PRTokeniser tokeniser = new PRTokeniser(new RandomAccessFileOrArray(new RandomAccessSourceFactory().createSource(contentBytes))); PdfContentParser ps = new PdfContentParser(tokeniser); ArrayList<PdfObject> operands = new ArrayList<PdfObject>(); while (ps.parse(operands).size() > 0){ PdfLiteral operator = (PdfLiteral)operands.get(operands.size()-1); if ("BI".equals(operator.toString())){ // we don't call invokeOperator for embedded images - this is one area of the PDF spec that is particularly nasty and inconsistent PdfDictionary colorSpaceDic = resources != null ? resources.getAsDict(PdfName.COLORSPACE) : null; ImageRenderInfo renderInfo = ImageRenderInfo.createForEmbeddedImage(gs().ctm, InlineImageUtils.parseInlineImage(ps, colorSpaceDic), colorSpaceDic); renderListener.renderImage(renderInfo); } else { invokeOperator(operator, operands); } } } catch (Exception e) { throw new ExceptionConverter(e); } this.resources.pop(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
public void handleXObject(PdfContentStreamProcessor processor, PdfStream stream, PdfIndirectReference ref) { final PdfDictionary resources = stream.getAsDict(PdfName.RESOURCES); // we read the content bytes up here so if it fails we don't leave the graphics state stack corrupted // this is probably not necessary (if we fail on this, probably the entire content stream processing // operation should be rejected byte[] contentBytes; try { contentBytes = ContentByteUtils.getContentBytesFromContentObject(stream); } catch (IOException e1) { throw new ExceptionConverter(e1); } final PdfArray matrix = stream.getAsArray(PdfName.MATRIX); new PushGraphicsState().invoke(processor, null, null); if (matrix != null){ float a = matrix.getAsNumber(0).floatValue(); float b = matrix.getAsNumber(1).floatValue(); float c = matrix.getAsNumber(2).floatValue(); float d = matrix.getAsNumber(3).floatValue(); float e = matrix.getAsNumber(4).floatValue(); float f = matrix.getAsNumber(5).floatValue(); Matrix formMatrix = new Matrix(a, b, c, d, e, f); processor.gs().ctm = formMatrix.multiply(processor.gs().ctm); } processor.processContent(contentBytes, resources); new PopGraphicsState().invoke(processor, null, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
public static ICC_Profile getInstance(byte[] data, int numComponents) { if (data.length < 128 || data[36] != 0x61 || data[37] != 0x63 || data[38] != 0x73 || data[39] != 0x70) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); try { ICC_Profile icc = new ICC_Profile(); icc.data = data; Integer cs; cs = cstags.get(new String(data, 16, 4, "US-ASCII")); int nc = cs == null ? 0 : cs.intValue(); icc.numComponents = nc; // invalid ICC if (nc != numComponents) { throw new IllegalArgumentException("ICC profile contains " + nc + " component(s), the image data contains " + numComponents + " component(s)"); } return icc; } catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
public static ICC_Profile getInstance(byte[] data) { try { Integer cs; cs = cstags.get(new String(data, 16, 4, "US-ASCII")); int numComponents = cs == null ? 0 : cs.intValue(); return getInstance(data, numComponents); } catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
public static ICC_Profile getInstance(InputStream file) { try { byte[] head = new byte[128]; int remain = head.length; int ptr = 0; while (remain > 0) { int n = file.read(head, ptr, remain); if (n < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain -= n; ptr += n; } if (head[36] != 0x61 || head[37] != 0x63 || head[38] != 0x73 || head[39] != 0x70) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain = (head[0] & 0xff) << 24 | (head[1] & 0xff) << 16 | (head[2] & 0xff) << 8 | head[3] & 0xff; byte[] icc = new byte[remain]; System.arraycopy(head, 0, icc, 0, head.length); remain -= head.length; ptr = head.length; while (remain > 0) { int n = file.read(icc, ptr, remain); if (n < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain -= n; ptr += n; } return getInstance(icc); } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
public static ICC_Profile GetInstance(String fname) { FileInputStream fs = null; try { fs = new FileInputStream(fname); ICC_Profile icc = getInstance(fs); return icc; } catch (Exception ex) { throw new ExceptionConverter(ex); } finally { try{fs.close();}catch(Exception x){} } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
Override void addChar(PdfString mark, PdfObject code) { try { byte[] src = mark.getBytes(); String dest = createStringFromBytes(code.getBytes()); if (src.length == 1) { singleByteMappings.put(Integer.valueOf(src[0] & 0xff), dest); } else if (src.length == 2) { int intSrc = src[0] & 0xFF; intSrc <<= 8; intSrc |= src[1] & 0xFF; doubleByteMappings.put(Integer.valueOf(intSrc), dest); } else { throw new IOException(MessageLocalization.getComposedMessage("mapping.code.should.be.1.or.two.bytes.and.not.1", src.length)); } } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// 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 void setCheckType(int checkType) { if (checkType < TYPE_CHECK || checkType > TYPE_STAR) checkType = TYPE_CIRCLE; this.checkType = checkType; setText(typeChars[checkType - 1]); try { setFont(BaseFont.createFont(BaseFont.ZAPFDINGBATS, BaseFont.WINANSI, false)); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
Override public byte[] convertToBytes(String text) { if (cidDirect) return super.convertToBytes(text); try { if (text.length() == 1) return convertToBytes((int)text.charAt(0)); ByteArrayOutputStream bout = new ByteArrayOutputStream(); for (int k = 0; k < text.length(); ++k) { int val; if (Utilities.isSurrogatePair(text, k)) { val = Utilities.convertToUtf32(text, k); k++; } else { val = text.charAt(k); } bout.write(convertToBytes(val)); } return bout.toByteArray(); } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFont.java
static PdfFont getDefaultFont() { try { BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false); return new PdfFont(bf, 12); } catch (Exception ee) { throw new ExceptionConverter(ee); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode.java
public Image createImageWithBarcode(PdfContentByte cb, BaseColor barColor, BaseColor textColor) { try { return Image.getInstance(createTemplateWithBarcode(cb, barColor, textColor)); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public void setupAllKeys(byte userPassword[], byte ownerPassword[], int permissions) { if (ownerPassword == null || ownerPassword.length == 0) ownerPassword = md5.digest(createDocumentId()); permissions |= (revision == STANDARD_ENCRYPTION_128 || revision == AES_128 || revision == AES_256) ? 0xfffff0c0 : 0xffffffc0; permissions &= 0xfffffffc; this.permissions = permissions; if (revision == AES_256) { try { if (userPassword == null) userPassword = new byte[0]; documentID = createDocumentId(); byte[] uvs = IVGenerator.getIV(8); byte[] uks = IVGenerator.getIV(8); key = IVGenerator.getIV(32); // Algorithm 3.8.1 MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(userPassword, 0, Math.min(userPassword.length, 127)); md.update(uvs); userKey = new byte[48]; md.digest(userKey, 0, 32); System.arraycopy(uvs, 0, userKey, 32, 8); System.arraycopy(uks, 0, userKey, 40, 8); // Algorithm 3.8.2 md.update(userPassword, 0, Math.min(userPassword.length, 127)); md.update(uks); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(true, md.digest()); ueKey = ac.processBlock(key, 0, key.length); // Algorithm 3.9.1 byte[] ovs = IVGenerator.getIV(8); byte[] oks = IVGenerator.getIV(8); md.update(ownerPassword, 0, Math.min(ownerPassword.length, 127)); md.update(ovs); md.update(userKey); ownerKey = new byte[48]; md.digest(ownerKey, 0, 32); System.arraycopy(ovs, 0, ownerKey, 32, 8); System.arraycopy(oks, 0, ownerKey, 40, 8); // Algorithm 3.9.2 md.update(ownerPassword, 0, Math.min(ownerPassword.length, 127)); md.update(oks); md.update(userKey); ac = new AESCipherCBCnoPad(true, md.digest()); oeKey = ac.processBlock(key, 0, key.length); // Algorithm 3.10 byte[] permsp = IVGenerator.getIV(16); permsp[0] = (byte)permissions; permsp[1] = (byte)(permissions >> 8); permsp[2] = (byte)(permissions >> 16); permsp[3] = (byte)(permissions >> 24); permsp[4] = (byte)(255); permsp[5] = (byte)(255); permsp[6] = (byte)(255); permsp[7] = (byte)(255); permsp[8] = encryptMetadata ? (byte)'T' : (byte)'F'; permsp[9] = (byte)'a'; permsp[10] = (byte)'d'; permsp[11] = (byte)'b'; ac = new AESCipherCBCnoPad(true, key); perms = ac.processBlock(permsp, 0, permsp.length); } catch (Exception ex) { throw new ExceptionConverter(ex); } } else { // PDF reference 3.5.2 Standard Security Handler, Algorithm 3.3-1 // If there is no owner password, use the user password instead. byte userPad[] = padPassword(userPassword); byte ownerPad[] = padPassword(ownerPassword); this.ownerKey = computeOwnerKey(userPad, ownerPad); documentID = createDocumentId(); setupByUserPad(this.documentID, userPad, this.ownerKey, permissions); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public boolean readKey(PdfDictionary enc, byte[] password) throws BadPasswordException { try { if (password == null) password = new byte[0]; byte[] oValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.O).toString()); byte[] uValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.U).toString()); byte[] oeValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.OE).toString()); byte[] ueValue = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.UE).toString()); byte[] perms = com.itextpdf.text.DocWriter.getISOBytes(enc.get(PdfName.PERMS).toString()); boolean isUserPass = false; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); byte[] hash = md.digest(); boolean isOwnerPass = compareArray(hash, oValue, 32); if (isOwnerPass) { md.update(password, 0, Math.min(password.length, 127)); md.update(oValue, KEY_SALT_OFFSET, SALT_LENGHT); md.update(uValue, 0, OU_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(oeValue, 0, oeValue.length); } else { md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); isUserPass = compareArray(hash, uValue, 32); if (!isUserPass) throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); md.update(password, 0, Math.min(password.length, 127)); md.update(uValue, KEY_SALT_OFFSET, SALT_LENGHT); hash = md.digest(); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, hash); key = ac.processBlock(ueValue, 0, ueValue.length); } AESCipherCBCnoPad ac = new AESCipherCBCnoPad(false, key); byte[] decPerms = ac.processBlock(perms, 0, perms.length); if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b') throw new BadPasswordException(MessageLocalization.getComposedMessage("bad.user.password")); permissions = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8) | ((decPerms[2] & 0xff) << 16) | ((decPerms[2] & 0xff) << 24); encryptMetadata = decPerms[8] == (byte)'T'; return isOwnerPass; } catch (BadPasswordException ex) { throw ex; } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public static byte[] createDocumentId() { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new ExceptionConverter(e); } long time = System.currentTimeMillis(); long mem = Runtime.getRuntime().freeMemory(); String s = time + "+" + mem + "+" + (seq++); return md5.digest(s.getBytes()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public PdfDictionary getEncryptionDictionary() { PdfDictionary dic = new PdfDictionary(); if (publicKeyHandler.getRecipientsSize() > 0) { PdfArray recipients = null; dic.put(PdfName.FILTER, PdfName.PUBSEC); dic.put(PdfName.R, new PdfNumber(revision)); try { recipients = publicKeyHandler.getEncodedRecipients(); } catch (Exception f) { throw new ExceptionConverter(f); } if (revision == STANDARD_ENCRYPTION_40) { dic.put(PdfName.V, new PdfNumber(1)); dic.put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4); dic.put(PdfName.RECIPIENTS, recipients); } else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata) { dic.put(PdfName.V, new PdfNumber(2)); dic.put(PdfName.LENGTH, new PdfNumber(128)); dic.put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4); dic.put(PdfName.RECIPIENTS, recipients); } else { if (revision == AES_256) { dic.put(PdfName.R, new PdfNumber(AES_256)); dic.put(PdfName.V, new PdfNumber(5)); } else { dic.put(PdfName.R, new PdfNumber(AES_128)); dic.put(PdfName.V, new PdfNumber(4)); } dic.put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S5); PdfDictionary stdcf = new PdfDictionary(); stdcf.put(PdfName.RECIPIENTS, recipients); if (!encryptMetadata) stdcf.put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); if (revision == AES_128) { stdcf.put(PdfName.CFM, PdfName.AESV2); stdcf.put(PdfName.LENGTH, new PdfNumber(128)); } else if (revision == AES_256) { stdcf.put(PdfName.CFM, PdfName.AESV3); stdcf.put(PdfName.LENGTH, new PdfNumber(256)); } else stdcf.put(PdfName.CFM, PdfName.V2); PdfDictionary cf = new PdfDictionary(); cf.put(PdfName.DEFAULTCRYPTFILTER, stdcf); dic.put(PdfName.CF, cf); if (embeddedFilesOnly) { dic.put(PdfName.EFF, PdfName.DEFAULTCRYPTFILTER); dic.put(PdfName.STRF, PdfName.IDENTITY); dic.put(PdfName.STMF, PdfName.IDENTITY); } else { dic.put(PdfName.STRF, PdfName.DEFAULTCRYPTFILTER); dic.put(PdfName.STMF, PdfName.DEFAULTCRYPTFILTER); } } MessageDigest md = null; byte[] encodedRecipient = null; try { if (revision == AES_256) md = MessageDigest.getInstance("SHA-256"); else md = MessageDigest.getInstance("SHA-1"); md.update(publicKeyHandler.getSeed()); for (int i = 0; i < publicKeyHandler.getRecipientsSize(); i++) { encodedRecipient = publicKeyHandler.getEncodedRecipient(i); md.update(encodedRecipient); } if (!encryptMetadata) md.update(new byte[] { (byte) 255, (byte) 255, (byte) 255, (byte) 255 }); } catch (Exception f) { throw new ExceptionConverter(f); } byte[] mdResult = md.digest(); if (revision == AES_256) key = mdResult; else setupByEncryptionKey(mdResult, keyLength); } else { dic.put(PdfName.FILTER, PdfName.STANDARD); dic.put(PdfName.O, new PdfLiteral(PdfContentByte .escapeString(ownerKey))); dic.put(PdfName.U, new PdfLiteral(PdfContentByte .escapeString(userKey))); dic.put(PdfName.P, new PdfNumber(permissions)); dic.put(PdfName.R, new PdfNumber(revision)); if (revision == STANDARD_ENCRYPTION_40) { dic.put(PdfName.V, new PdfNumber(1)); } else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata) { dic.put(PdfName.V, new PdfNumber(2)); dic.put(PdfName.LENGTH, new PdfNumber(128)); } else if (revision == AES_256) { if (!encryptMetadata) dic.put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); dic.put(PdfName.OE, new PdfLiteral(PdfContentByte .escapeString(oeKey))); dic.put(PdfName.UE, new PdfLiteral(PdfContentByte .escapeString(ueKey))); dic.put(PdfName.PERMS, new PdfLiteral(PdfContentByte .escapeString(perms))); dic.put(PdfName.V, new PdfNumber(revision)); dic.put(PdfName.LENGTH, new PdfNumber(256)); PdfDictionary stdcf = new PdfDictionary(); stdcf.put(PdfName.LENGTH, new PdfNumber(32)); if (embeddedFilesOnly) { stdcf.put(PdfName.AUTHEVENT, PdfName.EFOPEN); dic.put(PdfName.EFF, PdfName.STDCF); dic.put(PdfName.STRF, PdfName.IDENTITY); dic.put(PdfName.STMF, PdfName.IDENTITY); } else { stdcf.put(PdfName.AUTHEVENT, PdfName.DOCOPEN); dic.put(PdfName.STRF, PdfName.STDCF); dic.put(PdfName.STMF, PdfName.STDCF); } stdcf.put(PdfName.CFM, PdfName.AESV3); PdfDictionary cf = new PdfDictionary(); cf.put(PdfName.STDCF, stdcf); dic.put(PdfName.CF, cf); } else { if (!encryptMetadata) dic.put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); dic.put(PdfName.R, new PdfNumber(AES_128)); dic.put(PdfName.V, new PdfNumber(4)); dic.put(PdfName.LENGTH, new PdfNumber(128)); PdfDictionary stdcf = new PdfDictionary(); stdcf.put(PdfName.LENGTH, new PdfNumber(16)); if (embeddedFilesOnly) { stdcf.put(PdfName.AUTHEVENT, PdfName.EFOPEN); dic.put(PdfName.EFF, PdfName.STDCF); dic.put(PdfName.STRF, PdfName.IDENTITY); dic.put(PdfName.STMF, PdfName.IDENTITY); } else { stdcf.put(PdfName.AUTHEVENT, PdfName.DOCOPEN); dic.put(PdfName.STRF, PdfName.STDCF); dic.put(PdfName.STMF, PdfName.STDCF); } if (revision == AES_128) stdcf.put(PdfName.CFM, PdfName.AESV2); else stdcf.put(PdfName.CFM, PdfName.V2); PdfDictionary cf = new PdfDictionary(); cf.put(PdfName.STDCF, stdcf); dic.put(PdfName.CF, cf); } } return dic; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public byte[] encryptByteArray(byte[] b) { try { ByteArrayOutputStream ba = new ByteArrayOutputStream(); OutputStreamEncryption os2 = getEncryptionStream(ba); os2.write(b); os2.finish(); return ba.toByteArray(); } catch (IOException ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public byte[] decryptByteArray(byte[] b) { try { ByteArrayOutputStream ba = new ByteArrayOutputStream(); StandardDecryption dec = getDecryptor(); byte[] b2 = dec.update(b, 0, b.length); if (b2 != null) ba.write(b2); b2 = dec.finish(); if (b2 != null) ba.write(b2); return ba.toByteArray(); } catch (IOException ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPageLabels.java
public PdfDictionary getDictionary(PdfWriter writer) { try { return PdfNumberTree.writeTree(map, writer); } catch (IOException e) { throw new ExceptionConverter(e); } }
// 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 initFont() { processToUnicode(); try { //if (toUnicodeCmap == null) processUni2Byte(); spaceWidth = super.getWidth(' '); if (spaceWidth == 0){ spaceWidth = computeAverageWidth(); } if (cjkEncoding != null) { byteCid = CMapCache.getCachedCMapByteCid(cjkEncoding); cidUni = CMapCache.getCachedCMapCidUni(uniMap); } } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
public static X500Name getIssuerFields(X509Certificate cert) { try { return new X500Name((ASN1Sequence)CertificateInfo.getIssuer(cert.getTBSCertificate())); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
public static ASN1Primitive getIssuer(byte[] enc) { try { ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc)); ASN1Sequence seq = (ASN1Sequence)in.readObject(); return (ASN1Primitive)seq.getObjectAt(seq.getObjectAt(0) instanceof ASN1TaggedObject ? 3 : 2); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
public static X500Name getSubjectFields(X509Certificate cert) { try { if (cert != null) return new X500Name((ASN1Sequence)CertificateInfo.getSubject(cert.getTBSCertificate())); } catch (Exception e) { throw new ExceptionConverter(e); } return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
public static ASN1Primitive getSubject(byte[] enc) { try { ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(enc)); ASN1Sequence seq = (ASN1Sequence)in.readObject(); return (ASN1Primitive)seq.getObjectAt(seq.getObjectAt(0) instanceof ASN1TaggedObject ? 5 : 4); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
public void setExternalDigest(byte digest[], byte RSAdata[], String digestEncryptionAlgorithm) { externalDigest = digest; externalRSAdata = RSAdata; if (digestEncryptionAlgorithm != null) { if (digestEncryptionAlgorithm.equals("RSA")) { this.digestEncryptionAlgorithmOid = SecurityIDs.ID_RSA; } else if (digestEncryptionAlgorithm.equals("DSA")) { this.digestEncryptionAlgorithmOid = SecurityIDs.ID_DSA; } else if (digestEncryptionAlgorithm.equals("ECDSA")) { this.digestEncryptionAlgorithmOid = SecurityIDs.ID_ECDSA; } else throw new ExceptionConverter(new NoSuchAlgorithmException(MessageLocalization.getComposedMessage("unknown.key.algorithm.1", digestEncryptionAlgorithm))); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
public byte[] getEncodedPKCS1() { try { if (externalDigest != null) digest = externalDigest; else digest = sig.sign(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dout = new ASN1OutputStream(bOut); dout.writeObject(new DEROctetString(digest)); dout.close(); return bOut.toByteArray(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
public byte[] getEncodedPKCS7(byte secondDigest[], Calendar signingTime, TSAClient tsaClient, byte[] ocsp, Collection<byte[]> crlBytes, CryptoStandard sigtype) { try { if (externalDigest != null) { digest = externalDigest; if (RSAdata != null) RSAdata = externalRSAdata; } else if (externalRSAdata != null && RSAdata != null) { RSAdata = externalRSAdata; sig.update(RSAdata); digest = sig.sign(); } else { if (RSAdata != null) { RSAdata = messageDigest.digest(); sig.update(RSAdata); } digest = sig.sign(); } // Create the set of Hash algorithms ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector(); for (Object element : digestalgos) { ASN1EncodableVector algos = new ASN1EncodableVector(); algos.add(new ASN1ObjectIdentifier((String)element)); algos.add(DERNull.INSTANCE); digestAlgorithms.add(new DERSequence(algos)); } // Create the contentInfo. ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA)); if (RSAdata != null) v.add(new DERTaggedObject(0, new DEROctetString(RSAdata))); DERSequence contentinfo = new DERSequence(v); // Get all the certificates // v = new ASN1EncodableVector(); for (Object element : certs) { ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(((X509Certificate)element).getEncoded())); v.add(tempstream.readObject()); } DERSet dercertificates = new DERSet(v); // Create signerinfo structure. // ASN1EncodableVector signerinfo = new ASN1EncodableVector(); // Add the signerInfo version // signerinfo.add(new ASN1Integer(signerversion)); v = new ASN1EncodableVector(); v.add(CertificateInfo.getIssuer(signCert.getTBSCertificate())); v.add(new ASN1Integer(signCert.getSerialNumber())); signerinfo.add(new DERSequence(v)); // Add the digestAlgorithm v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(digestAlgorithmOid)); v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // add the authenticated attribute if present if (secondDigest != null && signingTime != null) { signerinfo.add(new DERTaggedObject(false, 0, getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype))); } // Add the digestEncryptionAlgorithm v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(digestEncryptionAlgorithmOid)); v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // Add the digest signerinfo.add(new DEROctetString(digest)); // When requested, go get and add the timestamp. May throw an exception. // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15 // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest if (tsaClient != null) { byte[] tsImprint = tsaClient.getMessageDigest().digest(digest); byte[] tsToken = tsaClient.getTimeStampToken(tsImprint); if (tsToken != null) { ASN1EncodableVector unauthAttributes = buildUnauthenticatedAttributes(tsToken); if (unauthAttributes != null) { signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unauthAttributes))); } } } // Finally build the body out of all the components above ASN1EncodableVector body = new ASN1EncodableVector(); body.add(new ASN1Integer(version)); body.add(new DERSet(digestAlgorithms)); body.add(contentinfo); body.add(new DERTaggedObject(false, 0, dercertificates)); // Only allow one signerInfo body.add(new DERSet(new DERSequence(signerinfo))); // Now we have the body, wrap it in it's PKCS7Signed shell // and return it // ASN1EncodableVector whole = new ASN1EncodableVector(); whole.add(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA)); whole.add(new DERTaggedObject(0, new DERSequence(body))); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dout = new ASN1OutputStream(bOut); dout.writeObject(new DERSequence(whole)); dout.close(); return bOut.toByteArray(); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
public byte[] getAuthenticatedAttributeBytes(byte secondDigest[], Calendar signingTime, byte[] ocsp, Collection<byte[]> crlBytes, CryptoStandard sigtype) { try { return getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype).getEncoded(ASN1Encoding.DER); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
private DERSet getAuthenticatedAttributeSet(byte secondDigest[], Calendar signingTime, byte[] ocsp, Collection<byte[]> crlBytes, CryptoStandard sigtype) { try { ASN1EncodableVector attribute = new ASN1EncodableVector(); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE)); v.add(new DERSet(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA))); attribute.add(new DERSequence(v)); v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_SIGNING_TIME)); v.add(new DERSet(new DERUTCTime(signingTime.getTime()))); attribute.add(new DERSequence(v)); v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST)); v.add(new DERSet(new DEROctetString(secondDigest))); attribute.add(new DERSequence(v)); boolean haveCrl = false; if (crlBytes != null) { for (byte[] bCrl : crlBytes) { if (bCrl != null) { haveCrl = true; break; } } } if (ocsp != null || haveCrl) { v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION)); ASN1EncodableVector revocationV = new ASN1EncodableVector(); if (haveCrl) { ASN1EncodableVector v2 = new ASN1EncodableVector(); for (byte[] bCrl : crlBytes) { if (bCrl == null) continue; ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(bCrl)); v2.add(t.readObject()); } revocationV.add(new DERTaggedObject(true, 0, new DERSequence(v2))); } if (ocsp != null) { DEROctetString doctet = new DEROctetString(ocsp); ASN1EncodableVector vo1 = new ASN1EncodableVector(); 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))); vo1.add(new DERSequence(v3)); revocationV.add(new DERTaggedObject(true, 1, new DERSequence(vo1))); } v.add(new DERSet(new DERSequence(revocationV))); attribute.add(new DERSequence(v)); } if (sigtype == CryptoStandard.CADES) { v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)); ASN1EncodableVector aaV2 = new ASN1EncodableVector(); AlgorithmIdentifier algoId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(digestAlgorithmOid), null); aaV2.add(algoId); MessageDigest md = interfaceDigest.getMessageDigest(getHashAlgorithm()); byte[] dig = md.digest(signCert.getEncoded()); aaV2.add(new DEROctetString(dig)); v.add(new DERSet(new DERSequence(new DERSequence(new DERSequence(aaV2))))); attribute.add(new DERSequence(v)); } return new DERSet(attribute); } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
public static KeyStore loadCacertsKeyStore(String provider) { File file = new File(System.getProperty("java.home"), "lib"); file = new File(file, "security"); file = new File(file, "cacerts"); FileInputStream fin = null; try { fin = new FileInputStream(file); KeyStore k; if (provider == null) k = KeyStore.getInstance("JKS"); else k = KeyStore.getInstance("JKS", provider); k.load(fin, null); return k; } catch (Exception e) { throw new ExceptionConverter(e); } finally { try{if (fin != null) {fin.close();}}catch(Exception ex){} } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Font.java
public BaseFont getCalculatedBaseFont(final boolean specialEncoding) { if (baseFont != null) return baseFont; int style = this.style; if (style == UNDEFINED) { style = NORMAL; } String fontName = BaseFont.HELVETICA; String encoding = BaseFont.WINANSI; BaseFont cfont = null; switch (family) { case COURIER: switch (style & BOLDITALIC) { case BOLD: fontName = BaseFont.COURIER_BOLD; break; case ITALIC: fontName = BaseFont.COURIER_OBLIQUE; break; case BOLDITALIC: fontName = BaseFont.COURIER_BOLDOBLIQUE; break; default: // case NORMAL: fontName = BaseFont.COURIER; break; } break; case TIMES_ROMAN: switch (style & BOLDITALIC) { case BOLD: fontName = BaseFont.TIMES_BOLD; break; case ITALIC: fontName = BaseFont.TIMES_ITALIC; break; case BOLDITALIC: fontName = BaseFont.TIMES_BOLDITALIC; break; default: case NORMAL: fontName = BaseFont.TIMES_ROMAN; break; } break; case SYMBOL: fontName = BaseFont.SYMBOL; if (specialEncoding) encoding = BaseFont.SYMBOL; break; case ZAPFDINGBATS: fontName = BaseFont.ZAPFDINGBATS; if (specialEncoding) encoding = BaseFont.ZAPFDINGBATS; break; default: case HELVETICA: switch (style & BOLDITALIC) { case BOLD: fontName = BaseFont.HELVETICA_BOLD; break; case ITALIC: fontName = BaseFont.HELVETICA_OBLIQUE; break; case BOLDITALIC: fontName = BaseFont.HELVETICA_BOLDOBLIQUE; break; default: case NORMAL: fontName = BaseFont.HELVETICA; break; } break; } try { cfont = BaseFont.createFont(fontName, encoding, false); } catch (Exception ee) { throw new ExceptionConverter(ee); } return cfont; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addHeader(String name, String content) { try { return add(new Header(name, content)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addTitle(String title) { try { return add(new Meta(Element.TITLE, title)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addSubject(String subject) { try { return add(new Meta(Element.SUBJECT, subject)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addKeywords(String keywords) { try { return add(new Meta(Element.KEYWORDS, keywords)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addAuthor(String author) { try { return add(new Meta(Element.AUTHOR, author)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addCreator(String creator) { try { return add(new Meta(Element.CREATOR, creator)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addProducer() { try { return add(new Meta(Element.PRODUCER, Version.getInstance().getVersion())); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addLanguage(String language) { try { return add(new Meta(Element.LANGUAGE, language)); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
public boolean addCreationDate() { try { /* bugfix by 'taqua' (Thomas) */ final SimpleDateFormat sdf = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy"); return add(new Meta(Element.CREATIONDATE, sdf.format(new Date()))); } catch (DocumentException de) { throw new ExceptionConverter(de); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void startElement(final String tag, final Map<String, String> attrs) { HTMLTagProcessor htmlTag = tags.get(tag); if (htmlTag == null) { return; } // apply the styles to attrs style.applyStyle(tag, attrs); // deal with the style attribute StyleSheet.resolveStyleAttribute(attrs, chain); // process the tag try { htmlTag.startElement(this, tag, attrs); } catch (DocumentException e) { throw new ExceptionConverter(e); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void endElement(final String tag) { HTMLTagProcessor htmlTag = tags.get(tag); if (htmlTag == null) { return; } // process the tag try { htmlTag.endElement(this, tag); } catch (DocumentException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
public void endDocument() { try { // flush the stack for (int k = 0; k < stack.size(); ++k) document.add(stack.elementAt(k)); // add current paragraph if (currentParagraph != null) document.add(currentParagraph); currentParagraph = null; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
public void close() { open = false; try { os.flush(); if (closeStream) os.close(); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
public void flush() { try { os.flush(); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
public Font getFont(String fontname, final String encoding, final boolean embedded, final float size, int style, final BaseColor color, final boolean cached) { if (fontname == null) return new Font(FontFamily.UNDEFINED, size, style, color); String lowercasefontname = fontname.toLowerCase(); ArrayList<String> tmp = fontFamilies.get(lowercasefontname); if (tmp != null) { // some bugs were fixed here by Daniel Marczisovszky int s = style == Font.UNDEFINED ? Font.NORMAL : style; int fs = Font.NORMAL; boolean found = false; for (String string : tmp) { String f = string; String lcf = f.toLowerCase(); fs = Font.NORMAL; if (lcf.toLowerCase().indexOf("bold") != -1) fs |= Font.BOLD; if (lcf.toLowerCase().indexOf("italic") != -1 || lcf.toLowerCase().indexOf("oblique") != -1) fs |= Font.ITALIC; if ((s & Font.BOLDITALIC) == fs) { fontname = f; found = true; break; } } if (style != Font.UNDEFINED && found) { style &= ~fs; } } BaseFont basefont = null; try { try { // the font is a type 1 font or CJK font basefont = BaseFont.createFont(fontname, encoding, embedded, cached, null, null, true); } catch(DocumentException de) { } if (basefont == null) { // the font is a true type font or an unknown font fontname = trueTypeFonts.get(fontname.toLowerCase()); // the font is not registered as truetype font if (fontname == null) return new Font(FontFamily.UNDEFINED, size, style, color); // the font is registered as truetype font basefont = BaseFont.createFont(fontname, encoding, embedded, cached, null, null); } } catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); } catch(IOException ioe) { // the font is registered as a true type font, but the path was wrong return new Font(FontFamily.UNDEFINED, size, style, color); } catch(NullPointerException npe) { // null was entered as fontname and/or encoding return new Font(FontFamily.UNDEFINED, size, style, color); } return new Font(basefont, size, style, color); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
public void register(final String path, final String alias) { try { if (path.toLowerCase().endsWith(".ttf") || path.toLowerCase().endsWith(".otf") || path.toLowerCase().indexOf(".ttc,") > 0) { Object allNames[] = BaseFont.getAllFontNames(path, BaseFont.WINANSI, null); trueTypeFonts.put(((String)allNames[0]).toLowerCase(), path); if (alias != null) { trueTypeFonts.put(alias.toLowerCase(), path); } // register all the font names with all the locales String[][] names = (String[][])allNames[2]; //full name for (String[] name : names) { trueTypeFonts.put(name[3].toLowerCase(), path); } String fullName = null; String familyName = null; names = (String[][])allNames[1]; //family name for (int k = 0; k < TTFamilyOrder.length; k += 3) { for (String[] name : names) { if (TTFamilyOrder[k].equals(name[0]) && TTFamilyOrder[k + 1].equals(name[1]) && TTFamilyOrder[k + 2].equals(name[2])) { familyName = name[3].toLowerCase(); k = TTFamilyOrder.length; break; } } } if (familyName != null) { String lastName = ""; names = (String[][])allNames[2]; //full name for (String[] name : names) { for (int k = 0; k < TTFamilyOrder.length; k += 3) { if (TTFamilyOrder[k].equals(name[0]) && TTFamilyOrder[k + 1].equals(name[1]) && TTFamilyOrder[k + 2].equals(name[2])) { fullName = name[3]; if (fullName.equals(lastName)) continue; lastName = fullName; registerFamily(familyName, fullName, null); break; } } } } } else if (path.toLowerCase().endsWith(".ttc")) { if (alias != null) LOGGER.error("You can't define an alias for a true type collection."); String[] names = BaseFont.enumerateTTCNames(path); for (int i = 0; i < names.length; i++) { register(path + "," + i); } } else if (path.toLowerCase().endsWith(".afm") || path.toLowerCase().endsWith(".pfm")) { BaseFont bf = BaseFont.createFont(path, BaseFont.CP1252, false); String fullName = bf.getFullFontName()[0][3].toLowerCase(); String familyName = bf.getFamilyFontName()[0][3].toLowerCase(); String psName = bf.getPostscriptFontName().toLowerCase(); registerFamily(familyName, fullName, null); trueTypeFonts.put(psName, path); trueTypeFonts.put(fullName, path); } if (LOGGER.isLogging(Level.TRACE)) { LOGGER.trace(String.format("Registered %s", path)); } } catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
160
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/DefaultFontMapper.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/xmp/XmpReader.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (BadElementException be) { throw new ExceptionConverter(be); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/GifImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2Image.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch(DataFormatException dfe) { throw new ExceptionConverter(dfe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEAN.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/OutputStreamEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/SimplePatternParser.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfICCBased.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPRow.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAcroForm.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPattern.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPCell.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/events/FieldPositioningEvents.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LZWDecoder.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFunction.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfAnnotationsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (SAXException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CFFFont.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch(Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (DocumentException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeQRCode.java
catch (WriterException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (IOException e1) { throw new ExceptionConverter(e1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSmartCopy.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeCodabar.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapToUnicode.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/TrueTypeFontSubSet.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RadioCheckField.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CJKFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFont.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeInter25.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (Exception f) { throw new ExceptionConverter(f); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPageLabels.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/RandomAccessFileOrArray.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOffline.java
catch (Exception ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/KeyStoreUtil.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Font.java
catch (Exception ee) { throw new ExceptionConverter(ee); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Document.java
catch (DocumentException de) { throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (DocumentException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (Exception e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(DocumentException de) { // this shouldn't happen throw new ExceptionConverter(de); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
0 0 0 0
checked (Domain) FontReadingException
public class FontReadingException extends Exception {
    
    private static final long serialVersionUID = 1L;

    public FontReadingException(String message) {
        super(message);
    }
    
    public FontReadingException(String message, Exception e) {
        super(message, e);
    }

}
3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
public Language getSupportedLanguage() throws FontReadingException { Language[] allLangs = Language.values(); for (String supportedLang : supportedLanguages) { for (Language lang : allLangs) { if (lang.isSupported(supportedLang)) { return lang; } } } throw new FontReadingException("Unsupported languages " + supportedLanguages); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
protected final void startReadingTable() throws FontReadingException { try { TableHeader header = readHeader(); // read the Script tables readScriptListTable(tableLocation + header.scriptListOffset); // read Feature table readFeatureListTable(tableLocation + header.featureListOffset); // read LookUpList table readLookupListTable(tableLocation + header.lookupListOffset); } catch (IOException e) { throw new FontReadingException("Error reading font file", e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
private String getTextFromGlyph(int glyphId, Map<Integer, Character> glyphToCharacterMap) throws FontReadingException { StringBuilder chars = new StringBuilder(1); Character c = glyphToCharacterMap.get(glyphId); if (c == null) { // it means this represents a compound glyph List<Integer> constituentGlyphs = rawLigatureSubstitutionMap.get(glyphId); if (constituentGlyphs == null || constituentGlyphs.isEmpty()) { throw new FontReadingException("No corresponding character or simple glyphs found for GlyphID=" + glyphId); } for (int constituentGlyphId : constituentGlyphs) { chars.append(getTextFromGlyph(constituentGlyphId, glyphToCharacterMap)); } } else { chars.append(c.charValue()); } return chars.toString(); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
catch (IOException e) { throw new FontReadingException("Error reading font file", e); }
6
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
public Language getSupportedLanguage() throws FontReadingException { Language[] allLangs = Language.values(); for (String supportedLang : supportedLanguages) { for (Language lang : allLangs) { if (lang.isSupported(supportedLang)) { return lang; } } } throw new FontReadingException("Unsupported languages " + supportedLanguages); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
protected final void startReadingTable() throws FontReadingException { try { TableHeader header = readHeader(); // read the Script tables readScriptListTable(tableLocation + header.scriptListOffset); // read Feature table readFeatureListTable(tableLocation + header.featureListOffset); // read LookUpList table readLookupListTable(tableLocation + header.lookupListOffset); } catch (IOException e) { throw new FontReadingException("Error reading font file", e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
public void read() throws FontReadingException { rawLigatureSubstitutionMap = new LinkedHashMap<Integer, List<Integer>>(); startReadingTable(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
public Map<String, Glyph> getGlyphSubstitutionMap() throws FontReadingException { Map<String, Glyph> glyphSubstitutionMap = new LinkedHashMap<String, Glyph>(); for (Integer glyphIdToReplace : rawLigatureSubstitutionMap.keySet()) { List<Integer> constituentGlyphs = rawLigatureSubstitutionMap.get(glyphIdToReplace); StringBuilder chars = new StringBuilder(constituentGlyphs.size()); for (Integer constituentGlyphId : constituentGlyphs) { chars.append(getTextFromGlyph(constituentGlyphId, glyphToCharacterMap)); } Glyph glyph = new Glyph(glyphIdToReplace, glyphWidthsByIndex[glyphIdToReplace], chars.toString()); glyphSubstitutionMap.put(glyph.chars, glyph); } return Collections.unmodifiableMap(glyphSubstitutionMap); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphSubstitutionTableReader.java
private String getTextFromGlyph(int glyphId, Map<Integer, Character> glyphToCharacterMap) throws FontReadingException { StringBuilder chars = new StringBuilder(1); Character c = glyphToCharacterMap.get(glyphId); if (c == null) { // it means this represents a compound glyph List<Integer> constituentGlyphs = rawLigatureSubstitutionMap.get(glyphId); if (constituentGlyphs == null || constituentGlyphs.isEmpty()) { throw new FontReadingException("No corresponding character or simple glyphs found for GlyphID=" + glyphId); } for (int constituentGlyphId : constituentGlyphs) { chars.append(getTextFromGlyph(constituentGlyphId, glyphToCharacterMap)); } } else { chars.append(c.charValue()); } return chars.toString(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/GlyphPositioningTableReader.java
public void read() throws FontReadingException { startReadingTable(); }
0 0 0
unknown (Lib) GeneralSecurityException 3
            
// 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/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<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; }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvTimestamp.java
catch(Exception e) { throw new GeneralSecurityException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch (OCSPException e) { throw new GeneralSecurityException(e); }
34
            
// 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/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/PrivateKeySignature.java
public byte[] sign(byte[] b) throws GeneralSecurityException { String signMode = hashAlgorithm + "with" + encryptionAlgorithm; Signature sig; if (provider == null) sig = Signature.getInstance(signMode); else sig = Signature.getInstance(signMode, provider); sig.initSign(pk); sig.update(b); return sig.sign(); }
// 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 MessageDigest getMessageDigest() throws GeneralSecurityException { return new BouncyCastleDigest().getMessageDigest(digestAlgorithm); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/ExternalBlankSignatureContainer.java
public byte[] sign(InputStream data) throws GeneralSecurityException { return new byte[0]; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
protected PdfPKCS7 coversWholeDocument() throws GeneralSecurityException { PdfPKCS7 pkcs7 = fields.verifySignature(signatureName); if (fields.signatureCoversWholeDocument(signatureName)) { LOGGER.info("The timestamp covers whole document."); } else { throw new VerificationException(null, "Signature doesn't cover whole document."); } if (pkcs7.verify()) { LOGGER.info("The signed document has not been modified."); return pkcs7; } else { throw new VerificationException(null, "The document was altered after the final signature was applied."); } }
// 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 void verifyChain(Certificate[] chain) throws GeneralSecurityException { // Loop over the certificates in the chain for (int i = 0; i < chain.length; i++) { X509Certificate cert = (X509Certificate) chain[i]; // check if the certificate was/is valid cert.checkValidity(signDate); // check if the previous certificate was issued by this certificate if (i > 0) chain[i-1].verify(chain[i].getPublicKey()); } LOGGER.info("All certificates are valid on " + signDate.toString()); }
// 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/CRLVerifier.java
public boolean verify(X509CRL crl, X509Certificate signCert, X509Certificate issuerCert, Date signDate) throws GeneralSecurityException { if (crl == null || signDate == null) return false; // We only check CRLs valid on the signing date for which the issuer matches if (crl.getIssuerX500Principal().equals(signCert.getIssuerX500Principal()) && signDate.after(crl.getThisUpdate()) && signDate.before(crl.getNextUpdate())) { // the signing certificate may not be revoked if (isSignatureValid(crl, issuerCert) && crl.isRevoked(signCert)) { throw new VerificationException(signCert, "The certificate has been revoked."); } return true; } return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
public boolean verifyTimestampImprint() throws GeneralSecurityException { if (timeStampToken == null) return false; TimeStampTokenInfo info = timeStampToken.getTimeStampInfo(); MessageImprint imprint = info.toASN1Structure().getMessageImprint(); String algOID = info.getMessageImprintAlgOID().getId(); byte[] md = new BouncyCastleDigest().getMessageDigest(DigestAlgorithms.getDigest(algOID)).digest(digest); byte[] imphashed = imprint.getHashedMessage(); boolean res = Arrays.equals(md, imphashed); return res; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/BouncyCastleDigest.java
public MessageDigest getMessageDigest(String hashAlgorithm) throws GeneralSecurityException { String oid = DigestAlgorithms.getAllowedDigests(hashAlgorithm); if (oid == null) throw new NoSuchAlgorithmException(hashAlgorithm); if (oid.equals("1.2.840.113549.2.2")) { //MD2 return new MD2.Digest(); } else if (oid.equals("1.2.840.113549.2.5")) { //MD5 return new MD5.Digest(); } else if (oid.equals("1.3.14.3.2.26")) { //SHA1 return new SHA1.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.4")) { //SHA224 return new SHA224.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.1")) { //SHA256 return new SHA256.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.2")) { //SHA384 return new SHA384.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.3")) { //SHA512 return new SHA512.Digest(); } else if (oid.equals("1.3.36.3.2.2")) { //RIPEMD128 return new RIPEMD128.Digest(); } else if (oid.equals("1.3.36.3.2.1")) { //RIPEMD160 return new RIPEMD160.Digest(); } else if (oid.equals("1.3.36.3.2.3")) { //RIPEMD256 return new RIPEMD256.Digest(); } else if (oid.equals("1.2.643.2.2.9")) { //GOST3411 return new GOST3411.Digest(); } throw new NoSuchAlgorithmException(hashAlgorithm); //shouldn't get here }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/ProviderDigest.java
public MessageDigest getMessageDigest(String hashAlgorithm) throws GeneralSecurityException{ return DigestAlgorithms.getMessageDigest(hashAlgorithm, provider); }
// 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/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(); }
11
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
catch (GeneralSecurityException e) { EncodedRecipients = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/RootStoreVerifier.java
catch (GeneralSecurityException e) { continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/RootStoreVerifier.java
catch (GeneralSecurityException e) { return super.verify(signCert, issuerCert, signDate); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch(GeneralSecurityException e) { throw new VerificationException(signCert, "Couldn't verify with CRL or OCSP or trusted anchor"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
catch(GeneralSecurityException e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
catch (GeneralSecurityException e) { LOGGER.warn("CRL not issued by the same authority as the certificate that is being checked"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
catch (GeneralSecurityException e) { continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
catch (GeneralSecurityException e) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch(GeneralSecurityException e) { if (super.verify(responderCert, issuerCert, null).size() == 0) throw new VerificationException(responderCert, "Responder certificate couldn't be verified"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch (GeneralSecurityException e) { continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch (GeneralSecurityException e) { return false; }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch(GeneralSecurityException e) { throw new VerificationException(signCert, "Couldn't verify with CRL or OCSP or trusted anchor"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch(GeneralSecurityException e) { if (super.verify(responderCert, issuerCert, null).size() == 0) throw new VerificationException(responderCert, "Responder certificate couldn't be verified"); }
0
checked (Domain) HyphenationException
public class HyphenationException extends Exception {

    private static final long serialVersionUID = 4721513606846982325L;

	public HyphenationException(String msg) {
        super(msg);
    }

}
0 0 0 0 0 0
checked (Lib) IOException 55
            
// 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 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/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/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 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 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 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/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/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 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 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/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/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/TiffImage.java
protected static Image getTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s) { try { int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); int predictor = 1; TIFFLZWDecoder lzwDecoder = null; switch (compression) { case TIFFConstants.COMPRESSION_NONE: case TIFFConstants.COMPRESSION_LZW: case TIFFConstants.COMPRESSION_PACKBITS: case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: case TIFFConstants.COMPRESSION_OJPEG: case TIFFConstants.COMPRESSION_JPEG: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.compression.1.is.not.supported", compression)); } int photometric = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); switch (photometric) { case TIFFConstants.PHOTOMETRIC_MINISWHITE: case TIFFConstants.PHOTOMETRIC_MINISBLACK: case TIFFConstants.PHOTOMETRIC_RGB: case TIFFConstants.PHOTOMETRIC_SEPARATED: case TIFFConstants.PHOTOMETRIC_PALETTE: break; default: if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.photometric.1.is.not.supported", photometric)); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } if (dir.isTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) && dir.getFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("planar.images.are.not.supported")); int extraSamples = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES)) extraSamples = 1; int samplePerPixel = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4 samplePerPixel = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL); int bitsPerSample = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE)) bitsPerSample = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE); switch (bitsPerSample) { case 1: case 2: case 4: case 8: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample)); } Image img = null; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); int fillOrder = 1; boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE) { TIFFField predictorField = dir.getField(TIFFConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.getAsInt(0); if (predictor != 1 && predictor != 2) { throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.value.for.predictor.in.tiff.file")); } if (predictor == 2 && bitsPerSample != 8) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample)); } } } if (compression == TIFFConstants.COMPRESSION_LZW) { lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel); } int rowsLeft = h; ByteArrayOutputStream stream = null; ByteArrayOutputStream mstream = null; DeflaterOutputStream zip = null; DeflaterOutputStream mzip = null; if (extraSamples > 0) { mstream = new ByteArrayOutputStream(); mzip = new DeflaterOutputStream(mstream); } CCITTG4Encoder g4 = null; if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4 = new CCITTG4Encoder(w); } else { stream = new ByteArrayOutputStream(); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) zip = new DeflaterOutputStream(stream); } if (compression == TIFFConstants.COMPRESSION_OJPEG) { // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and // is often missing if ((!dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET))) { throw new IOException(MessageLocalization.getComposedMessage("missing.tag.s.for.ojpeg.compression")); } int jpegOffset = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET); int jpegLength = (int)s.length() - jpegOffset; if (dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT)) { jpegLength = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0]; } byte[] jpeg = new byte[Math.min(jpegLength, (int)s.length() - jpegOffset)]; int posFilePointer = (int)s.getFilePointer(); posFilePointer += jpegOffset; s.seek(posFilePointer); s.readFully(jpeg); img = new Jpeg(jpeg); } else if (compression == TIFFConstants.COMPRESSION_JPEG) { if (size.length > 1) throw new IOException(MessageLocalization.getComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.length)); byte[] jpeg = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(jpeg); // if quantization and/or Huffman tables are stored separately in the tiff, // we need to add them to the jpeg data TIFFField jpegtables = dir.getField(TIFFConstants.TIFFTAG_JPEGTABLES); if (jpegtables != null) { byte[] temp = jpegtables.getAsBytes(); int tableoffset = 0; int tablelength = temp.length; // remove FFD8 from start if (temp[0] == (byte) 0xFF && temp[1] == (byte) 0xD8) { tableoffset = 2; tablelength -= 2; } // remove FFD9 from end if (temp[temp.length-2] == (byte) 0xFF && temp[temp.length-1] == (byte) 0xD9) tablelength -= 2; byte[] tables = new byte[tablelength]; System.arraycopy(temp, tableoffset, tables, 0, tablelength); // TODO insert after JFIF header, instead of at the start byte[] jpegwithtables = new byte[jpeg.length + tables.length]; System.arraycopy(jpeg, 0, jpegwithtables, 0, 2); System.arraycopy(tables, 0, jpegwithtables, 2, tables.length); System.arraycopy(jpeg, 2, jpegwithtables, tables.length+2, jpeg.length-2); jpeg = jpegwithtables; } img = new Jpeg(jpeg); } else { for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); byte outBuf[] = null; if (compression != TIFFConstants.COMPRESSION_NONE) outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height]; if (reverse) TIFFFaxDecoder.reverseBits(im); switch (compression) { case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: inflate(im, outBuf); applyPredictor(outBuf, predictor, w, height, samplePerPixel); break; case TIFFConstants.COMPRESSION_NONE: outBuf = im; break; case TIFFConstants.COMPRESSION_PACKBITS: decodePackbits(im, outBuf); break; case TIFFConstants.COMPRESSION_LZW: lzwDecoder.decode(im, outBuf, height); break; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4.fax4Encode(outBuf, height); } else { if (extraSamples > 0) ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height); else zip.write(outBuf); } rowsLeft -= rowsStrip; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { img = Image.getInstance(w, h, false, Image.CCITTG4, photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.close()); } else { zip.close(); img = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.toByteArray()); img.setDeflated(true); } } img.setDpi(dpiX, dpiY); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) { if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (samplePerPixel - extraSamples == icc_prof.getNumComponents()) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } if (dir.isTagPresent(TIFFConstants.TIFFTAG_COLORMAP)) { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_COLORMAP); char rgb[] = fd.getAsChars(); byte palette[] = new byte[rgb.length]; int gColor = rgb.length / 3; int bColor = gColor * 2; for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)(rgb[k] >>> 8); palette[k * 3 + 1] = (byte)(rgb[k + gColor] >>> 8); palette[k * 3 + 2] = (byte)(rgb[k + bColor] >>> 8); } // Colormap components are supposed to go from 0 to 655535 but, // as usually, some tiff producers just put values from 0 to 255. // Let's check for these broken tiffs. boolean colormapBroken = true; for (int k = 0; k < palette.length; ++k) { if (palette[k] != 0) { colormapBroken = false; break; } } if (colormapBroken) { for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)rgb[k]; palette[k * 3 + 1] = (byte)rgb[k + gColor]; palette[k * 3 + 2] = (byte)rgb[k + bColor]; } } PdfArray indexed = new PdfArray(); indexed.add(PdfName.INDEXED); indexed.add(PdfName.DEVICERGB); indexed.add(new PdfNumber(gColor - 1)); indexed.add(new PdfString(palette)); PdfDictionary additional = new PdfDictionary(); additional.put(PdfName.COLORSPACE, indexed); img.setAdditional(additional); } img.setOriginalType(Image.ORIGINAL_TIFF); } if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE) img.setInverted(true); if (rotation != 0) img.setInitialRotation(rotation); if (extraSamples > 0) { mzip.close(); Image mimg = Image.getInstance(w, h, 1, bitsPerSample, mstream.toByteArray()); mimg.makeMask(); mimg.setDeflated(true); img.setImageMask(mimg); } return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// 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/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/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/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/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/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/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/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/fonts/cmaps/CMapToUnicode.java
Override void addChar(PdfString mark, PdfObject code) { try { byte[] src = mark.getBytes(); String dest = createStringFromBytes(code.getBytes()); if (src.length == 1) { singleByteMappings.put(Integer.valueOf(src[0] & 0xff), dest); } else if (src.length == 2) { int intSrc = src[0] & 0xFF; intSrc <<= 8; intSrc |= src[1] & 0xFF; doubleByteMappings.put(Integer.valueOf(intSrc), dest); } else { throw new IOException(MessageLocalization.getComposedMessage("mapping.code.should.be.1.or.two.bytes.and.not.1", src.length)); } } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// 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/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/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/OcspClientBouncyCastle.java
public byte[] getEncoded(X509Certificate checkCert, X509Certificate rootCert, String url) { try { BasicOCSPResp basicResponse = getBasicOCSPResp(checkCert, rootCert, url); if (basicResponse != null) { SingleResp[] responses = basicResponse.getResponses(); if (responses.length == 1) { SingleResp resp = responses[0]; Object status = resp.getCertStatus(); if (status == CertificateStatus.GOOD) { return basicResponse.getEncoded(); } else if (status instanceof org.bouncycastle.ocsp.RevokedStatus) { throw new IOException(MessageLocalization.getComposedMessage("ocsp.status.is.revoked")); } else { throw new IOException(MessageLocalization.getComposedMessage("ocsp.status.is.unknown")); } } } } catch (Exception ex) { if (LOGGER.isLogging(Level.ERROR)) LOGGER.error(ex.getMessage()); } return null; }
// 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/CrlClientOnline.java
public Collection<byte[]> getEncoded(X509Certificate checkCert, String url) { if (checkCert == null) return null; List<URL> urllist = new ArrayList<URL>(urls); if (urllist.size() == 0) { LOGGER.info("Looking for CRL for certificate " + checkCert.getSubjectDN()); try { if (url == null) url = CertificateUtil.getCRLURL(checkCert); if (url == null) throw new NullPointerException(); urllist.add(new URL(url)); LOGGER.info("Found CRL url: " + url); } catch (Exception e) { LOGGER.info("Skipped CRL url: " + e.getMessage()); } } ArrayList<byte[]> ar = new ArrayList<byte[]>(); for (URL urlt : urllist) { try { LOGGER.info("Checking CRL: " + urlt); HttpURLConnection con = (HttpURLConnection)urlt.openConnection(); if (con.getResponseCode() / 100 != 2) { throw new IOException(MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode())); } //Get Response InputStream inp = (InputStream) con.getContent(); byte[] buf = new byte[1024]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while (true) { int n = inp.read(buf, 0, buf.length); if (n <= 0) break; bout.write(buf, 0, n); } inp.close(); ar.add(bout.toByteArray()); LOGGER.info("Added CRL found at: " + urlt); } catch (Exception e) { LOGGER.info("Skipped CRL: " + e.getMessage() + " for " + urlt); } } return ar; }
// 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(); }
3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/TSAClientBouncyCastle.java
catch (IOException ioe) { throw new IOException(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL)); }
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. &lt;, &#187;, 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; }
78
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
catch(IOException ioe){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
catch(IOException ioe){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
catch(IOException ioe){}
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
catch (IOException e){ if (exceptionIsMapFailureException(e)) throw new MapFailedException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/JBIG2SegmentReader.java
catch (IOException e) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { e.printStackTrace(); return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { e.printStackTrace(); return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { // Just return originally-decoded bytes }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { e.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { success = false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { success = false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { System.err.println( "Error decoding from file " + filename ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { System.err.println( "Error encoding from file " + filename ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException ex ) { ex.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException ex ) { ex.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { // Only a problem if we got no data at all. if( i == 0 ) throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
catch (IOException e) { EncodedRecipients = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/SimplePatternParser.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (IOException ioe) { ioe.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (IOException e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfLister.java
catch (IOException e) { System.err.println("I/O exception: " + e); // } catch (java.util.zip.DataFormatException e) { // System.err.println("Data Format Exception: " + e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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/PdfStamperImp.java
catch (IOException ioe) { ioe.printStackTrace(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch(IOException e) { xmp = new PdfStream(altMetadata); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch (IOException ioe) { // do nothing }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LZWDecoder.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFunction.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfAnnotationsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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
catch (IOException e) { xref = null; throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (IOException ioe) { // Never happens }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (IOException ioe) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
catch (IOException ioe) { }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (IOException e1) { throw new ExceptionConverter(e1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
catch (IOException e) { throw new FontReadingException("Error reading font file", e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
catch(IOException ioe) { throw new BadPdfFormatException(ioe.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPageLabels.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/CMapAwareDocumentFont.java
catch (IOException e) { toUnicodeCmap = null; uni2cid = null; // technically, we should log this or provide some sort of feedback... but sometimes the cmap will be junk, but it's still possible to get text, so we don't want to throw an exception //throw new IllegalStateException("Unable to process ToUnicode map - " + e.getMessage(), e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateUtil.java
catch (IOException e) { obj = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateUtil.java
catch (IOException e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateUtil.java
catch (IOException e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/TSAClientBouncyCastle.java
catch (IOException ioe) { throw new IOException(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CRLVerifier.java
catch(IOException e) { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (IOException e) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (IOException e){ close(); throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(IOException ioe) { // the font is registered as a true type font, but the path was wrong return new Font(FontFamily.UNDEFINED, size, style, color); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
48
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
catch (IOException e){ if (exceptionIsMapFailureException(e)) throw new MapFailedException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.IOException e ) { // Only a problem if we got no data at all. if( i == 0 ) throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/hyphenation/SimplePatternParser.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
catch (IOException e) { // this really shouldn't ever happen - the source view we use is based on a Safe view, which is a no-op anyway throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
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/PdfStamperImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFieldsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LZWDecoder.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfFunction.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfAnnotationsImp.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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
catch (IOException e) { xref = null; throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PRStream.java
catch (IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/PdfContentStreamProcessor.java
catch (IOException e1) { throw new ExceptionConverter(e1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/otf/OpenTypeFontTableReader.java
catch (IOException e) { throw new FontReadingException("Error reading font file", e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImage.java
catch(IOException ioe) { throw new BadPdfFormatException(ioe.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
catch (IOException ex) { throw new ExceptionConverter(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPageLabels.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/TSAClientBouncyCastle.java
catch (IOException ioe) { throw new IOException(MessageLocalization.getComposedMessage("failed.to.get.tsa.response.from.1", tsaURL)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CertificateInfo.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (IOException e) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (IOException e){ close(); throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/simpleparser/HTMLWorker.java
catch (IOException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/DocWriter.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(IOException ioe) { throw new ExceptionConverter(ioe); }
39
runtime (Lib) IllegalArgumentException 168
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/misc/RenderingHints.java
public Object put(Object key, Object value) { if (!((Key)key).isCompatibleValue(value)) { throw new IllegalArgumentException(); } return map.put(key, value); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
public void setWindingRule(int rule) { if (rule != WIND_EVEN_ODD && rule != WIND_NON_ZERO) { // awt.209=Invalid winding rule value throw new java.lang.IllegalArgumentException(Messages.getString("awt.209")); //$NON-NLS-1$ } this.rule = rule; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
private boolean drawImage(Image img, Image mask, AffineTransform xform, Color bgColor, ImageObserver obs) { if (xform==null) xform = new AffineTransform(); else xform = new AffineTransform(xform); xform.translate(0, img.getHeight(obs)); xform.scale(img.getWidth(obs), img.getHeight(obs)); AffineTransform inverse = this.normalizeMatrix(); AffineTransform flipper = AffineTransform.getScaleInstance(1,-1); inverse.concatenate(xform); inverse.concatenate(flipper); double[] mx = new double[6]; inverse.getMatrix(mx); if (currentFillGState != 255) { PdfGState gs = fillGState[255]; if (gs == null) { gs = new PdfGState(); gs.setFillOpacity(1); fillGState[255] = gs; } cb.setGState(gs); } try { com.itextpdf.text.Image image = null; if(!convertImagesToJPEG){ image = com.itextpdf.text.Image.getInstance(img, bgColor); } else{ BufferedImage scaled = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g3 = scaled.createGraphics(); g3.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null); g3.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageWriteParam iwparam = new JPEGImageWriteParam(Locale.getDefault()); iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwparam.setCompressionQuality(jpegQuality);//Set here your compression rate ImageWriter iw = ImageIO.getImageWritersByFormatName("jpg").next(); ImageOutputStream ios = ImageIO.createImageOutputStream(baos); iw.setOutput(ios); iw.write(null, new IIOImage(scaled, null, null), iwparam); iw.dispose(); ios.close(); scaled.flush(); scaled = null; image = com.itextpdf.text.Image.getInstance(baos.toByteArray()); } if (mask!=null) { com.itextpdf.text.Image msk = com.itextpdf.text.Image.getInstance(mask, null, true); msk.makeMask(); msk.setInverted(true); image.setImageMask(msk); } cb.addImage(image, (float)mx[0], (float)mx[1], (float)mx[2], (float)mx[3], (float)mx[4], (float)mx[5]); Object url = getRenderingHint(HyperLinkKey.KEY_INSTANCE); if (url != null && !url.equals(HyperLinkKey.VALUE_HYPERLINKKEY_OFF)) { PdfAction action = new PdfAction(url.toString()); cb.setAction(action, (float)mx[4], (float)mx[5], (float)(mx[0]+mx[4]), (float)(mx[3]+mx[5])); } } catch (Exception ex) { throw new IllegalArgumentException(ex); } if (currentFillGState >= 0 && currentFillGState != 255) { PdfGState gs = fillGState[currentFillGState]; cb.setGState(gs); } return true; }
// 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/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/pdf/codec/JBIG2Image.java
public static Image getJbig2Image(RandomAccessFileOrArray ra, int page) { if (page < 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.page.number.must.be.gt.eq.1")); try { JBIG2SegmentReader sr = new JBIG2SegmentReader(ra); sr.read(); JBIG2SegmentReader.JBIG2Page p = sr.getPage(page); Image img = new ImgJBIG2(p.pageBitmapWidth, p.pageBitmapHeight, p.getData(true), sr.getGlobal(true)); return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// 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
public static Image getTiffImage(RandomAccessFileOrArray s, int page, boolean direct) { if (page < 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.page.number.must.be.gt.eq.1")); try { TIFFDirectory dir = new TIFFDirectory(s, page - 1); if (dir.isTagPresent(TIFFConstants.TIFFTAG_TILEWIDTH)) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("tiles.are.not.supported")); int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: case TIFFConstants.COMPRESSION_CCITTFAX3: case TIFFConstants.COMPRESSION_CCITTFAX4: break; default: return getTiffImageColor(dir, s); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } Image img = null; long tiffT4Options = 0; long tiffT6Options = 0; int fillOrder = 1; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; float XYRatio = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); if (resolutionUnit == TIFFConstants.RESUNIT_NONE) { if (dpiY != 0) XYRatio = (float)dpiX / (float)dpiY; dpiX = 0; dpiY = 0; } int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int params = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_PHOTOMETRIC)) { long photo = dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); if (photo == TIFFConstants.PHOTOMETRIC_MINISBLACK) params |= Image.CCITT_BLACKIS1; } int imagecomp = 0; switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: imagecomp = Image.CCITTG3_1D; params |= Image.CCITT_ENCODEDBYTEALIGN | Image.CCITT_ENDOFBLOCK; break; case TIFFConstants.COMPRESSION_CCITTFAX3: imagecomp = Image.CCITTG3_1D; params |= Image.CCITT_ENDOFLINE | Image.CCITT_ENDOFBLOCK; TIFFField t4OptionsField = dir.getField(TIFFConstants.TIFFTAG_GROUP3OPTIONS); if (t4OptionsField != null) { tiffT4Options = t4OptionsField.getAsLong(0); if ((tiffT4Options & TIFFConstants.GROUP3OPT_2DENCODING) != 0) imagecomp = Image.CCITTG3_2D; if ((tiffT4Options & TIFFConstants.GROUP3OPT_FILLBITS) != 0) params |= Image.CCITT_ENCODEDBYTEALIGN; } break; case TIFFConstants.COMPRESSION_CCITTFAX4: imagecomp = Image.CCITTG4; TIFFField t6OptionsField = dir.getField(TIFFConstants.TIFFTAG_GROUP4OPTIONS); if (t6OptionsField != null) tiffT6Options = t6OptionsField.getAsLong(0); break; } if (direct && rowsStrip == h) { //single strip, direct byte im[] = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(im); img = Image.getInstance(w, h, false, imagecomp, params, im); img.setInverted(true); } else { int rowsLeft = h; CCITTG4Encoder g4 = new CCITTG4Encoder(w); for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); TIFFFaxDecoder decoder = new TIFFFaxDecoder(fillOrder, w, height); byte outBuf[] = new byte[(w + 7) / 8 * height]; switch (compression) { case TIFFConstants.COMPRESSION_CCITTRLEW: case TIFFConstants.COMPRESSION_CCITTRLE: decoder.decode1D(outBuf, im, 0, height); g4.fax4Encode(outBuf,height); break; case TIFFConstants.COMPRESSION_CCITTFAX3: try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e) { // let's flip the fill bits and try again... tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS; try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e2) { throw e; } } g4.fax4Encode(outBuf, height); break; case TIFFConstants.COMPRESSION_CCITTFAX4: decoder.decodeT6(outBuf, im, 0, height, tiffT6Options); g4.fax4Encode(outBuf, height); break; } rowsLeft -= rowsStrip; } byte g4pic[] = g4.close(); img = Image.getInstance(w, h, false, Image.CCITTG4, params & Image.CCITT_BLACKIS1, g4pic); } img.setDpi(dpiX, dpiY); img.setXYRatio(XYRatio); if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (icc_prof.getNumComponents() == 1) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } img.setOriginalType(Image.ORIGINAL_TIFF); if (rotation != 0) img.setInitialRotation(rotation); return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
protected static Image getTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s) { try { int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); int predictor = 1; TIFFLZWDecoder lzwDecoder = null; switch (compression) { case TIFFConstants.COMPRESSION_NONE: case TIFFConstants.COMPRESSION_LZW: case TIFFConstants.COMPRESSION_PACKBITS: case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: case TIFFConstants.COMPRESSION_OJPEG: case TIFFConstants.COMPRESSION_JPEG: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.compression.1.is.not.supported", compression)); } int photometric = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); switch (photometric) { case TIFFConstants.PHOTOMETRIC_MINISWHITE: case TIFFConstants.PHOTOMETRIC_MINISBLACK: case TIFFConstants.PHOTOMETRIC_RGB: case TIFFConstants.PHOTOMETRIC_SEPARATED: case TIFFConstants.PHOTOMETRIC_PALETTE: break; default: if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.photometric.1.is.not.supported", photometric)); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } if (dir.isTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) && dir.getFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("planar.images.are.not.supported")); int extraSamples = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES)) extraSamples = 1; int samplePerPixel = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4 samplePerPixel = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL); int bitsPerSample = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE)) bitsPerSample = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE); switch (bitsPerSample) { case 1: case 2: case 4: case 8: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample)); } Image img = null; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); int fillOrder = 1; boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE) { TIFFField predictorField = dir.getField(TIFFConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.getAsInt(0); if (predictor != 1 && predictor != 2) { throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.value.for.predictor.in.tiff.file")); } if (predictor == 2 && bitsPerSample != 8) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample)); } } } if (compression == TIFFConstants.COMPRESSION_LZW) { lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel); } int rowsLeft = h; ByteArrayOutputStream stream = null; ByteArrayOutputStream mstream = null; DeflaterOutputStream zip = null; DeflaterOutputStream mzip = null; if (extraSamples > 0) { mstream = new ByteArrayOutputStream(); mzip = new DeflaterOutputStream(mstream); } CCITTG4Encoder g4 = null; if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4 = new CCITTG4Encoder(w); } else { stream = new ByteArrayOutputStream(); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) zip = new DeflaterOutputStream(stream); } if (compression == TIFFConstants.COMPRESSION_OJPEG) { // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and // is often missing if ((!dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET))) { throw new IOException(MessageLocalization.getComposedMessage("missing.tag.s.for.ojpeg.compression")); } int jpegOffset = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET); int jpegLength = (int)s.length() - jpegOffset; if (dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT)) { jpegLength = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0]; } byte[] jpeg = new byte[Math.min(jpegLength, (int)s.length() - jpegOffset)]; int posFilePointer = (int)s.getFilePointer(); posFilePointer += jpegOffset; s.seek(posFilePointer); s.readFully(jpeg); img = new Jpeg(jpeg); } else if (compression == TIFFConstants.COMPRESSION_JPEG) { if (size.length > 1) throw new IOException(MessageLocalization.getComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.length)); byte[] jpeg = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(jpeg); // if quantization and/or Huffman tables are stored separately in the tiff, // we need to add them to the jpeg data TIFFField jpegtables = dir.getField(TIFFConstants.TIFFTAG_JPEGTABLES); if (jpegtables != null) { byte[] temp = jpegtables.getAsBytes(); int tableoffset = 0; int tablelength = temp.length; // remove FFD8 from start if (temp[0] == (byte) 0xFF && temp[1] == (byte) 0xD8) { tableoffset = 2; tablelength -= 2; } // remove FFD9 from end if (temp[temp.length-2] == (byte) 0xFF && temp[temp.length-1] == (byte) 0xD9) tablelength -= 2; byte[] tables = new byte[tablelength]; System.arraycopy(temp, tableoffset, tables, 0, tablelength); // TODO insert after JFIF header, instead of at the start byte[] jpegwithtables = new byte[jpeg.length + tables.length]; System.arraycopy(jpeg, 0, jpegwithtables, 0, 2); System.arraycopy(tables, 0, jpegwithtables, 2, tables.length); System.arraycopy(jpeg, 2, jpegwithtables, tables.length+2, jpeg.length-2); jpeg = jpegwithtables; } img = new Jpeg(jpeg); } else { for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); byte outBuf[] = null; if (compression != TIFFConstants.COMPRESSION_NONE) outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height]; if (reverse) TIFFFaxDecoder.reverseBits(im); switch (compression) { case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: inflate(im, outBuf); applyPredictor(outBuf, predictor, w, height, samplePerPixel); break; case TIFFConstants.COMPRESSION_NONE: outBuf = im; break; case TIFFConstants.COMPRESSION_PACKBITS: decodePackbits(im, outBuf); break; case TIFFConstants.COMPRESSION_LZW: lzwDecoder.decode(im, outBuf, height); break; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4.fax4Encode(outBuf, height); } else { if (extraSamples > 0) ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height); else zip.write(outBuf); } rowsLeft -= rowsStrip; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { img = Image.getInstance(w, h, false, Image.CCITTG4, photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.close()); } else { zip.close(); img = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.toByteArray()); img.setDeflated(true); } } img.setDpi(dpiX, dpiY); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) { if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (samplePerPixel - extraSamples == icc_prof.getNumComponents()) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } if (dir.isTagPresent(TIFFConstants.TIFFTAG_COLORMAP)) { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_COLORMAP); char rgb[] = fd.getAsChars(); byte palette[] = new byte[rgb.length]; int gColor = rgb.length / 3; int bColor = gColor * 2; for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)(rgb[k] >>> 8); palette[k * 3 + 1] = (byte)(rgb[k + gColor] >>> 8); palette[k * 3 + 2] = (byte)(rgb[k + bColor] >>> 8); } // Colormap components are supposed to go from 0 to 655535 but, // as usually, some tiff producers just put values from 0 to 255. // Let's check for these broken tiffs. boolean colormapBroken = true; for (int k = 0; k < palette.length; ++k) { if (palette[k] != 0) { colormapBroken = false; break; } } if (colormapBroken) { for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)rgb[k]; palette[k * 3 + 1] = (byte)rgb[k + gColor]; palette[k * 3 + 2] = (byte)rgb[k + bColor]; } } PdfArray indexed = new PdfArray(); indexed.add(PdfName.INDEXED); indexed.add(PdfName.DEVICERGB); indexed.add(new PdfNumber(gColor - 1)); indexed.add(new PdfString(palette)); PdfDictionary additional = new PdfDictionary(); additional.put(PdfName.COLORSPACE, indexed); img.setAdditional(additional); } img.setOriginalType(Image.ORIGINAL_TIFF); } if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE) img.setInverted(true); if (rotation != 0) img.setInitialRotation(rotation); if (extraSamples > 0) { mzip.close(); Image mimg = Image.getInstance(w, h, 1, bitsPerSample, mstream.toByteArray()); mimg.makeMask(); mimg.setDeflated(true); img.setImageMask(mimg); } return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// 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/TIFFField.java
public int compareTo(TIFFField o) { if(o == null) { throw new IllegalArgumentException(); } int oTag = o.getTag(); if(tag < oTag) { return -1; } else if(tag > oTag) { return 1; } else { return 0; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/DocumentFont.java
PdfIndirectReference getIndirectReference() { if (refFont == null) throw new IllegalArgumentException("Font reuse not allowed with direct font objects."); return refFont; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseField.java
public void setRotation(int rotation) { if (rotation % 90 != 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("rotation.must.be.a.multiple.of.90")); rotation %= 360; if (rotation < 0) rotation += 360; this.rotation = rotation; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public void addElement(Element element) { if (element == null) return; if (element instanceof Image) { Image img = (Image)element; PdfPTable t = new PdfPTable(1); float w = img.getWidthPercentage(); if (w == 0) { t.setTotalWidth(img.getScaledWidth()); t.setLockedWidth(true); } else t.setWidthPercentage(w); t.setSpacingAfter(img.getSpacingAfter()); t.setSpacingBefore(img.getSpacingBefore()); switch (img.getAlignment()) { case Image.LEFT: t.setHorizontalAlignment(Element.ALIGN_LEFT); break; case Image.RIGHT: t.setHorizontalAlignment(Element.ALIGN_RIGHT); break; default: t.setHorizontalAlignment(Element.ALIGN_CENTER); break; } PdfPCell c = new PdfPCell(img, true); c.setPadding(0); c.setBorder(img.getBorder()); c.setBorderColor(img.getBorderColor()); c.setBorderWidth(img.getBorderWidth()); c.setBackgroundColor(img.getBackgroundColor()); t.addCell(c); element = t; } if (element.type() == Element.CHUNK) { element = new Paragraph((Chunk)element); } else if (element.type() == Element.PHRASE) { element = new Paragraph((Phrase)element); } if (element.type() != Element.PARAGRAPH && element.type() != Element.LIST && element.type() != Element.PTABLE && element.type() != Element.YMARK && element.type() != Element.DIV) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("element.not.allowed")); if (!composite) { composite = true; compositeElements = new LinkedList<Element>(); bidiLine = null; waitPhrase = null; } if (element.type() == Element.PARAGRAPH) { Paragraph p = (Paragraph)element; compositeElements.addAll(p.breakUp()); return; } compositeElements.add(element); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setListOption(String fieldName, String[] exportValues, String[] displayValues) { if (exportValues == null && displayValues == null) return false; if (exportValues != null && displayValues != null && exportValues.length != displayValues.length) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.export.and.the.display.array.must.have.the.same.size")); int ftype = getFieldType(fieldName); if (ftype != FIELD_TYPE_COMBO && ftype != FIELD_TYPE_LIST) return false; Item fd = fields.get(fieldName); String[] sing = null; if (exportValues == null && displayValues != null) sing = displayValues; else if (exportValues != null && displayValues == null) sing = exportValues; PdfArray opt = new PdfArray(); if (sing != null) { for (int k = 0; k < sing.length; ++k) opt.add(new PdfString(sing[k], PdfObject.TEXT_UNICODE)); } else { for (int k = 0; k < exportValues.length; ++k) { PdfArray a = new PdfArray(); a.add(new PdfString(exportValues[k], PdfObject.TEXT_UNICODE)); a.add(new PdfString(displayValues[k], PdfObject.TEXT_UNICODE)); opt.add(a); } } fd.writeToAll( PdfName.OPT, opt, Item.WRITE_VALUE | Item.WRITE_MERGED ); return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAction.java
public static PdfAction setOCGstate(ArrayList<Object> state, boolean preserveRB) { PdfAction action = new PdfAction(); action.put(PdfName.S, PdfName.SETOCGSTATE); PdfArray a = new PdfArray(); for (int k = 0; k < state.size(); ++k) { Object o = state.get(k); if (o == null) continue; if (o instanceof PdfIndirectReference) a.add((PdfIndirectReference)o); else if (o instanceof PdfLayer) a.add(((PdfLayer)o).getRef()); else if (o instanceof PdfName) a.add((PdfName)o); else if (o instanceof String) { PdfName name = null; String s = (String)o; if (s.equalsIgnoreCase("on")) name = PdfName.ON; else if (s.equalsIgnoreCase("off")) name = PdfName.OFF; else if (s.equalsIgnoreCase("toggle")) name = PdfName.TOGGLE; else throw new IllegalArgumentException(MessageLocalization.getComposedMessage("a.string.1.was.passed.in.state.only.on.off.and.toggle.are.allowed", s)); a.add(name); } else throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.type.was.passed.in.state.1", o.getClass().getName())); } action.put(PdfName.STATE, a); if (!preserveRB) action.put(PdfName.PRESERVERB, PdfBoolean.PDFFALSE); return action; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setTagged() { if (open) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("tagging.must.be.set.before.opening.the.document")); tagged = true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
void registerLayer(final PdfOCG layer) { PdfWriter.checkPdfIsoConformance(this, PdfIsoKeys.PDFISOKEY_LAYER, null); if (layer instanceof PdfLayer) { PdfLayer la = (PdfLayer)layer; if (la.getTitle() == null) { if (!documentOCG.contains(layer)) { documentOCG.add(layer); documentOCGorder.add(layer); } } else { documentOCGorder.add(layer); } } else throw new IllegalArgumentException(MessageLocalization.getComposedMessage("only.pdflayer.is.accepted")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/crypto/AESCipherCBCnoPad.java
public byte[] processBlock(byte[] inp, int inpOff, int inpLen) { if ((inpLen % cbc.getBlockSize()) != 0) throw new IllegalArgumentException("Not multiple of block: " + inpLen); byte[] outp = new byte[inpLen]; int baseOffset = 0; while (inpLen > 0) { cbc.processBlock(inp, inpOff, outp, baseOffset); inpLen -= cbc.getBlockSize(); baseOffset += cbc.getBlockSize(); inpOff += cbc.getBlockSize(); } return outp; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
public void setVisibleSignature(Rectangle pageRect, int page, String fieldName) { if (fieldName != null) { if (fieldName.indexOf('.') >= 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("field.names.cannot.contain.a.dot")); AcroFields af = writer.getAcroFields(); AcroFields.Item item = af.getFieldItem(fieldName); if (item != null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.field.1.already.exists", fieldName)); this.fieldName = fieldName; } if (page < 1 || page > writer.reader.getNumberOfPages()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.page.number.1", page)); this.pageRect = new Rectangle(pageRect); this.pageRect.normalize(); rect = new Rectangle(this.pageRect.getWidth(), this.pageRect.getHeight()); this.page = page; newField = true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
public void setVisibleSignature(String fieldName) { AcroFields af = writer.getAcroFields(); AcroFields.Item item = af.getFieldItem(fieldName); if (item == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.field.1.does.not.exist", fieldName)); PdfDictionary merged = item.getMerged(0); if (!PdfName.SIG.equals(PdfReader.getPdfObject(merged.get(PdfName.FT)))) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.field.1.is.not.a.signature.field", fieldName)); this.fieldName = fieldName; PdfArray r = merged.getAsArray(PdfName.RECT); float llx = r.getAsNumber(0).floatValue(); float lly = r.getAsNumber(1).floatValue(); float urx = r.getAsNumber(2).floatValue(); float ury = r.getAsNumber(3).floatValue(); pageRect = new Rectangle(llx, lly, urx, ury); pageRect.normalize(); page = item.getPage(0).intValue(); int rotation = writer.reader.getPageRotation(page); Rectangle pageSize = writer.reader.getPageSizeWithRotation(page); switch (rotation) { case 90: pageRect = new Rectangle( pageRect.getBottom(), pageSize.getTop() - pageRect.getLeft(), pageRect.getTop(), pageSize.getTop() - pageRect.getRight()); break; case 180: pageRect = new Rectangle( pageSize.getRight() - pageRect.getLeft(), pageSize.getTop() - pageRect.getBottom(), pageSize.getRight() - pageRect.getRight(), pageSize.getTop() - pageRect.getTop()); break; case 270: pageRect = new Rectangle( pageSize.getRight() - pageRect.getBottom(), pageRect.getLeft(), pageSize.getRight() - pageRect.getTop(), pageRect.getRight()); break; } if (rotation != 0) pageRect.normalize(); rect = new Rectangle(this.pageRect.getWidth(), this.pageRect.getHeight()); }
// 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 flatFields() { if (append) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("field.flattening.is.not.supported.in.append.mode")); getAcroFields(); Map<String, Item> fields = acroFields.getFields(); if (fieldsAdded && partialFlattening.isEmpty()) { for (String s: fields.keySet()) { partialFlattening.add(s); } } PdfDictionary acroForm = reader.getCatalog().getAsDict(PdfName.ACROFORM); PdfArray acroFds = null; if (acroForm != null) { acroFds = (PdfArray)PdfReader.getPdfObject(acroForm.get(PdfName.FIELDS), acroForm); } for (Map.Entry<String, Item> entry: fields.entrySet()) { String name = entry.getKey(); if (!partialFlattening.isEmpty() && !partialFlattening.contains(name)) continue; AcroFields.Item item = entry.getValue(); for (int k = 0; k < item.size(); ++k) { PdfDictionary merged = item.getMerged(k); PdfNumber ff = merged.getAsNumber(PdfName.F); int flags = 0; if (ff != null) flags = ff.intValue(); int page = item.getPage(k).intValue(); PdfDictionary appDic = merged.getAsDict(PdfName.AP); if (appDic != null && (flags & PdfFormField.FLAGS_PRINT) != 0 && (flags & PdfFormField.FLAGS_HIDDEN) == 0) { PdfObject obj = appDic.get(PdfName.N); PdfAppearance app = null; if (obj != null) { PdfObject objReal = PdfReader.getPdfObject(obj); if (obj instanceof PdfIndirectReference && !obj.isIndirect()) app = new PdfAppearance((PdfIndirectReference)obj); else if (objReal instanceof PdfStream) { ((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM); app = new PdfAppearance((PdfIndirectReference)obj); } else { if (objReal != null && objReal.isDictionary()) { PdfName as = merged.getAsName(PdfName.AS); if (as != null) { PdfIndirectReference iref = (PdfIndirectReference)((PdfDictionary)objReal).get(as); if (iref != null) { app = new PdfAppearance(iref); if (iref.isIndirect()) { objReal = PdfReader.getPdfObject(iref); ((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM); } } } } } } if (app != null) { Rectangle box = PdfReader.getNormalizedRectangle(merged.getAsArray(PdfName.RECT)); PdfContentByte cb = getOverContent(page); cb.setLiteral("Q "); cb.addTemplate(app, box.getLeft(), box.getBottom()); cb.setLiteral("q "); } } if (partialFlattening.isEmpty()) continue; PdfDictionary pageDic = reader.getPageN(page); PdfArray annots = pageDic.getAsArray(PdfName.ANNOTS); if (annots == null) continue; for (int idx = 0; idx < annots.size(); ++idx) { PdfObject ran = annots.getPdfObject(idx); if (!ran.isIndirect()) continue; PdfObject ran2 = item.getWidgetRef(k); if (!ran2.isIndirect()) continue; if (((PRIndirectReference)ran).getNumber() == ((PRIndirectReference)ran2).getNumber()) { annots.remove(idx--); PRIndirectReference wdref = (PRIndirectReference)ran2; while (true) { PdfDictionary wd = (PdfDictionary)PdfReader.getPdfObject(wdref); PRIndirectReference parentRef = (PRIndirectReference)wd.get(PdfName.PARENT); PdfReader.killIndirect(wdref); if (parentRef == null) { // reached AcroForm for (int fr = 0; fr < acroFds.size(); ++fr) { PdfObject h = acroFds.getPdfObject(fr); if (h.isIndirect() && ((PRIndirectReference)h).getNumber() == wdref.getNumber()) { acroFds.remove(fr); --fr; } } break; } PdfDictionary parent = (PdfDictionary)PdfReader.getPdfObject(parentRef); PdfArray kids = parent.getAsArray(PdfName.KIDS); for (int fr = 0; fr < kids.size(); ++fr) { PdfObject h = kids.getPdfObject(fr); if (h.isIndirect() && ((PRIndirectReference)h).getNumber() == wdref.getNumber()) { kids.remove(fr); --fr; } } if (!kids.isEmpty()) break; wdref = parentRef; } } } if (annots.isEmpty()) { PdfReader.killIndirect(pageDic.get(PdfName.ANNOTS)); pageDic.remove(PdfName.ANNOTS); } } } if (!fieldsAdded && partialFlattening.isEmpty()) { for (int page = 1; page <= reader.getNumberOfPages(); ++page) { PdfDictionary pageDic = reader.getPageN(page); PdfArray annots = pageDic.getAsArray(PdfName.ANNOTS); if (annots == null) continue; for (int idx = 0; idx < annots.size(); ++idx) { PdfObject annoto = annots.getDirectObject(idx); if (annoto instanceof PdfIndirectReference && !annoto.isIndirect()) continue; if (!annoto.isDictionary() || PdfName.WIDGET.equals(((PdfDictionary)annoto).get(PdfName.SUBTYPE))) { annots.remove(idx); --idx; } } if (annots.isEmpty()) { PdfReader.killIndirect(pageDic.get(PdfName.ANNOTS)); pageDic.remove(PdfName.ANNOTS); } } eliminateAcroformObjects(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
protected void flatFreeTextFields() { if (append) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("freetext.flattening.is.not.supported.in.append.mode")); for (int page = 1; page <= reader.getNumberOfPages(); ++page) { PdfDictionary pageDic = reader.getPageN(page); PdfArray annots = pageDic.getAsArray(PdfName.ANNOTS); if (annots == null) continue; for (int idx = 0; idx < annots.size(); ++idx) { PdfObject annoto = annots.getDirectObject(idx); if (annoto instanceof PdfIndirectReference && !annoto.isIndirect()) continue; PdfDictionary annDic = (PdfDictionary)annoto; if (!((PdfName)annDic.get(PdfName.SUBTYPE)).equals(PdfName.FREETEXT)) continue; PdfNumber ff = annDic.getAsNumber(PdfName.F); int flags = ff != null ? ff.intValue() : 0; if ( (flags & PdfFormField.FLAGS_PRINT) != 0 && (flags & PdfFormField.FLAGS_HIDDEN) == 0) { PdfObject obj1 = annDic.get(PdfName.AP); if (obj1 == null) continue; PdfDictionary appDic = obj1 instanceof PdfIndirectReference ? (PdfDictionary) PdfReader.getPdfObject(obj1) : (PdfDictionary) obj1; PdfObject obj = appDic.get(PdfName.N); PdfAppearance app = null; PdfObject objReal = PdfReader.getPdfObject(obj); if (obj instanceof PdfIndirectReference && !obj.isIndirect()) app = new PdfAppearance((PdfIndirectReference)obj); else if (objReal instanceof PdfStream) { ((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM); app = new PdfAppearance((PdfIndirectReference)obj); } else { if (objReal.isDictionary()) { PdfName as_p = appDic.getAsName(PdfName.AS); if (as_p != null) { PdfIndirectReference iref = (PdfIndirectReference)((PdfDictionary)objReal).get(as_p); if (iref != null) { app = new PdfAppearance(iref); if (iref.isIndirect()) { objReal = PdfReader.getPdfObject(iref); ((PdfDictionary)objReal).put(PdfName.SUBTYPE, PdfName.FORM); } } } } } if (app != null) { Rectangle box = PdfReader.getNormalizedRectangle(annDic.getAsArray(PdfName.RECT)); PdfContentByte cb = getOverContent(page); cb.setLiteral("Q "); cb.addTemplate(app, box.getLeft(), box.getBottom()); cb.setLiteral("q "); } } } for (int idx = 0; idx < annots.size(); ++idx) { PdfDictionary annot = annots.getAsDict(idx); if (annot != null) { if (PdfName.FREETEXT.equals(annot.get(PdfName.SUBTYPE))) { annots.remove(idx); --idx; } } } if (annots.isEmpty()) { PdfReader.killIndirect(pageDic.get(PdfName.ANNOTS)); pageDic.remove(PdfName.ANNOTS); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public PdfIndirectReference getPageReference(int page) { PdfIndirectReference ref = reader.getPageOrigRef(page); if (ref == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.page.number.1", page)); return ref; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPCell.java
public void setRotation(int rotation) { rotation %= 360; if (rotation < 0) rotation += 360; if (rotation % 90 != 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("rotation.must.be.a.multiple.of.90")); this.rotation = rotation; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/events/FieldPositioningEvents.java
public void cellLayout(PdfPCell cell, Rectangle rect, PdfContentByte[] canvases) { if (cellField == null || fieldWriter == null && parent == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.used.the.wrong.constructor.for.this.fieldpositioningevents.class")); cellField.put(PdfName.RECT, new PdfRectangle(rect.getLeft(padding), rect.getBottom(padding), rect.getRight(padding), rect.getTop(padding))); if (parent == null) fieldWriter.addAnnotation(cellField); else parent.addKid(cellField); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
private byte[] convertToBytesAfterGlyphSubstitution(final String text) throws UnsupportedEncodingException { if (!canApplyGlyphSubstitution()) { throw new IllegalArgumentException("Make sure the font type if TTF Unicode and a valid GlyphSubstitutionTable exists!"); } Map<String, Glyph> glyphSubstitutionMap = ttu.getGlyphSubstitutionMap(); // generate a regex from the characters to be substituted // for Indic languages: push back the CompositeCharacters with smaller length Set<String> compositeCharacters = new TreeSet<String>(new IndicCompositeCharacterComparator()); compositeCharacters.addAll(glyphSubstitutionMap.keySet()); // convert the text to a list of Glyph, also take care of the substitution ArrayBasedStringTokenizer tokenizer = new ArrayBasedStringTokenizer(compositeCharacters.toArray(new String[0])); String[] tokens = tokenizer.tokenize(text); List<Glyph> glyphList = new ArrayList<Glyph>(50); for (String token : tokens) { // first check whether this is in the substitution map Glyph subsGlyph = glyphSubstitutionMap.get(token); if (subsGlyph != null) { glyphList.add(subsGlyph); } else { // break up the string into individual characters for (char c : token.toCharArray()) { int[] metrics = ttu.getMetricsTT(c); int glyphCode = metrics[0]; int glyphWidth = metrics[1]; glyphList.add(new Glyph(glyphCode, glyphWidth, String.valueOf(c))); } } } GlyphRepositioner glyphRepositioner = getGlyphRepositioner(); if (glyphRepositioner != null) { glyphRepositioner.repositionGlyphs(glyphList); } char[] charEncodedGlyphCodes = new char[glyphList.size()]; // process each Glyph thus obtained for (int i = 0; i < glyphList.size(); i++) { Glyph glyph = glyphList.get(i); charEncodedGlyphCodes[i] = (char) glyph.code; Integer glyphCode = Integer.valueOf(glyph.code); if (!longTag.containsKey(glyphCode)) { // FIXME: this is buggy as the 3rd arg. should be a String as a Glyph can represent more than 1 char longTag.put(glyphCode, new int[]{glyph.code, glyph.width, glyph.chars.charAt(0)}); } } return new String(charEncodedGlyphCodes).getBytes(CJKFont.CJK_ENCODING); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
private GlyphRepositioner getGlyphRepositioner() { Language language = ttu.getSupportedLanguage(); if (language == null) { throw new IllegalArgumentException("The supported language field cannot be null in " + ttu.getClass().getName()); } switch (language) { case BENGALI: return new BanglaGlyphRepositioner(Collections.unmodifiableMap(ttu.cmap31), ttu.getGlyphSubstitutionMap()); default: return null; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/ReedSolomonEncoder.java
public void encode(int[] toEncode, int ecBytes) { if (ecBytes == 0) { throw new IllegalArgumentException("No error correction bytes"); } int dataBytes = toEncode.length - ecBytes; if (dataBytes <= 0) { throw new IllegalArgumentException("No data bytes provided"); } GF256Poly generator = buildGenerator(ecBytes); int[] infoCoefficients = new int[dataBytes]; System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes); GF256Poly info = new GF256Poly(field, infoCoefficients); info = info.multiplyByMonomial(ecBytes, 1); GF256Poly remainder = info.divide(generator)[1]; int[] coefficients = remainder.getCoefficients(); int numZeroCoefficients = ecBytes - coefficients.length; for (int i = 0; i < numZeroCoefficients; i++) { toEncode[dataBytes + i] = 0; } System.arraycopy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.length); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Version.java
public static Version getProvisionalVersionForDimension(int dimension) { if (dimension % 4 != 1) { throw new IllegalArgumentException(); } try { return getVersionForNumber((dimension - 17) >> 2); } catch (IllegalArgumentException iae) { throw iae; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Version.java
public static Version getVersionForNumber(int versionNumber) { if (versionNumber < 1 || versionNumber > 40) { throw new IllegalArgumentException(); } return VERSIONS[versionNumber - 1]; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Mode.java
public static Mode forBits(int bits) { switch (bits) { case 0x0: return TERMINATOR; case 0x1: return NUMERIC; case 0x2: return ALPHANUMERIC; case 0x3: return STRUCTURED_APPEND; case 0x4: return BYTE; case 0x5: return FNC1_FIRST_POSITION; case 0x7: return ECI; case 0x8: return KANJI; case 0x9: return FNC1_SECOND_POSITION; default: throw new IllegalArgumentException(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Mode.java
public int getCharacterCountBits(Version version) { if (characterCountBitsForVersions == null) { throw new IllegalArgumentException("Character count doesn't apply to this mode"); } int number = version.getVersionNumber(); int offset; if (number <= 9) { offset = 0; } else if (number <= 26) { offset = 1; } else { offset = 2; } return characterCountBitsForVersions[offset]; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256Poly.java
GF256Poly addOrSubtract(GF256Poly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GF256Polys do not have same GF256 field"); } if (isZero()) { return other; } if (other.isZero()) { return this; } int[] smallerCoefficients = this.coefficients; int[] largerCoefficients = other.coefficients; if (smallerCoefficients.length > largerCoefficients.length) { int[] temp = smallerCoefficients; smallerCoefficients = largerCoefficients; largerCoefficients = temp; } int[] sumDiff = new int[largerCoefficients.length]; int lengthDiff = largerCoefficients.length - smallerCoefficients.length; // Copy high-order terms only found in higher-degree polynomial's coefficients System.arraycopy(largerCoefficients, 0, sumDiff, 0, lengthDiff); for (int i = lengthDiff; i < largerCoefficients.length; i++) { sumDiff[i] = GF256.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]); } return new GF256Poly(field, sumDiff); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256Poly.java
GF256Poly multiply(GF256Poly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GF256Polys do not have same GF256 field"); } if (isZero() || other.isZero()) { return field.getZero(); } int[] aCoefficients = this.coefficients; int aLength = aCoefficients.length; int[] bCoefficients = other.coefficients; int bLength = bCoefficients.length; int[] product = new int[aLength + bLength - 1]; for (int i = 0; i < aLength; i++) { int aCoeff = aCoefficients[i]; for (int j = 0; j < bLength; j++) { product[i + j] = GF256.addOrSubtract(product[i + j], field.multiply(aCoeff, bCoefficients[j])); } } return new GF256Poly(field, product); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256Poly.java
GF256Poly multiplyByMonomial(int degree, int coefficient) { if (degree < 0) { throw new IllegalArgumentException(); } if (coefficient == 0) { return field.getZero(); } int size = coefficients.length; int[] product = new int[size + degree]; for (int i = 0; i < size; i++) { product[i] = field.multiply(coefficients[i], coefficient); } return new GF256Poly(field, product); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256Poly.java
GF256Poly[] divide(GF256Poly other) { if (!field.equals(other.field)) { throw new IllegalArgumentException("GF256Polys do not have same GF256 field"); } if (other.isZero()) { throw new IllegalArgumentException("Divide by 0"); } GF256Poly quotient = field.getZero(); GF256Poly remainder = this; int denominatorLeadingTerm = other.getCoefficient(other.getDegree()); int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm); while (remainder.getDegree() >= other.getDegree() && !remainder.isZero()) { int degreeDifference = remainder.getDegree() - other.getDegree(); int scale = field.multiply(remainder.getCoefficient(remainder.getDegree()), inverseDenominatorLeadingTerm); GF256Poly term = other.multiplyByMonomial(degreeDifference, scale); GF256Poly iterationQuotient = field.buildMonomial(degreeDifference, scale); quotient = quotient.addOrSubtract(iterationQuotient); remainder = remainder.addOrSubtract(term); } return new GF256Poly[] { quotient, remainder }; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/ErrorCorrectionLevel.java
public static ErrorCorrectionLevel forBits(int bits) { if (bits < 0 || bits >= FOR_BITS.length) { throw new IllegalArgumentException(); } return FOR_BITS[bits]; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitArray.java
public boolean isRange(int start, int end, boolean value) { if (end < start) { throw new IllegalArgumentException(); } if (end == start) { return true; // empty range matches } end--; // will be easier to treat this as the last actually set bit -- inclusive int firstInt = start >> 5; int lastInt = end >> 5; for (int i = firstInt; i <= lastInt; i++) { int firstBit = i > firstInt ? 0 : start & 0x1F; int lastBit = i < lastInt ? 31 : end & 0x1F; int mask; if (firstBit == 0 && lastBit == 31) { mask = -1; } else { mask = 0; for (int j = firstBit; j <= lastBit; j++) { mask |= 1 << j; } } // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is, // equals the mask, or we're looking for 0s and the masked portion is not all 0s if ((bits[i] & mask) != (value ? mask : 0)) { return false; } } return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitMatrix.java
public void setRegion(int left, int top, int width, int height) { if (top < 0 || left < 0) { throw new IllegalArgumentException("Left and top must be nonnegative"); } if (height < 1 || width < 1) { throw new IllegalArgumentException("Height and width must be at least 1"); } int right = left + width; int bottom = top + height; if (bottom > this.height || right > this.width) { throw new IllegalArgumentException("The region must fit inside the matrix"); } for (int y = top; y < bottom; y++) { int offset = y * rowSize; for (int x = left; x < right; x++) { bits[offset + (x >> 5)] |= 1 << (x & 0x1f); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256.java
GF256Poly buildMonomial(int degree, int coefficient) { if (degree < 0) { throw new IllegalArgumentException(); } if (coefficient == 0) { return zero; } int[] coefficients = new int[degree + 1]; coefficients[0] = coefficient; return new GF256Poly(this, coefficients); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/GF256.java
int log(int a) { if (a == 0) { throw new IllegalArgumentException(); } return logTable[a]; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/QRCodeWriter.java
public ByteMatrix encode(String contents, int width, int height, Map<EncodeHintType,Object> hints) throws WriterException { if (contents == null || contents.length() == 0) { throw new IllegalArgumentException("Found empty contents"); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height); } ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; if (hints != null) { ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints.get(EncodeHintType.ERROR_CORRECTION); if (requestedECLevel != null) { errorCorrectionLevel = requestedECLevel; } } QRCode code = new QRCode(); Encoder.encode(contents, errorCorrectionLevel, hints, code); return renderResult(code, width, height); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitVector.java
public int at(int index) { if (index < 0 || index >= sizeInBits) { throw new IllegalArgumentException("Bad index: " + index); } int value = array[index >> 3] & 0xff; return (value >> (7 - (index & 0x7))) & 1; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitVector.java
public void appendBit(int bit) { if (!(bit == 0 || bit == 1)) { throw new IllegalArgumentException("Bad bit"); } int numBitsInLastByte = sizeInBits & 0x7; // We'll expand array if we don't have bits in the last byte. if (numBitsInLastByte == 0) { appendByte(0); sizeInBits -= 8; } // Modify the last byte. array[sizeInBits >> 3] |= (bit << (7 - numBitsInLastByte)); ++sizeInBits; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitVector.java
public void appendBits(int value, int numBits) { if (numBits < 0 || numBits > 32) { throw new IllegalArgumentException("Num bits must be between 0 and 32"); } int numBitsLeft = numBits; while (numBitsLeft > 0) { // Optimization for byte-oriented appending. if ((sizeInBits & 0x7) == 0 && numBitsLeft >= 8) { int newByte = (value >> (numBitsLeft - 8)) & 0xff; appendByte(newByte); numBitsLeft -= 8; } else { int bit = (value >> (numBitsLeft - 1)) & 1; appendBit(bit); --numBitsLeft; } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitVector.java
public void xor(BitVector other) { if (sizeInBits != other.size()) { throw new IllegalArgumentException("BitVector sizes don't match"); } int sizeInBytes = (sizeInBits + 7) >> 3; for (int i = 0; i < sizeInBytes; ++i) { // The last byte could be incomplete (i.e. not have 8 bits in // it) but there is no problem since 0 XOR 0 == 0. array[i] ^= other.array[i]; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitVector.java
public String toString() { StringBuffer result = new StringBuffer(sizeInBits); for (int i = 0; i < sizeInBits; ++i) { if (at(i) == 0) { result.append('0'); } else if (at(i) == 1) { result.append('1'); } else { throw new IllegalArgumentException("Byte isn't 0 or 1"); } } return result.toString(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MaskUtil.java
public static boolean getDataMaskBit(int maskPattern, int x, int y) { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new IllegalArgumentException("Invalid mask pattern"); } int intermediate, temp; switch (maskPattern) { case 0: intermediate = (y + x) & 0x1; break; case 1: intermediate = y & 0x1; break; case 2: intermediate = x % 3; break; case 3: intermediate = (y + x) % 3; break; case 4: intermediate = ((y >>> 1) + (x / 3)) & 0x1; break; case 5: temp = y * x; intermediate = (temp & 0x1) + (temp % 3); break; case 6: temp = y * x; intermediate = (((temp & 0x1) + (temp % 3)) & 0x1); break; case 7: temp = y * x; intermediate = (((temp % 3) + ((y + x) & 0x1)) & 0x1); break; default: throw new IllegalArgumentException("Invalid mask pattern: " + maskPattern); } return intermediate == 0; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void setFontAndSize(final BaseFont bf, final float size) { if (!inText && isTagged()) { beginText(true); } checkWriter(); if (size < 0.0001f && size > -0.0001f) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("font.size.too.small.1", String.valueOf(size))); state.size = size; state.fontDetails = writer.addSimple(bf); PageResources prs = getPageResources(); PdfName name = state.fontDetails.getFontName(); name = prs.addFont(name, state.fontDetails.getIndirectReference()); content.append(name.getBytes()).append(' ').append(size).append(" Tf").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void beginLayer(final PdfOCG layer) { if (layer instanceof PdfLayer && ((PdfLayer)layer).getTitle() != null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("a.title.is.not.a.layer")); if (layerDepth == null) layerDepth = new ArrayList<Integer>(); if (layer instanceof PdfLayerMembership) { layerDepth.add(Integer.valueOf(1)); beginLayer2(layer); return; } int n = 0; PdfLayer la = (PdfLayer)layer; while (la != null) { if (la.getTitle() == null) { beginLayer2(la); ++n; } la = la.getParent(); } layerDepth.add(Integer.valueOf(n)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void beginMarkedContentSequence(final PdfStructureElement struc) { PdfObject obj = struc.get(PdfName.K); int mark = pdf.getMarkPoint(); if (obj != null) { PdfArray ar = null; if (obj.isNumber()) { ar = new PdfArray(); ar.add(obj); struc.put(PdfName.K, ar); } else if (obj.isArray()) { ar = (PdfArray)obj; } else throw new IllegalArgumentException(MessageLocalization.getComposedMessage("unknown.object.at.k.1", obj.getClass().toString())); if (ar.getAsNumber(0) != null) { PdfDictionary dic = new PdfDictionary(PdfName.MCR); dic.put(PdfName.PG, writer.getCurrentPage()); dic.put(PdfName.MCID, new PdfNumber(mark)); ar.add(dic); } struc.setPageMark(writer.getPageNumber() - 1, -1); } else { struc.setPageMark(writer.getPageNumber() - 1, mark); struc.put(PdfName.PG, writer.getCurrentPage()); } pdf.incMarkPoint(); setMcDepth(getMcDepth() + 1); int contentSize = content.size(); content.append(struc.get(PdfName.S).getBytes()).append(" <</MCID ").append(mark).append(">> BDC").append_i(separator); markedContentSize += content.size() - contentSize; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
public static byte[] getBarsCode39(String text) { text = "*" + text + "*"; byte bars[] = new byte[text.length() * 10 - 1]; for (int k = 0; k < text.length(); ++k) { int idx = CHARS.indexOf(text.charAt(k)); if (idx < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.character.1.is.illegal.in.code.39", text.charAt(k))); System.arraycopy(BARS[idx], 0, bars, k * 10, 9); } return bars; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
public static String getCode39Ex(String text) { StringBuilder out = new StringBuilder(""); for (int k = 0; k < text.length(); ++k) { char c = text.charAt(k); if (c > 127) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.character.1.is.illegal.in.code.39.extended", c)); char c1 = EXTENDED.charAt(c * 2); char c2 = EXTENDED.charAt(c * 2 + 1); if (c1 != ' ') out.append(c1); out.append(c2); } return out.toString(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode39.java
static char getChecksum(String text) { int chk = 0; for (int k = 0; k < text.length(); ++k) { int idx = CHARS.indexOf(text.charAt(k)); if (idx < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.character.1.is.illegal.in.code.39", text.charAt(k))); chk += idx; } return CHARS.charAt(chk % 43); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfLayer.java
public void addChild(PdfLayer child) { if (child.parent != null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.layer.1.already.has.a.parent", child.getAsString(PdfName.NAME).toUnicodeString())); child.parent = this; if (children == null) children = new ArrayList<PdfLayer>(); children.add(child); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Type3Font.java
public PdfContentByte defineGlyph(char c, float wx, float llx, float lly, float urx, float ury) { if (c == 0 || c > 255) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.char.1.doesn.t.belong.in.this.type3.font", c)); usedSlot[c] = true; Integer ck = Integer.valueOf(c); Type3Glyph glyph = char2glyph.get(ck); if (glyph != null) return glyph; widths3.put(c, (int)wx); if (!colorized) { if (Float.isNaN(this.llx)) { this.llx = llx; this.lly = lly; this.urx = urx; this.ury = ury; } else { this.llx = Math.min(this.llx, llx); this.lly = Math.min(this.lly, lly); this.urx = Math.max(this.urx, urx); this.ury = Math.max(this.ury, ury); } } glyph = new Type3Glyph(writer, pageResources, wx, llx, lly, urx, ury, colorized); char2glyph.put(ck, glyph); return glyph; }
// 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/Type3Font.java
Override public int getWidth(int char1) { if (!widths3.containsKey(char1)) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.char.1.is.not.defined.in.a.type3.font", char1)); return widths3.get(char1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReaderInstance.java
PdfImportedPage getImportedPage(int pageNumber) { if (!reader.isOpenedWithFullPermissions()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password")); if (pageNumber < 1 || pageNumber > reader.getNumberOfPages()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.page.number.1", pageNumber)); Integer i = Integer.valueOf(pageNumber); PdfImportedPage pageT = importedPages.get(i); if (pageT == null) { pageT = new PdfImportedPage(this, writer, pageNumber); importedPages.put(i, pageT); } return pageT; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfVisibilityExpression.java
Override public void add(int index, PdfObject element) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.ve.value")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfVisibilityExpression.java
Override public boolean add(PdfObject object) { if (object instanceof PdfLayer) return super.add(((PdfLayer)object).getRef()); if (object instanceof PdfVisibilityExpression) return super.add(object); throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.ve.value")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfVisibilityExpression.java
Override public void addFirst(PdfObject object) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.ve.value")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfVisibilityExpression.java
Override public boolean add(float[] values) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.ve.value")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfVisibilityExpression.java
Override public boolean add(int[] values) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.ve.value")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopyFormsImp.java
public void copyDocumentFields(PdfReader reader) throws DocumentException { if (!reader.isOpenedWithFullPermissions()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("pdfreader.not.opened.with.owner.password")); 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()); fields.add(reader.getAcroFields()); updateCalculationOrder(reader); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/collection/PdfCollectionSort.java
public void setSortOrder(boolean ascending) { PdfObject o = get(PdfName.S); if (o instanceof PdfName) { put(PdfName.A, new PdfBoolean(ascending)); } else { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.to.define.a.boolean.array.for.this.collection.sort.dictionary")); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/collection/PdfCollectionSort.java
public void setSortOrder(boolean[] ascending) { PdfObject o = get(PdfName.S); if (o instanceof PdfArray) { if (((PdfArray)o).size() != ascending.length) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.number.of.booleans.in.this.array.doesn.t.correspond.with.the.number.of.fields")); } PdfArray array = new PdfArray(); for (int i = 0; i < ascending.length; i++) { array.add(new PdfBoolean(ascending[i])); } put(PdfName.A, array); } else { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.need.a.single.boolean.for.this.collection.sort.dictionary")); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/collection/PdfCollectionItem.java
public void setPrefix(String key, String prefix) { PdfName fieldname = new PdfName(key); PdfObject o = get(fieldname); if (o == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.must.set.a.value.before.adding.a.prefix")); PdfDictionary dict = new PdfDictionary(PdfName.COLLECTIONSUBITEM); dict.put(PdfName.D, o); dict.put(PdfName.P, new PdfString(prefix, PdfObject.TEXT_UNICODE)); put(fieldname, dict); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/collection/PdfCollectionField.java
public PdfObject getValue(String v) { switch(fieldType) { case TEXT: return new PdfString(v, PdfObject.TEXT_UNICODE); case DATE: return new PdfDate(PdfDate.decode(v)); case NUMBER: return new PdfNumber(v); } throw new IllegalArgumentException(MessageLocalization.getComposedMessage("1.is.not.an.acceptable.value.for.the.field.2", v, get(PdfName.N).toString())); }
// 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) { PdfName dictionaryName = (PdfName)operands.get(0); PdfDictionary extGState = processor.resources.getAsDict(PdfName.EXTGSTATE); if (extGState == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("resources.do.not.contain.extgstate.entry.unable.to.process.operator.1", operator)); PdfDictionary gsDic = extGState.getAsDict(dictionaryName); if (gsDic == null) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("1.is.an.unknown.graphics.state.dictionary", dictionaryName)); // at this point, all we care about is the FONT entry in the GS dictionary PdfArray fontParameter = gsDic.getAsArray(PdfName.FONT); if (fontParameter != null){ CMapAwareDocumentFont font = processor.getFont((PRIndirectReference)fontParameter.getPdfObject(0)); float size = fontParameter.getAsNumber(1).floatValue(); processor.gs().font = font; processor.gs().fontSize = size; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/parser/InlineImageUtils.java
private static int getComponentsPerPixel(PdfName colorSpaceName, PdfDictionary colorSpaceDic){ if (colorSpaceName == null) return 1; if (colorSpaceName.equals(PdfName.DEVICEGRAY)) return 1; if (colorSpaceName.equals(PdfName.DEVICERGB)) return 3; if (colorSpaceName.equals(PdfName.DEVICECMYK)) return 4; if (colorSpaceDic != null){ PdfArray colorSpace = colorSpaceDic.getAsArray(colorSpaceName); if (colorSpace != null){ if (PdfName.INDEXED.equals(colorSpace.getAsName(0))){ return 1; } } } throw new IllegalArgumentException("Unexpected color space " + colorSpaceName); }
// 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/ICC_Profile.java
public static ICC_Profile getInstance(byte[] data, int numComponents) { if (data.length < 128 || data[36] != 0x61 || data[37] != 0x63 || data[38] != 0x73 || data[39] != 0x70) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); try { ICC_Profile icc = new ICC_Profile(); icc.data = data; Integer cs; cs = cstags.get(new String(data, 16, 4, "US-ASCII")); int nc = cs == null ? 0 : cs.intValue(); icc.numComponents = nc; // invalid ICC if (nc != numComponents) { throw new IllegalArgumentException("ICC profile contains " + nc + " component(s), the image data contains " + numComponents + " component(s)"); } return icc; } catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
public static ICC_Profile getInstance(InputStream file) { try { byte[] head = new byte[128]; int remain = head.length; int ptr = 0; while (remain > 0) { int n = file.read(head, ptr, remain); if (n < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain -= n; ptr += n; } if (head[36] != 0x61 || head[37] != 0x63 || head[38] != 0x73 || head[39] != 0x70) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain = (head[0] & 0xff) << 24 | (head[1] & 0xff) << 16 | (head[2] & 0xff) << 8 | head[3] & 0xff; byte[] icc = new byte[remain]; System.arraycopy(head, 0, icc, 0, head.length); remain -= head.length; ptr = head.length; while (remain > 0) { int n = file.read(icc, ptr, remain); if (n < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.icc.profile")); remain -= n; ptr += n; } return getInstance(icc); } catch (Exception ex) { throw new ExceptionConverter(ex); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
public int getDestinationPage() { if (!isInternal()) return 0; // here destination is something like // [132 0 R, /XYZ, 29.3898, 731.864502, null] PdfIndirectReference ref = destination.getAsIndirectObject(0); PRIndirectReference pr = (PRIndirectReference) ref; PdfReader r = pr.getReader(); for (int i = 1; i <= r.getNumberOfPages(); i++) { PRIndirectReference pp = r.getPageOrigRef(i); if (pp.getGeneration() == pr.getGeneration() && pp.getNumber() == pr.getNumber()) return i; } throw new IllegalArgumentException(MessageLocalization.getComposedMessage("page.not.found")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
public void setDestinationPage(int newPage) { if (!isInternal()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("cannot.change.destination.of.external.link")); this.newPage=newPage; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
public void transformDestination(float a, float b, float c, float d, float e, float f) { if (!isInternal()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("cannot.change.destination.of.external.link")); if (destination.getAsName(1).equals(PdfName.XYZ)) { float x = destination.getAsNumber(2).floatValue(); float y = destination.getAsNumber(3).floatValue(); float xx = x * a + y * c + e; float yy = x * b + y * d + f; destination.set(2, new PdfNumber(xx)); destination.set(3, new PdfNumber(yy)); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
public void paintCode() { int maxErr, lenErr, tot, pad; if ((options & PDF417_USE_RAW_CODEWORDS) != 0) { if (lenCodewords > MAX_DATA_CODEWORDS || lenCodewords < 1 || lenCodewords != codewords[0]) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.codeword.size")); } } else { if (text == null) throw new NullPointerException(MessageLocalization.getComposedMessage("text.cannot.be.null")); if (text.length > ABSOLUTE_MAX_TEXT_SIZE) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } segmentList = new SegmentList(); breakString(); //dumpList(); assemble(); segmentList = null; codewords[0] = lenCodewords = cwPtr; } maxErr = maxPossibleErrorLevel(MAX_DATA_CODEWORDS + 2 - lenCodewords); if ((options & PDF417_USE_ERROR_LEVEL) == 0) { if (lenCodewords < 41) errorLevel = 2; else if (lenCodewords < 161) errorLevel = 3; else if (lenCodewords < 321) errorLevel = 4; else errorLevel = 5; } if (errorLevel < 0) errorLevel = 0; else if (errorLevel > maxErr) errorLevel = maxErr; if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) codeRows = 90; lenErr = 2 << errorLevel; boolean fixedColumn = (options & PDF417_FIXED_ROWS) == 0; boolean skipRowColAdjust = false; tot = lenCodewords + lenErr; if ((options & PDF417_FIXED_RECTANGLE) != 0) { tot = codeColumns * codeRows; if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } if (tot < lenCodewords + lenErr) tot = lenCodewords + lenErr; else skipRowColAdjust = true; } else if ((options & (PDF417_FIXED_COLUMNS | PDF417_FIXED_ROWS)) == 0) { double c, b; fixedColumn = true; if (aspectRatio < 0.001) aspectRatio = 0.001f; else if (aspectRatio > 1000) aspectRatio = 1000; b = 73 * aspectRatio - 4; c = (-b + Math.sqrt(b * b + 4 * 17 * aspectRatio * (lenCodewords + lenErr) * yHeight)) / (2 * 17 * aspectRatio); codeColumns = (int)(c + 0.5); if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; } if (!skipRowColAdjust) { if (fixedColumn) { codeRows = (tot - 1) / codeColumns + 1; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) { codeRows = 90; codeColumns = (tot - 1) / 90 + 1; } } else { codeColumns = (tot - 1) / codeRows + 1; if (codeColumns > 30) { codeColumns = 30; codeRows = (tot - 1) / 30 + 1; } } tot = codeRows * codeColumns; } if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } errorLevel = maxPossibleErrorLevel(tot - lenCodewords); lenErr = 2 << errorLevel; pad = tot - lenErr - lenCodewords; if ((options & PDF417_USE_MACRO) != 0) { // the padding comes before the control block System.arraycopy(codewords, macroIndex, codewords, macroIndex + pad, pad); cwPtr = lenCodewords + pad; while (pad-- != 0) codewords[macroIndex++] = TEXT_MODE; } else { cwPtr = lenCodewords; while (pad-- != 0) codewords[cwPtr++] = TEXT_MODE; } codewords[0] = lenCodewords = cwPtr; calculateErrorCorrection(lenCodewords); lenCodewords = tot; outPaintCode(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeCodabar.java
public static byte[] getBarsCodabar(String text) { text = text.toUpperCase(); int len = text.length(); if (len < 2) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("codabar.must.have.at.least.a.start.and.stop.character")); if (CHARS.indexOf(text.charAt(0)) < START_STOP_IDX || CHARS.indexOf(text.charAt(len - 1)) < START_STOP_IDX) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("codabar.must.have.one.of.abcd.as.start.stop.character")); byte bars[] = new byte[text.length() * 8 - 1]; for (int k = 0; k < len; ++k) { int idx = CHARS.indexOf(text.charAt(k)); if (idx >= START_STOP_IDX && k > 0 && k < len - 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("in.codabar.start.stop.characters.are.only.allowed.at.the.extremes")); if (idx < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.character.1.is.illegal.in.codabar", text.charAt(k))); System.arraycopy(BARS[idx], 0, bars, k * 8, 7); } return bars; }
// 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/cmaps/AbstractCMap.java
void addRange(PdfString from, PdfString to, PdfObject code) { byte[] a1 = decodeStringToByte(from); byte[] a2 = decodeStringToByte(to); if (a1.length != a2.length || a1.length == 0) throw new IllegalArgumentException("Invalid map."); byte[] sout = null; if (code instanceof PdfString) sout = decodeStringToByte((PdfString)code); int start = a1[a1.length - 1] & 0xff; int end = a2[a2.length - 1] & 0xff; for (int k = start; k <= end; ++k) { a1[a1.length - 1] = (byte)k; PdfString s = new PdfString(a1); s.setHexWriting(true); if (code instanceof PdfArray) { addChar(s, ((PdfArray)code).getPdfObject(k - start)); } else if (code instanceof PdfNumber) { int nn = ((PdfNumber)code).intValue() + k - start; addChar(s, new PdfNumber(nn)); } else if (code instanceof PdfString) { PdfString s1 = new PdfString(sout); s1.setHexWriting(true); ++sout[sout.length - 1]; addChar(s, s1); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setWidthPercentage(final float columnWidth[], final Rectangle pageSize) throws DocumentException { if (columnWidth.length != getNumberOfColumns()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("wrong.number.of.columns")); float totalWidth = 0; for (int k = 0; k < columnWidth.length; ++k) totalWidth += columnWidth[k]; widthPercentage = totalWidth / (pageSize.getRight() - pageSize.getLeft()) * 100f; setWidths(columnWidth); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void resetColumnCount(final int newColCount) { if (newColCount <= 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.number.of.columns.in.pdfptable.constructor.must.be.greater.than.zero")); relativeWidths = new float[newColCount]; for (int k = 0; k < newColCount; ++k) relativeWidths[k] = 1; absoluteWidths = new float[relativeWidths.length]; calculateWidths(); currentRow = new PdfPCell[absoluteWidths.length]; totalHeight = 0; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PushbuttonField.java
public void setLayout(int layout) { if (layout < LAYOUT_LABEL_ONLY || layout > LAYOUT_LABEL_OVER_ICON) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("layout.out.of.bounds")); this.layout = layout; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeInter25.java
public static byte[] getBarsInter25(String text) { text = keepNumbers(text); if ((text.length() & 1) != 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.text.length.must.be.even")); byte bars[] = new byte[text.length() * 5 + 7]; int pb = 0; bars[pb++] = 0; bars[pb++] = 0; bars[pb++] = 0; bars[pb++] = 0; int len = text.length() / 2; for (int k = 0; k < len; ++k) { int c1 = text.charAt(k * 2) - '0'; int c2 = text.charAt(k * 2 + 1) - '0'; byte b1[] = BARS[c1]; byte b2[] = BARS[c2]; for (int j = 0; j < 5; ++j) { bars[pb++] = b1[j]; bars[pb++] = b2[j]; } } bars[pb++] = 1; bars[pb++] = 0; bars[pb++] = 0; return bars; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
public void setCode(String code) { if (getCodeType() == Barcode128.CODE128_UCC && code.startsWith("(")) { int idx = 0; StringBuilder ret = new StringBuilder(""); while (idx >= 0) { int end = code.indexOf(')', idx); if (end < 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("badly.formed.ucc.string.1", code)); String sai = code.substring(idx + 1, end); if (sai.length() < 2) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("ai.too.short.1", sai)); int ai = Integer.parseInt(sai); int len = ais.get(ai); if (len == 0) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("ai.not.found.1", sai)); sai = String.valueOf(ai); if (sai.length() == 1) sai = "0" + sai; idx = code.indexOf('(', end); int next = (idx < 0 ? code.length() : idx); ret.append(sai).append(code.substring(end + 1, next)); if (len < 0) { if (idx >= 0) ret.append(FNC1); } else if (next - end - 1 + sai.length() != len) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.ai.length.1", sai)); } super.setCode(ret.toString()); } else super.setCode(code); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfShading.java
public static void throwColorSpaceError() { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("a.tiling.or.shading.pattern.cannot.be.used.as.a.color.space.in.a.shading.pattern")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfShading.java
public static void checkCompatibleColors(BaseColor c1, BaseColor c2) { int type1 = ExtendedColor.getType(c1); int type2 = ExtendedColor.getType(c2); if (type1 != type2) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("both.colors.must.be.of.the.same.type")); if (type1 == ExtendedColor.TYPE_SEPARATION && ((SpotColor)c1).getPdfSpotColor() != ((SpotColor)c2).getPdfSpotColor()) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.spot.color.must.be.the.same.only.the.tint.can.vary")); if (type1 == ExtendedColor.TYPE_PATTERN || type1 == ExtendedColor.TYPE_SHADING) throwColorSpaceError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfShading.java
public void setBBox(float[] bBox) { if (bBox.length != 4) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bbox.must.be.a.4.element.array")); this.bBox = bBox; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncryption.java
public void setCryptoMode(int mode, int kl) { cryptoMode = mode; encryptMetadata = (mode & PdfWriter.DO_NOT_ENCRYPT_METADATA) != PdfWriter.DO_NOT_ENCRYPT_METADATA; embeddedFilesOnly = (mode & PdfWriter.EMBEDDED_FILES_ONLY) == PdfWriter.EMBEDDED_FILES_ONLY; mode &= PdfWriter.ENCRYPTION_MASK; switch (mode) { case PdfWriter.STANDARD_ENCRYPTION_40: encryptMetadata = true; embeddedFilesOnly = false; keyLength = 40; revision = STANDARD_ENCRYPTION_40; break; case PdfWriter.STANDARD_ENCRYPTION_128: embeddedFilesOnly = false; if (kl > 0) keyLength = kl; else keyLength = 128; revision = STANDARD_ENCRYPTION_128; break; case PdfWriter.ENCRYPTION_AES_128: keyLength = 128; revision = AES_128; break; case PdfWriter.ENCRYPTION_AES_256: keyLength = 256; keySize = 32; revision = AES_256; break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("no.valid.encryption.mode")); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPageLabels.java
public void addPageLabel(int page, int numberStyle, String text, int firstPage) { if (page < 1 || firstPage < 1) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("in.a.page.label.the.page.numbers.must.be.greater.or.equal.to.1")); PdfDictionary dic = new PdfDictionary(); if (numberStyle >= 0 && numberStyle < numberingStyle.length) dic.put(PdfName.S, numberingStyle[numberStyle]); if (text != null) dic.put(PdfName.P, new PdfString(text, PdfObject.TEXT_UNICODE)); if (firstPage != 1) dic.put(PdfName.ST, new PdfNumber(firstPage)); map.put(Integer.valueOf(page - 1), dic); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BidiOrder.java
private static void validateTypes(byte[] types) { if (types == null) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("types.is.null")); } for (int i = 0; i < types.length; ++i) { if (types[i] < TYPE_MIN || types[i] > TYPE_MAX) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.type.value.at.1.2", String.valueOf(i), String.valueOf(types[i]))); } } for (int i = 0; i < types.length - 1; ++i) { if (types[i] == B) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("b.type.before.end.of.paragraph.at.index.1", i)); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BidiOrder.java
private static void validateParagraphEmbeddingLevel(byte paragraphEmbeddingLevel) { if (paragraphEmbeddingLevel != -1 && paragraphEmbeddingLevel != 0 && paragraphEmbeddingLevel != 1) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("illegal.paragraph.embedding.level.1", paragraphEmbeddingLevel)); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BidiOrder.java
private static void validateLineBreaks(int[] linebreaks, int textLength) { int prev = 0; for (int i = 0; i < linebreaks.length; ++i) { int next = linebreaks[i]; if (next <= prev) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bad.linebreak.1.at.index.2", String.valueOf(next), String.valueOf(i))); } prev = next; } if (prev != textLength) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("last.linebreak.must.be.at.1", textLength)); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/BaseColor.java
private static void validate(final int value) { if (value < 0 || value > 255) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("color.value.outside.range.0.255")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/WebColors.java
public static BaseColor getRGBColor(String name) throws IllegalArgumentException { int[] c = { 0, 0, 0, 255 }; name = name.toLowerCase(); boolean colorStrWithoutHash = missingHashColorFormat(name); if (name.startsWith("#") || colorStrWithoutHash) { if (!colorStrWithoutHash) { name = name.substring(1); // lop off the # to unify hex parsing. } if (name.length() == 3) { String s = name.substring(0, 1); c[0] = Integer.parseInt(s+s, 16); String s2 = name.substring(1, 2); c[1] = Integer.parseInt(s2+s2, 16); String s3 = name.substring(2); c[2] = Integer.parseInt(s3+s3, 16); return new BaseColor(c[0], c[1], c[2], c[3]); } if (name.length() == 6) { c[0] = Integer.parseInt(name.substring(0, 2), 16); c[1] = Integer.parseInt(name.substring(2, 4), 16); c[2] = Integer.parseInt(name.substring(4), 16); return new BaseColor(c[0], c[1], c[2], c[3]); } throw new IllegalArgumentException(MessageLocalization.getComposedMessage("unknown.color.format.must.be.rgb.or.rrggbb")); } else if (name.startsWith("rgb(")) { StringTokenizer tok = new StringTokenizer(name, "rgb(), \t\r\n\f"); for (int k = 0; k < 3; ++k) { String v = tok.nextToken(); if (v.endsWith("%")) c[k] = Integer.parseInt(v.substring(0, v.length() - 1)) * 255 / 100; else c[k] = Integer.parseInt(v); if (c[k] < 0) c[k] = 0; else if (c[k] > 255) c[k] = 255; } return new BaseColor(c[0], c[1], c[2], c[3]); } if (!NAMES.containsKey(name)) // TODO localize this error message. throw new IllegalArgumentException("Color '" + name + "' not found."); c = NAMES.get(name); return new BaseColor(c[0], c[1], c[2], c[3]); }
3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (Exception ex) { throw new IllegalArgumentException(ex); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
catch (ClassCastException ex) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("you.have.to.consolidate.the.named.destinations.of.your.reader")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/PdfPKCS7.java
catch (IOException e) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object")); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/WebColors.java
public static BaseColor getRGBColor(String name) throws IllegalArgumentException { int[] c = { 0, 0, 0, 255 }; name = name.toLowerCase(); boolean colorStrWithoutHash = missingHashColorFormat(name); if (name.startsWith("#") || colorStrWithoutHash) { if (!colorStrWithoutHash) { name = name.substring(1); // lop off the # to unify hex parsing. } if (name.length() == 3) { String s = name.substring(0, 1); c[0] = Integer.parseInt(s+s, 16); String s2 = name.substring(1, 2); c[1] = Integer.parseInt(s2+s2, 16); String s3 = name.substring(2); c[2] = Integer.parseInt(s3+s3, 16); return new BaseColor(c[0], c[1], c[2], c[3]); } if (name.length() == 6) { c[0] = Integer.parseInt(name.substring(0, 2), 16); c[1] = Integer.parseInt(name.substring(2, 4), 16); c[2] = Integer.parseInt(name.substring(4), 16); return new BaseColor(c[0], c[1], c[2], c[3]); } throw new IllegalArgumentException(MessageLocalization.getComposedMessage("unknown.color.format.must.be.rgb.or.rrggbb")); } else if (name.startsWith("rgb(")) { StringTokenizer tok = new StringTokenizer(name, "rgb(), \t\r\n\f"); for (int k = 0; k < 3; ++k) { String v = tok.nextToken(); if (v.endsWith("%")) c[k] = Integer.parseInt(v.substring(0, v.length() - 1)) * 255 / 100; else c[k] = Integer.parseInt(v); if (c[k] < 0) c[k] = 0; else if (c[k] > 255) c[k] = 255; } return new BaseColor(c[0], c[1], c[2], c[3]); } if (!NAMES.containsKey(name)) // TODO localize this error message. throw new IllegalArgumentException("Color '" + name + "' not found."); c = NAMES.get(name); return new BaseColor(c[0], c[1], c[2], c[3]); }
3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Jpeg.java
catch(IllegalArgumentException e) { // ignore ICC profile if it's invalid. }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Version.java
catch (IllegalArgumentException iae) { throw iae; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/HtmlUtilities.java
catch(IllegalArgumentException iae) { return null; }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Version.java
catch (IllegalArgumentException iae) { throw iae; }
0
runtime (Domain) IllegalPathStateException
public class IllegalPathStateException extends RuntimeException {

    private static final long serialVersionUID = -5158084205220481094L;

    public IllegalPathStateException() {
    }

    public IllegalPathStateException(String s) {
        super(s);
    }

}
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
void checkBuf(int pointCount, boolean checkMove) { if (checkMove && typeSize == 0) { // awt.20A=First segment should be SEG_MOVETO type throw new IllegalPathStateException(Messages.getString("awt.20A")); //$NON-NLS-1$ } if (typeSize == types.length) { byte tmp[] = new byte[typeSize + BUFFER_CAPACITY]; System.arraycopy(types, 0, tmp, 0, typeSize); types = tmp; } if (pointSize + pointCount > points.length) { float tmp[] = new float[pointSize + Math.max(BUFFER_CAPACITY * 2, pointCount)]; System.arraycopy(points, 0, tmp, 0, pointSize); points = tmp; } }
0 0 0 0 0
runtime (Domain) IllegalPdfSyntaxException
public class IllegalPdfSyntaxException extends IllegalArgumentException {

	/** Serial version ID */
	private static final long serialVersionUID = -643024246596031671L;

	/**
	 * Creates an exception saying the PDF syntax isn't correct.
	 * @param	message	some extra info about the exception
	 */
	public IllegalPdfSyntaxException(String message) {
		super(message);
	}
}
25
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void moveTo(final float x, final float y) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x).append(' ').append(y).append(" m").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void lineTo(final float x, final float y) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x).append(' ').append(y).append(" l").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void curveTo(final float x1, final float y1, final float x2, final float y2, final float x3, final float y3) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x1).append(' ').append(y1).append(' ').append(x2).append(' ').append(y2).append(' ').append(x3).append(' ').append(y3).append(" c").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void curveTo(final float x2, final float y2, final float x3, final float y3) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x2).append(' ').append(y2).append(' ').append(x3).append(' ').append(y3).append(" v").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void curveFromTo(final float x1, final float y1, final float x3, final float y3) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x1).append(' ').append(y1).append(' ').append(x3).append(' ').append(y3).append(" y").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void rectangle(final float x, final float y, final float w, final float h) { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append(x).append(' ').append(y).append(' ').append(w).append(' ').append(h).append(" re").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void closePath() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("h").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void newPath() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("n").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void stroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("S").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void closePathStroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("s").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void fill() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("f").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void eoFill() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("f*").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void fillStroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("B").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void closePathFillStroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("b").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void eoFillStroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("B*").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void closePathEoFillStroke() { if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("path.construction.operator.inside.text.object")); } } content.append("b*").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
protected void beginText(boolean restoreTM) { if (inText) { if (isTagged()) { } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.begin.end.text.operators")); } } else { inText = true; content.append("BT").append_i(separator); if (restoreTM) { float xTLM = state.xTLM; float tx = state.tx; setTextMatrix(state.aTLM, state.bTLM, state.cTLM, state.dTLM, state.tx, state.yTLM); state.xTLM = xTLM; state.tx = tx; } else { state.xTLM = 0; state.yTLM = 0; state.tx = 0; } if (isTagged()) { try { restoreColor(); } catch (IOException ioe) { } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void endText() { if (!inText) { if (isTagged()) { } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.begin.end.text.operators")); } } else { inText = false; content.append("ET").append_i(separator); if (isTagged()) { try { restoreColor(); } catch (IOException ioe) { } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void restoreState() { if (inText && isTagged()) { endText(); } content.append("Q").append_i(separator); int idx = stateList.size() - 1; if (idx < 0) throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.save.restore.state.operators")); state = stateList.get(idx); stateList.remove(idx); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void endLayer() { int n = 1; if (layerDepth != null && !layerDepth.isEmpty()) { n = layerDepth.get(layerDepth.size() - 1).intValue(); layerDepth.remove(layerDepth.size() - 1); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.layer.operators")); } while (n-- > 0) content.append("EMC").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void endMarkedContentSequence() { if (getMcDepth() == 0) { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.begin.end.marked.content.operators")); } int contentSize = content.size(); setMcDepth(getMcDepth() - 1); content.append("EMC").append_i(separator); markedContentSize += content.size() - contentSize; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void sanityCheck() { if (getMcDepth() != 0) { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.marked.content.operators")); } if (inText) { if (isTagged()) { endText(); } else { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.begin.end.text.operators")); } } if (layerDepth != null && !layerDepth.isEmpty()) { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.layer.operators")); } if (!stateList.isEmpty()) { throw new IllegalPdfSyntaxException(MessageLocalization.getComposedMessage("unbalanced.save.restore.state.operators")); } }
0 0 0 0 0
runtime (Lib) IllegalStateException 25
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ChapterAutoNumber.java
Override public Section addSection(final String title) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } return addSection(title, 2); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/ChapterAutoNumber.java
Override public Section addSection(final Paragraph title) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } return addSection(title, 2); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/ArrayRandomAccessSource.java
public int get(long offset, byte[] bytes, int off, int len) { if (array == null) throw new IllegalStateException("Already closed"); if (offset >= array.length) return -1; if (offset + len > array.length) len = (int)(array.length - offset); System.arraycopy(array, (int)offset, bytes, off, len); return len; }
// 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/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/PdfSignatureAppearance.java
public PdfTemplate getAppearance() throws DocumentException { if (isInvisible()) { PdfTemplate t = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(0, 0)); writer.addDirectTemplateSimple(t, null); return t; } if (app[0] == null) { PdfTemplate t = app[0] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n0")); t.setLiteral("% DSBlank\n"); } if (app[1] == null && !acro6Layers) { PdfTemplate t = app[1] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n1")); t.setLiteral(questionMark); } if (app[2] == null) { String text; if (layer2Text == null) { StringBuilder buf = new StringBuilder(); buf.append("Digitally signed by "); String name = null; X500Name x500name = CertificateInfo.getSubjectFields((X509Certificate)signCertificate); if (x500name != null) { name = x500name.getField("CN"); if (name == null) name = x500name.getField("E"); } if (name == null) name = ""; buf.append(name).append('\n'); SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); buf.append("Date: ").append(sd.format(signDate.getTime())); if (reason != null) buf.append('\n').append("Reason: ").append(reason); if (location != null) buf.append('\n').append("Location: ").append(location); text = buf.toString(); } else text = layer2Text; PdfTemplate t = app[2] = new PdfTemplate(writer); t.setBoundingBox(rect); writer.addDirectTemplateSimple(t, new PdfName("n2")); if (image != null) { if (imageScale == 0) { t.addImage(image, rect.getWidth(), 0, 0, rect.getHeight(), 0, 0); } else { float usableScale = imageScale; if (imageScale < 0) usableScale = Math.min(rect.getWidth() / image.getWidth(), rect.getHeight() / image.getHeight()); float w = image.getWidth() * usableScale; float h = image.getHeight() * usableScale; float x = (rect.getWidth() - w) / 2; float y = (rect.getHeight() - h) / 2; t.addImage(image, w, 0, 0, h, x, y); } } Font font; if (layer2Font == null) font = new Font(); else font = new Font(layer2Font); float size = font.getSize(); Rectangle dataRect = null; Rectangle signatureRect = null; if (renderingMode == RenderingMode.NAME_AND_DESCRIPTION || renderingMode == RenderingMode.GRAPHIC_AND_DESCRIPTION && this.signatureGraphic != null) { // origin is the bottom-left signatureRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() / 2 - MARGIN, rect.getHeight() - MARGIN); dataRect = new Rectangle( rect.getWidth() / 2 + MARGIN / 2, MARGIN, rect.getWidth() - MARGIN / 2, rect.getHeight() - MARGIN); if (rect.getHeight() > rect.getWidth()) { signatureRect = new Rectangle( MARGIN, rect.getHeight() / 2, rect.getWidth() - MARGIN, rect.getHeight()); dataRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, rect.getHeight() / 2 - MARGIN); } } else if (renderingMode == RenderingMode.GRAPHIC) { if (signatureGraphic == null) { throw new IllegalStateException(MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.only")); } signatureRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, // take all space available rect.getHeight() - MARGIN); } else { dataRect = new Rectangle( MARGIN, MARGIN, rect.getWidth() - MARGIN, rect.getHeight() * (1 - TOP_SECTION) - MARGIN); } switch (renderingMode) { case NAME_AND_DESCRIPTION: String signedBy = CertificateInfo.getSubjectFields((X509Certificate)signCertificate).getField("CN"); if (signedBy == null) signedBy = CertificateInfo.getSubjectFields((X509Certificate)signCertificate).getField("E"); if (signedBy == null) signedBy = ""; Rectangle sr2 = new Rectangle(signatureRect.getWidth() - MARGIN, signatureRect.getHeight() - MARGIN ); float signedSize = ColumnText.fitText(font, signedBy, sr2, -1, runDirection); ColumnText ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(new Phrase(signedBy, font), signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), signedSize, Element.ALIGN_LEFT); ct2.go(); break; case GRAPHIC_AND_DESCRIPTION: if (signatureGraphic == null) { throw new IllegalStateException(MessageLocalization.getComposedMessage("a.signature.image.should.be.present.when.rendering.mode.is.graphic.and.description")); } ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), 0, Element.ALIGN_RIGHT); Image im = Image.getInstance(signatureGraphic); im.scaleToFit(signatureRect.getWidth(), signatureRect.getHeight()); Paragraph p = new Paragraph(); // must calculate the point to draw from to make image appear in middle of column float x = 0; // experimentation found this magic number to counteract Adobe's signature graphic, which // offsets the y co-ordinate by 15 units float y = -im.getScaledHeight() + 15; x = x + (signatureRect.getWidth() - im.getScaledWidth()) / 2; y = y - (signatureRect.getHeight() - im.getScaledHeight()) / 2; p.add(new Chunk(im, x + (signatureRect.getWidth() - im.getScaledWidth()) / 2, y, false)); ct2.addElement(p); ct2.go(); break; case GRAPHIC: ct2 = new ColumnText(t); ct2.setRunDirection(runDirection); ct2.setSimpleColumn(signatureRect.getLeft(), signatureRect.getBottom(), signatureRect.getRight(), signatureRect.getTop(), 0, Element.ALIGN_RIGHT); im = Image.getInstance(signatureGraphic); im.scaleToFit(signatureRect.getWidth(), signatureRect.getHeight()); p = new Paragraph(signatureRect.getHeight()); // must calculate the point to draw from to make image appear in middle of column x = (signatureRect.getWidth() - im.getScaledWidth()) / 2; y = (signatureRect.getHeight() - im.getScaledHeight()) / 2; p.add(new Chunk(im, x, y, false)); ct2.addElement(p); ct2.go(); break; default: } if(renderingMode != RenderingMode.GRAPHIC) { if (size <= 0) { Rectangle sr = new Rectangle(dataRect.getWidth(), dataRect.getHeight()); size = ColumnText.fitText(font, text, sr, 12, runDirection); } ColumnText ct = new ColumnText(t); ct.setRunDirection(runDirection); ct.setSimpleColumn(new Phrase(text, font), dataRect.getLeft(), dataRect.getBottom(), dataRect.getRight(), dataRect.getTop(), size, Element.ALIGN_LEFT); ct.go(); } } if (app[3] == null && !acro6Layers) { PdfTemplate t = app[3] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(100, 100)); writer.addDirectTemplateSimple(t, new PdfName("n3")); t.setLiteral("% DSBlank\n"); } if (app[4] == null && !acro6Layers) { PdfTemplate t = app[4] = new PdfTemplate(writer); t.setBoundingBox(new Rectangle(0, rect.getHeight() * (1 - TOP_SECTION), rect.getRight(), rect.getTop())); writer.addDirectTemplateSimple(t, new PdfName("n4")); Font font; if (layer2Font == null) font = new Font(); else font = new Font(layer2Font); //float size = font.getSize(); String text = "Signature Not Verified"; if (layer4Text != null) text = layer4Text; Rectangle sr = new Rectangle(rect.getWidth() - 2 * MARGIN, rect.getHeight() * TOP_SECTION - 2 * MARGIN); float size = ColumnText.fitText(font, text, sr, 15, runDirection); ColumnText ct = new ColumnText(t); ct.setRunDirection(runDirection); ct.setSimpleColumn(new Phrase(text, font), MARGIN, 0, rect.getWidth() - MARGIN, rect.getHeight() - MARGIN, size, Element.ALIGN_LEFT); ct.go(); } int rotation = writer.reader.getPageRotation(page); Rectangle rotated = new Rectangle(rect); int n = rotation; while (n > 0) { rotated = rotated.rotate(); n -= 90; } if (frm == null) { frm = new PdfTemplate(writer); frm.setBoundingBox(rotated); writer.addDirectTemplateSimple(frm, new PdfName("FRM")); float scale = Math.min(rect.getWidth(), rect.getHeight()) * 0.9f; float x = (rect.getWidth() - scale) / 2; float y = (rect.getHeight() - scale) / 2; scale /= 100; if (rotation == 90) frm.concatCTM(0, 1, -1, 0, rect.getHeight(), 0); else if (rotation == 180) frm.concatCTM(-1, 0, 0, -1, rect.getWidth(), rect.getHeight()); else if (rotation == 270) frm.concatCTM(0, -1, 1, 0, 0, rect.getWidth()); frm.addTemplate(app[0], 0, 0); if (!acro6Layers) frm.addTemplate(app[1], scale, 0, 0, scale, x, y); frm.addTemplate(app[2], 0, 0); if (!acro6Layers) { frm.addTemplate(app[3], scale, 0, 0, scale, x, y); frm.addTemplate(app[4], 0, 0); } } PdfTemplate napp = new PdfTemplate(writer); napp.setBoundingBox(rotated); writer.addDirectTemplateSimple(napp, null); napp.addTemplate(frm, 0, 0); return napp; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void replacePage(PdfReader r, int pageImported, int pageReplaced) { PdfDictionary pageN = reader.getPageN(pageReplaced); if (pagesToContent.containsKey(pageN)) throw new IllegalStateException(MessageLocalization.getComposedMessage("this.page.cannot.be.replaced.new.content.was.already.added")); PdfImportedPage p = getImportedPage(r, pageImported); PdfDictionary dic2 = reader.getPageNRelease(pageReplaced); dic2.remove(PdfName.RESOURCES); dic2.remove(PdfName.CONTENTS); moveRectangle(dic2, r, pageImported, PdfName.MEDIABOX, "media"); moveRectangle(dic2, r, pageImported, PdfName.CROPBOX, "crop"); moveRectangle(dic2, r, pageImported, PdfName.TRIMBOX, "trim"); moveRectangle(dic2, r, pageImported, PdfName.ARTBOX, "art"); moveRectangle(dic2, r, pageImported, PdfName.BLEEDBOX, "bleed"); dic2.put(PdfName.ROTATE, new PdfNumber(r.getPageRotation(pageImported))); PdfContentByte cb = getOverContent(pageReplaced); cb.addTemplate(p, 0, 0); PageStamp ps = pagesToContent.get(pageN); ps.replacePoint = ps.over.getInternalBuffer().size(); }
// 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/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/MarkedContentInfo.java
public int getMcid(){ PdfNumber id = dictionary.getAsNumber(PdfName.MCID); if (id == null) throw new IllegalStateException("MarkedContentInfo does not contain MCID"); return id.intValue(); }
// 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/BarcodePDF417.java
private void macroCodes() { if (macroSegmentId < 0) { throw new IllegalStateException(MessageLocalization.getComposedMessage("macrosegmentid.must.be.gt.eq.0")); } if (macroSegmentId >= macroSegmentCount) { throw new IllegalStateException(MessageLocalization.getComposedMessage("macrosegmentid.must.be.lt.macrosemgentcount")); } if (macroSegmentCount < 1) { throw new IllegalStateException(MessageLocalization.getComposedMessage("macrosemgentcount.must.be.gt.0")); } macroIndex = cwPtr; codewords[cwPtr++] = MACRO_SEGMENT_ID; append(macroSegmentId, 5); if (macroFileId != null) { append(macroFileId); } if (macroSegmentId >= macroSegmentCount-1) { codewords[cwPtr++] = MACRO_LAST_SEGMENT; } }
// 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/Section.java
Override public void add(final int index, final Element element) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } try { if (element.isNestable()) { super.add(index, element); } else { throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
Override public boolean add(final Element element) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } try { if (element.type() == Element.SECTION) { Section section = (Section) element; section.setNumbers(++subsections, numbers); return super.add(section); } else if (element instanceof MarkedSection && ((MarkedObject)element).element.type() == Element.SECTION) { MarkedSection mo = (MarkedSection)element; Section section = (Section)mo.element; section.setNumbers(++subsections, numbers); return super.add(mo); } else if (element.isNestable()) { return super.add(element); } else { throw new ClassCastException(MessageLocalization.getComposedMessage("you.can.t.add.a.1.to.a.section", element.getClass().getName())); } } catch(ClassCastException cce) { throw new ClassCastException(MessageLocalization.getComposedMessage("insertion.of.illegal.element.1", cce.getMessage())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Section.java
public Section addSection(final float indentation, final Paragraph title, final int numberDepth) { if (isAddedCompletely()) { throw new IllegalStateException(MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document")); } Section section = new Section(title, numberDepth); section.setIndentation(indentation); add(section); return section; }
0 0 0 0 0
unknown (Lib) IndexOutOfBoundsException 7
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfIndirectReference getPageReference(int page) { --page; if (page < 0) throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.page.number.must.be.gt.eq.1")); PdfIndirectReference ref; if (page < pageReferences.size()) { ref = pageReferences.get(page); if (ref == null) { ref = body.getPdfIndirectReference(); pageReferences.set(page, ref); } } else { int empty = page - pageReferences.size(); for (int k = 0; k < empty; ++k) pageReferences.add(null); ref = body.getPdfIndirectReference(); pageReferences.add(ref); } return ref; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontSelector.java
public Phrase process(String text) { int fsize = fonts.size(); if (fsize == 0) throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("no.font.is.defined")); char cc[] = text.toCharArray(); int len = cc.length; StringBuffer sb = new StringBuffer(); Font font = null; int lastidx = -1; Phrase ret = new Phrase(); for (int k = 0; k < len; ++k) { char c = cc[k]; if (c == '\n' || c == '\r') { sb.append(c); continue; } if (Utilities.isSurrogatePair(cc, k)) { int u = Utilities.convertToUtf32(cc, k); for (int f = 0; f < fsize; ++f) { font = fonts.get(f); if (font.getBaseFont().charExists(u)) { if (lastidx != f) { if (sb.length() > 0 && lastidx != -1) { Chunk ck = new Chunk(sb.toString(), fonts.get(lastidx)); ret.add(ck); sb.setLength(0); } lastidx = f; } sb.append(c); sb.append(cc[++k]); break; } } } else { for (int f = 0; f < fsize; ++f) { font = fonts.get(f); if (font.getBaseFont().charExists(c)) { if (lastidx != f) { if (sb.length() > 0 && lastidx != -1) { Chunk ck = new Chunk(sb.toString(), fonts.get(lastidx)); ret.add(ck); sb.setLength(0); } lastidx = f; } sb.append(c); break; } } } } if (sb.length() > 0) { Chunk ck = new Chunk(sb.toString(), fonts.get(lastidx == -1 ? 0 : lastidx)); ret.add(ck); } return ret; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
private void textCompaction(byte[] input, int start, int length) { int dest[] = new int[ABSOLUTE_MAX_TEXT_SIZE * 2]; int mode = ALPHA; int ptr = 0; int fullBytes = 0; int v = 0; int k; int size; length += start; for (k = start; k < length; ++k) { v = getTextTypeAndValue(input, length, k); if ((v & mode) != 0) { dest[ptr++] = v & 0xff; continue; } if ((v & ISBYTE) != 0) { if ((ptr & 1) != 0) { //add a padding word dest[ptr++] = PAL; mode = (mode & PUNCTUATION) != 0 ? ALPHA : mode; } dest[ptr++] = BYTESHIFT; dest[ptr++] = v & 0xff; fullBytes += 2; continue; } switch (mode) { case ALPHA: if ((v & LOWER) != 0) { dest[ptr++] = LL; dest[ptr++] = v & 0xff; mode = LOWER; } else if ((v & MIXED) != 0) { dest[ptr++] = ML; dest[ptr++] = v & 0xff; mode = MIXED; } else if ((getTextTypeAndValue(input, length, k + 1) & getTextTypeAndValue(input, length, k + 2) & PUNCTUATION) != 0) { dest[ptr++] = ML; dest[ptr++] = PL; dest[ptr++] = v & 0xff; mode = PUNCTUATION; } else { dest[ptr++] = PS; dest[ptr++] = v & 0xff; } break; case LOWER: if ((v & ALPHA) != 0) { if ((getTextTypeAndValue(input, length, k + 1) & getTextTypeAndValue(input, length, k + 2) & ALPHA) != 0) { dest[ptr++] = ML; dest[ptr++] = AL; mode = ALPHA; } else { dest[ptr++] = AS; } dest[ptr++] = v & 0xff; } else if ((v & MIXED) != 0) { dest[ptr++] = ML; dest[ptr++] = v & 0xff; mode = MIXED; } else if ((getTextTypeAndValue(input, length, k + 1) & getTextTypeAndValue(input, length, k + 2) & PUNCTUATION) != 0) { dest[ptr++] = ML; dest[ptr++] = PL; dest[ptr++] = v & 0xff; mode = PUNCTUATION; } else { dest[ptr++] = PS; dest[ptr++] = v & 0xff; } break; case MIXED: if ((v & LOWER) != 0) { dest[ptr++] = LL; dest[ptr++] = v & 0xff; mode = LOWER; } else if ((v & ALPHA) != 0) { dest[ptr++] = AL; dest[ptr++] = v & 0xff; mode = ALPHA; } else if ((getTextTypeAndValue(input, length, k + 1) & getTextTypeAndValue(input, length, k + 2) & PUNCTUATION) != 0) { dest[ptr++] = PL; dest[ptr++] = v & 0xff; mode = PUNCTUATION; } else { dest[ptr++] = PS; dest[ptr++] = v & 0xff; } break; case PUNCTUATION: dest[ptr++] = PAL; mode = ALPHA; --k; break; } } if ((ptr & 1) != 0) dest[ptr++] = PS; size = (ptr + fullBytes) / 2; if (size + cwPtr > MAX_DATA_CODEWORDS) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } length = ptr; ptr = 0; while (ptr < length) { v = dest[ptr++]; if (v >= 30) { codewords[cwPtr++] = v; codewords[cwPtr++] = dest[ptr++]; } else codewords[cwPtr++] = v * 30 + dest[ptr++]; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
private void numberCompaction(byte[] input, int start, int length) { int full = length / 44 * 15; int size = length % 44; int k; if (size == 0) size = full; else size = full + size / 3 + 1; if (size + cwPtr > MAX_DATA_CODEWORDS) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } length += start; for (k = start; k < length; k += 44) { size = length - k < 44 ? length - k : 44; basicNumberCompaction(input, k, size); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
void byteCompaction(int start, int length) { int k, j; int size = length / 6 * 5 + length % 6; if (size + cwPtr > MAX_DATA_CODEWORDS) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } length += start; for (k = start; k < length; k += 6) { size = length - k < 44 ? length - k : 6; if (size < 6) { for (j = 0; j < size; ++j) codewords[cwPtr++] = text[k + j] & 0xff; } else { byteCompaction6(k); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
public void paintCode() { int maxErr, lenErr, tot, pad; if ((options & PDF417_USE_RAW_CODEWORDS) != 0) { if (lenCodewords > MAX_DATA_CODEWORDS || lenCodewords < 1 || lenCodewords != codewords[0]) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.codeword.size")); } } else { if (text == null) throw new NullPointerException(MessageLocalization.getComposedMessage("text.cannot.be.null")); if (text.length > ABSOLUTE_MAX_TEXT_SIZE) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } segmentList = new SegmentList(); breakString(); //dumpList(); assemble(); segmentList = null; codewords[0] = lenCodewords = cwPtr; } maxErr = maxPossibleErrorLevel(MAX_DATA_CODEWORDS + 2 - lenCodewords); if ((options & PDF417_USE_ERROR_LEVEL) == 0) { if (lenCodewords < 41) errorLevel = 2; else if (lenCodewords < 161) errorLevel = 3; else if (lenCodewords < 321) errorLevel = 4; else errorLevel = 5; } if (errorLevel < 0) errorLevel = 0; else if (errorLevel > maxErr) errorLevel = maxErr; if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) codeRows = 90; lenErr = 2 << errorLevel; boolean fixedColumn = (options & PDF417_FIXED_ROWS) == 0; boolean skipRowColAdjust = false; tot = lenCodewords + lenErr; if ((options & PDF417_FIXED_RECTANGLE) != 0) { tot = codeColumns * codeRows; if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } if (tot < lenCodewords + lenErr) tot = lenCodewords + lenErr; else skipRowColAdjust = true; } else if ((options & (PDF417_FIXED_COLUMNS | PDF417_FIXED_ROWS)) == 0) { double c, b; fixedColumn = true; if (aspectRatio < 0.001) aspectRatio = 0.001f; else if (aspectRatio > 1000) aspectRatio = 1000; b = 73 * aspectRatio - 4; c = (-b + Math.sqrt(b * b + 4 * 17 * aspectRatio * (lenCodewords + lenErr) * yHeight)) / (2 * 17 * aspectRatio); codeColumns = (int)(c + 0.5); if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; } if (!skipRowColAdjust) { if (fixedColumn) { codeRows = (tot - 1) / codeColumns + 1; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) { codeRows = 90; codeColumns = (tot - 1) / 90 + 1; } } else { codeColumns = (tot - 1) / codeRows + 1; if (codeColumns > 30) { codeColumns = 30; codeRows = (tot - 1) / 30 + 1; } } tot = codeRows * codeColumns; } if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } errorLevel = maxPossibleErrorLevel(tot - lenCodewords); lenErr = 2 << errorLevel; pad = tot - lenErr - lenCodewords; if ((options & PDF417_USE_MACRO) != 0) { // the padding comes before the control block System.arraycopy(codewords, macroIndex, codewords, macroIndex + pad, pad); cwPtr = lenCodewords + pad; while (pad-- != 0) codewords[macroIndex++] = TEXT_MODE; } else { cwPtr = lenCodewords; while (pad-- != 0) codewords[cwPtr++] = TEXT_MODE; } codewords[0] = lenCodewords = cwPtr; calculateErrorCorrection(lenCodewords); lenCodewords = tot; outPaintCode(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ByteBuffer.java
public void setSize(int size) { if (size > count || size < 0) throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.new.size.must.be.positive.and.lt.eq.of.the.current.size")); count = size; }
0 0 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfName.java
catch (IndexOutOfBoundsException e) { // empty on purpose }
0 0
checked (Domain) InlineImageParseException
public static class InlineImageParseException extends IOException{

		private static final long serialVersionUID = 233760879000268548L;

		public InlineImageParseException(String message) {
            super(message);
        }

    }
3
            
// 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"); }
0 0 0 0 0
unknown (Lib) InternalError 10
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/RectangularShape.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Dimension2D.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Point2D.java
Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
Override public Object clone() { try { GeneralPath p = (GeneralPath) super.clone(); p.types = types.clone(); p.points = points.clone(); return p; } catch (CloneNotSupportedException e) { throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
Override public Object clone() { try { LongHashtable t = (LongHashtable)super.clone(); t.table = new Entry[table.length]; for (int i = table.length ; i-- > 0 ; ) { t.table[i] = table[i] != null ? (Entry)table[i].clone() : null; } return t; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/IntHashtable.java
Override public Object clone() { try { IntHashtable t = (IntHashtable)super.clone(); t.table = new Entry[table.length]; for (int i = table.length ; i-- > 0 ; ) { t.table[i] = table[i] != null ? (Entry)table[i].clone() : null; } return t; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } }
10
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/RectangularShape.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Dimension2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Point2D.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
catch (CloneNotSupportedException e) { throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/IntHashtable.java
catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }
0 0 0 0
unknown (Lib) InterruptedException 0 0 2
            
// 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); }
3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (InterruptedException e) { // empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Image.java
catch (InterruptedException e) { throw new IOException(MessageLocalization.getComposedMessage("java.awt.image.interrupted.waiting.for.pixels")); }
0
unknown (Lib) InvalidKeyException 0 0 1 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
catch(InvalidKeyException e){ cipher.init(1,x509certificate.getPublicKey()); }
0 0
checked (Domain) InvalidPdfException
public class InvalidPdfException extends IOException {

	/** a serial version UID */
	private static final long serialVersionUID = -2319614911517026938L;
	private final Throwable cause;

	/**
	 * Creates an instance with a message and no cause
	 * @param	message	the reason why the document isn't a PDF document according to iText.
	 */
	public InvalidPdfException(String message) {
		this(message, null);
	}	
	
	/**
	 * Creates an exception with a message and a cause
	 * @param message	the reason why the document isn't a PDF document according to iText. 
	 * @param cause the cause of the exception, if any
	 */
	public InvalidPdfException(String message, Throwable cause){
		super(message);
		this.cause = cause;
	}
	
	/**
	 * This method is included (instead of using super(message, cause) in the constructors) to support backwards compatabilty with
	 * JDK 1.5, which did not have cause constructors for Throwable
	 * @return the cause of this exception
	 */
	public Throwable getCause() {
		return cause;
	}
}
25
            
// 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/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 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 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 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]; } }
4
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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())); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne){ throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
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); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
catch (Exception ne) { throw new InvalidPdfException(MessageLocalization.getComposedMessage("rebuild.failed.1.original.message.2", ne.getMessage(), e.getMessage()), ne); }
0 0 0 0
unknown (Lib) MalformedURLException 0 0 5
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Utilities.java
public static URL toURL(final String filename) throws MalformedURLException { try { return new URL(filename); } catch (Exception e) { return new File(filename).toURI().toURL(); } }
// 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(); } } }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
catch (MalformedURLException e) { LOGGER.info("Skipped CRL url (malformed): " + url); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/Anchor.java
catch(MalformedURLException mue) { return null; }
0 0
unknown (Lib) MapFailedException 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); } }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/MappedChannelRandomAccessSource.java
catch (IOException e){ if (exceptionIsMapFailureException(e)) throw new MapFailedException(e); }
0 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/io/RandomAccessSourceFactory.java
catch (MapFailedException e){ return new RAFRandomAccessSource(raf); }
0 0
unknown (Lib) MissingResourceException 0 0 0 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/misc/Messages.java
catch (MissingResourceException e) { return "Missing message: " + msg; //$NON-NLS-1$ }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/misc/Messages.java
catch (MissingResourceException e) { }
0 0
unknown (Lib) NoSuchAlgorithmException 4
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/BouncyCastleDigest.java
public MessageDigest getMessageDigest(String hashAlgorithm) throws GeneralSecurityException { String oid = DigestAlgorithms.getAllowedDigests(hashAlgorithm); if (oid == null) throw new NoSuchAlgorithmException(hashAlgorithm); if (oid.equals("1.2.840.113549.2.2")) { //MD2 return new MD2.Digest(); } else if (oid.equals("1.2.840.113549.2.5")) { //MD5 return new MD5.Digest(); } else if (oid.equals("1.3.14.3.2.26")) { //SHA1 return new SHA1.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.4")) { //SHA224 return new SHA224.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.1")) { //SHA256 return new SHA256.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.2")) { //SHA384 return new SHA384.Digest(); } else if (oid.equals("2.16.840.1.101.3.4.2.3")) { //SHA512 return new SHA512.Digest(); } else if (oid.equals("1.3.36.3.2.2")) { //RIPEMD128 return new RIPEMD128.Digest(); } else if (oid.equals("1.3.36.3.2.1")) { //RIPEMD160 return new RIPEMD160.Digest(); } else if (oid.equals("1.3.36.3.2.3")) { //RIPEMD256 return new RIPEMD256.Digest(); } else if (oid.equals("1.2.643.2.2.9")) { //GOST3411 return new GOST3411.Digest(); } throw new NoSuchAlgorithmException(hashAlgorithm); //shouldn't get here }
0 5
            
// 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
private static byte[] hashBytesSha1(byte[] b) throws NoSuchAlgorithmException { MessageDigest sh = MessageDigest.getInstance("SHA1"); return sh.digest(b); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/DigestAlgorithms.java
public static MessageDigest getMessageDigestFromOid(String digestOid, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { return getMessageDigest(getDigest(digestOid), provider); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/DigestAlgorithms.java
public static MessageDigest getMessageDigest(String hashAlgorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { if (provider == null || provider.startsWith("SunPKCS11") || provider.startsWith("SunMSCAPI")) return MessageDigest.getInstance(DigestAlgorithms.normalizeDigestName(hashAlgorithm)); else return MessageDigest.getInstance(hashAlgorithm, provider); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPublicKeySecurityHandler.java
catch (NoSuchAlgorithmException e) { seed = SecureRandom.getSeed(SEED_LENGTH); }
0 0
unknown (Lib) NoSuchElementException 16
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/FlatteningPathIterator.java
public int currentSegment(float[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4Bx")); //$NON-NLS-1$ } evaluate(); int type = bufType; if (type != SEG_CLOSE) { coords[0] = (float)px; coords[1] = (float)py; if (type != SEG_MOVETO) { type = SEG_LINETO; } } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/FlatteningPathIterator.java
public int currentSegment(double[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } evaluate(); int type = bufType; if (type != SEG_CLOSE) { coords[0] = px; coords[1] = py; if (type != SEG_MOVETO) { type = SEG_LINETO; } } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Rectangle2D.java
public int currentSegment(double[] coords) { if (isDone()) { throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } if (index == 5) { return SEG_CLOSE; } int type; if (index == 0) { type = SEG_MOVETO; coords[0] = x; coords[1] = y; } else { type = SEG_LINETO; switch(index) { case 1: coords[0] = x + width; coords[1] = y; break; case 2: coords[0] = x + width; coords[1] = y + height; break; case 3: coords[0] = x; coords[1] = y + height; break; case 4: coords[0] = x; coords[1] = y; break; } } if (t != null) { t.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Rectangle2D.java
public int currentSegment(float[] coords) { if (isDone()) { throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } if (index == 5) { return SEG_CLOSE; } int type; if (index == 0) { coords[0] = (float)x; coords[1] = (float)y; type = SEG_MOVETO; } else { type = SEG_LINETO; switch(index) { case 1: coords[0] = (float)(x + width); coords[1] = (float)y; break; case 2: coords[0] = (float)(x + width); coords[1] = (float)(y + height); break; case 3: coords[0] = (float)x; coords[1] = (float)(y + height); break; case 4: coords[0] = (float)x; coords[1] = (float)y; break; } } if (t != null) { t.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
public int currentSegment(double[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; if (index == 0) { type = SEG_MOVETO; coords[0] = x1; coords[1] = y1; } else { type = SEG_LINETO; coords[0] = x2; coords[1] = y2; } if (t != null) { t.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/Line2D.java
public int currentSegment(float[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; if (index == 0) { type = SEG_MOVETO; coords[0] = (float)x1; coords[1] = (float)y1; } else { type = SEG_LINETO; coords[0] = (float)x2; coords[1] = (float)y2; } if (t != null) { t.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
public int currentSegment(double[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; int count; if (index == 0) { type = SEG_MOVETO; coords[0] = c.getX1(); coords[1] = c.getY1(); count = 1; } else { type = SEG_QUADTO; coords[0] = c.getCtrlX(); coords[1] = c.getCtrlY(); coords[2] = c.getX2(); coords[3] = c.getY2(); count = 2; } if (t != null) { t.transform(coords, 0, coords, 0, count); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/QuadCurve2D.java
public int currentSegment(float[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; int count; if (index == 0) { type = SEG_MOVETO; coords[0] = (float)c.getX1(); coords[1] = (float)c.getY1(); count = 1; } else { type = SEG_QUADTO; coords[0] = (float)c.getCtrlX(); coords[1] = (float)c.getCtrlY(); coords[2] = (float)c.getX2(); coords[3] = (float)c.getY2(); count = 2; } if (t != null) { t.transform(coords, 0, coords, 0, count); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
public int currentSegment(double[] coords) { if (isDone()) { throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; int count; if (index == 0) { type = SEG_MOVETO; coords[0] = c.getX1(); coords[1] = c.getY1(); count = 1; } else { type = SEG_CUBICTO; coords[0] = c.getCtrlX1(); coords[1] = c.getCtrlY1(); coords[2] = c.getCtrlX2(); coords[3] = c.getCtrlY2(); coords[4] = c.getX2(); coords[5] = c.getY2(); count = 3; } if (t != null) { t.transform(coords, 0, coords, 0, count); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/CubicCurve2D.java
public int currentSegment(float[] coords) { if (isDone()) { throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type; int count; if (index == 0) { type = SEG_MOVETO; coords[0] = (float)c.getX1(); coords[1] = (float)c.getY1(); count = 1; } else { type = SEG_CUBICTO; coords[0] = (float)c.getCtrlX1(); coords[1] = (float)c.getCtrlY1(); coords[2] = (float)c.getCtrlX2(); coords[3] = (float)c.getCtrlY2(); coords[4] = (float)c.getX2(); coords[5] = (float)c.getY2(); count = 3; } if (t != null) { t.transform(coords, 0, coords, 0, count); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/PolylineShapeIterator.java
public int currentSegment(double[] coords) { if (isDone()) { throw new NoSuchElementException(MessageLocalization.getComposedMessage("line.iterator.out.of.bounds")); } int type = (index==0)?SEG_MOVETO:SEG_LINETO; coords[0] = poly.x[index]; coords[1] = poly.y[index]; if (affine != null) { affine.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/PolylineShapeIterator.java
public int currentSegment(float[] coords) { if (isDone()) { throw new NoSuchElementException(MessageLocalization.getComposedMessage("line.iterator.out.of.bounds")); } int type = (index==0)?SEG_MOVETO:SEG_LINETO; coords[0] = poly.x[index]; coords[1] = poly.y[index]; if (affine != null) { affine.transform(coords, 0, coords, 0, 1); } return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
public int currentSegment(double[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type = p.types[typeIndex]; int count = GeneralPath.pointShift[type]; for (int i = 0; i < count; i++) { coords[i] = p.points[pointIndex + i]; } if (t != null) { t.transform(coords, 0, coords, 0, count / 2); } pointIndex += count; return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/GeneralPath.java
public int currentSegment(float[] coords) { if (isDone()) { // awt.4B=Iterator out of bounds throw new NoSuchElementException(Messages.getString("awt.4B")); //$NON-NLS-1$ } int type = p.types[typeIndex]; int count = GeneralPath.pointShift[type]; System.arraycopy(p.points, pointIndex, coords, 0, count); if (t != null) { t.transform(coords, 0, coords, 0, count / 2); } pointIndex += count; return type; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
public Entry next() { if (entry == null) { while (index-- > 0 && (entry = table[index]) == null); } if (entry != null) { Entry e = entry; entry = e.next; return e; } throw new NoSuchElementException(MessageLocalization.getComposedMessage("inthashtableiterator")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/IntHashtable.java
public Entry next() { if (entry == null) { while (index-- > 0 && (entry = table[index]) == null); } if (entry != null) { Entry e = entry; entry = e.next; return e; } throw new NoSuchElementException(MessageLocalization.getComposedMessage("inthashtableiterator")); }
0 0 0 0 0
checked (Domain) NoninvertibleTransformException
public class NoninvertibleTransformException extends java.lang.Exception {

    private static final long serialVersionUID = 6137225240503990466L;

    public NoninvertibleTransformException(String s) {
        super(s);
    }

}
3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public AffineTransform createInverse() throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } return new AffineTransform( m11 / det, // m00 -m10 / det, // m10 -m01 / det, // m01 m00 / det, // m11 (m01 * m12 - m11 * m02) / det, // m02 (m10 * m02 - m00 * m12) / det // m12 ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public Point2D inverseTransform(Point2D src, Point2D dst) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } if (dst == null) { if (src instanceof Point2D.Double) { dst = new Point2D.Double(); } else { dst = new Point2D.Float(); } } double x = src.getX() - m02; double y = src.getY() - m12; dst.setLocation((x * m11 - y * m01) / det, (y * m00 - x * m10) / det); return dst; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public void inverseTransform(double[] src, int srcOff, double[] dst, int dstOff, int length) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } while (--length >= 0) { double x = src[srcOff++] - m02; double y = src[srcOff++] - m12; dst[dstOff++] = (x * m11 - y * m01) / det; dst[dstOff++] = (y * m00 - x * m10) / det; } }
0 3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public AffineTransform createInverse() throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } return new AffineTransform( m11 / det, // m00 -m10 / det, // m10 -m01 / det, // m01 m00 / det, // m11 (m01 * m12 - m11 * m02) / det, // m02 (m10 * m02 - m00 * m12) / det // m12 ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public Point2D inverseTransform(Point2D src, Point2D dst) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } if (dst == null) { if (src instanceof Point2D.Double) { dst = new Point2D.Double(); } else { dst = new Point2D.Float(); } } double x = src.getX() - m02; double y = src.getY() - m12; dst.setLocation((x * m11 - y * m01) / det, (y * m00 - x * m10) / det); return dst; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/AffineTransform.java
public void inverseTransform(double[] src, int srcOff, double[] dst, int dstOff, int length) throws NoninvertibleTransformException { double det = getDeterminant(); if (Math.abs(det) < ZERO) { // awt.204=Determinant is zero throw new NoninvertibleTransformException(Messages.getString("awt.204")); //$NON-NLS-1$ } while (--length >= 0) { double x = src[srcOff++] - m02; double y = src[srcOff++] - m12; dst[dstOff++] = (x * m11 - y * m01) / det; dst[dstOff++] = (y * m00 - x * m10) / det; } }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/PdfGraphics2D.java
catch (NoninvertibleTransformException e) { return null; }
0 0
runtime (Lib) NullPointerException 15
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/awt/geom/misc/RenderingHints.java
public boolean containsKey(Object key) { if (key == null) { throw new NullPointerException(); } return map.containsKey(key); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactory.java
public static void setFontImp(final FontFactoryImp fontImp) { if (fontImp == null) throw new NullPointerException(MessageLocalization.getComposedMessage("fontfactoryimp.cannot.be.null")); FontFactory.fontImp = fontImp; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/VerticalText.java
public int go(boolean simulate) { boolean dirty = false; PdfContentByte graphics = null; if (text != null) { graphics = text.getDuplicate(); } else if (!simulate) throw new NullPointerException(MessageLocalization.getComposedMessage("verticaltext.go.with.simulate.eq.eq.false.and.text.eq.eq.null")); int status = 0; for (;;) { if (maxLines <= 0) { status = NO_MORE_COLUMN; if (chunks.isEmpty()) status |= NO_MORE_TEXT; break; } if (chunks.isEmpty()) { status = NO_MORE_TEXT; break; } PdfLine line = createLine(height); if (!simulate && !dirty) { text.beginText(); dirty = true; } shortenChunkArray(); if (!simulate) { text.setTextMatrix(startX, startY - line.indentLeft()); writeLine(line, text, graphics); } --maxLines; startX -= leading; } if (dirty) { text.endText(); text.add(graphics); } return status; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public int go(final boolean simulate, final IAccessibleElement elementToGo) throws DocumentException { if (composite) return goComposite(simulate); ListBody lBody = null; if (isTagged(canvas) && elementToGo instanceof ListItem) { lBody = ((ListItem)elementToGo).getListBody(); } addWaitingPhrase(); if (bidiLine == null) return NO_MORE_TEXT; descender = 0; linesWritten = 0; lastX = 0; boolean dirty = false; float ratio = spaceCharRatio; Object currentValues[] = new Object[2]; PdfFont currentFont = null; Float lastBaseFactor = new Float(0); currentValues[1] = lastBaseFactor; PdfDocument pdf = null; PdfContentByte graphics = null; PdfContentByte text = null; firstLineY = Float.NaN; int localRunDirection = PdfWriter.RUN_DIRECTION_NO_BIDI; if (runDirection != PdfWriter.RUN_DIRECTION_DEFAULT) localRunDirection = runDirection; if (canvas != null) { graphics = canvas; pdf = canvas.getPdfDocument(); if (!isTagged(canvas)) text = canvas.getDuplicate(); else text = canvas; } else if (!simulate) throw new NullPointerException(MessageLocalization.getComposedMessage("columntext.go.with.simulate.eq.eq.false.and.text.eq.eq.null")); if (!simulate) { if (ratio == GLOBAL_SPACE_CHAR_RATIO) ratio = text.getPdfWriter().getSpaceCharRatio(); else if (ratio < 0.001f) ratio = 0.001f; } if (!rectangularMode) { float max = 0; for (PdfChunk c : bidiLine.chunks) { max = Math.max(max, c.font.size()); } currentLeading = fixedLeading + max * multipliedLeading; } float firstIndent = 0; PdfLine line; float x1; int status = 0; while(true) { firstIndent = lastWasNewline ? indent : followingIndent; // if (rectangularMode) { if (rectangularWidth <= firstIndent + rightIndent) { status = NO_MORE_COLUMN; if (bidiLine.isEmpty()) status |= NO_MORE_TEXT; break; } if (bidiLine.isEmpty()) { status = NO_MORE_TEXT; break; } line = bidiLine.processLine(leftX, rectangularWidth - firstIndent - rightIndent, alignment, localRunDirection, arabicOptions, minY, yLine, descender); if (line == null) { status = NO_MORE_TEXT; break; } float[] maxSize = line.getMaxSize(fixedLeading, multipliedLeading); if (isUseAscender() && Float.isNaN(firstLineY)) currentLeading = line.getAscender(); else currentLeading = Math.max(maxSize[0], maxSize[1] - descender); if (yLine > maxY || yLine - currentLeading < minY ) { status = NO_MORE_COLUMN; bidiLine.restore(); break; } yLine -= currentLeading; if (!simulate && !dirty) { text.beginText(); dirty = true; } if (Float.isNaN(firstLineY)) firstLineY = yLine; updateFilledWidth(rectangularWidth - line.widthLeft()); x1 = leftX; } else { float yTemp = yLine - currentLeading; float xx[] = findLimitsTwoLines(); if (xx == null) { status = NO_MORE_COLUMN; if (bidiLine.isEmpty()) status |= NO_MORE_TEXT; yLine = yTemp; break; } if (bidiLine.isEmpty()) { status = NO_MORE_TEXT; yLine = yTemp; break; } x1 = Math.max(xx[0], xx[2]); float x2 = Math.min(xx[1], xx[3]); if (x2 - x1 <= firstIndent + rightIndent) continue; if (!simulate && !dirty) { text.beginText(); dirty = true; } line = bidiLine.processLine(x1, x2 - x1 - firstIndent - rightIndent, alignment, localRunDirection, arabicOptions, minY, yLine, descender); if (line == null) { status = NO_MORE_TEXT; yLine = yTemp; break; } } if (isTagged(canvas) && elementToGo instanceof ListItem) { if (!Float.isNaN(firstLineY) && !firstLineYDone) { if (!simulate) { ListLabel lbl = ((ListItem)elementToGo).getListLabel(); canvas.openMCBlock(lbl); Chunk symbol = new Chunk(((ListItem)elementToGo).getListSymbol()); if (!lbl.getTagLabelContent()) { symbol.setRole(null); } ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(symbol), leftX + lbl.getIndentation(), firstLineY, 0); canvas.closeMCBlock(lbl); } firstLineYDone = true; } } if (!simulate) { if (lBody != null) { canvas.openMCBlock(lBody); lBody = null; } currentValues[0] = currentFont; text.setTextMatrix(x1 + (line.isRTL() ? rightIndent : firstIndent) + line.indentLeft(), yLine); lastX = pdf.writeLineToContent(line, text, graphics, currentValues, ratio); currentFont = (PdfFont)currentValues[0]; } lastWasNewline = repeatFirstLineIndent && line.isNewlineSplit(); yLine -= line.isNewlineSplit() ? extraParagraphSpace : 0; ++linesWritten; descender = line.getDescender(); } if (dirty) { text.endText(); if (canvas != text) canvas.add(text); } return status; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
private void showText2(final String text) { if (state.fontDetails == null) throw new NullPointerException(MessageLocalization.getComposedMessage("font.and.size.must.be.set.before.writing.any.text")); byte b[] = state.fontDetails.convertToBytes(text); escapeString(b, content); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void showTextKerned(final String text) { if (state.fontDetails == null) throw new NullPointerException(MessageLocalization.getComposedMessage("font.and.size.must.be.set.before.writing.any.text")); BaseFont bf = state.fontDetails.getBaseFont(); if (bf.hasKernPairs()) showText(getKernArray(text, bf)); else { showText(text); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
private void showTextAligned(final int alignment, final String text, float x, float y, final float rotation, final boolean kerned) { if (state.fontDetails == null) throw new NullPointerException(MessageLocalization.getComposedMessage("font.and.size.must.be.set.before.writing.any.text")); if (rotation == 0) { switch (alignment) { case ALIGN_CENTER: x -= getEffectiveStringWidth(text, kerned) / 2; break; case ALIGN_RIGHT: x -= getEffectiveStringWidth(text, kerned); break; } setTextMatrix(x, y); if (kerned) showTextKerned(text); else showText(text); } else { double alpha = rotation * Math.PI / 180.0; float cos = (float)Math.cos(alpha); float sin = (float)Math.sin(alpha); float len; switch (alignment) { case ALIGN_CENTER: len = getEffectiveStringWidth(text, kerned) / 2; x -= len * cos; y -= len * sin; break; case ALIGN_RIGHT: len = getEffectiveStringWidth(text, kerned); x -= len * cos; y -= len * sin; break; } setTextMatrix(cos, sin, -sin, cos, x, y); if (kerned) showTextKerned(text); else showText(text); setTextMatrix(0f, 0f); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
protected void checkWriter() { if (writer == null) throw new NullPointerException(MessageLocalization.getComposedMessage("the.writer.in.pdfcontentbyte.is.null")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void showText(final PdfTextArray text) { if (!inText && isTagged()) { beginText(true); } if (state.fontDetails == null) throw new NullPointerException(MessageLocalization.getComposedMessage("font.and.size.must.be.set.before.writing.any.text")); content.append("["); ArrayList<Object> arrayList = text.getArrayList(); boolean lastWasNumber = false; for (Object obj : arrayList) { if (obj instanceof String) { showText2((String)obj); updateTx((String)obj, 0); lastWasNumber = false; } else { if (lastWasNumber) content.append(' '); else lastWasNumber = true; content.append(((Float)obj).floatValue()); updateTx("", ((Float)obj).floatValue()); } } content.append("]TJ").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfLayer.java
public static PdfLayer createTitle(String title, PdfWriter writer) { if (title == null) throw new NullPointerException(MessageLocalization.getComposedMessage("title.cannot.be.null")); PdfLayer layer = new PdfLayer(title); writer.registerLayer(layer); return layer; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodePDF417.java
public void paintCode() { int maxErr, lenErr, tot, pad; if ((options & PDF417_USE_RAW_CODEWORDS) != 0) { if (lenCodewords > MAX_DATA_CODEWORDS || lenCodewords < 1 || lenCodewords != codewords[0]) { throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.codeword.size")); } } else { if (text == null) throw new NullPointerException(MessageLocalization.getComposedMessage("text.cannot.be.null")); if (text.length > ABSOLUTE_MAX_TEXT_SIZE) { throw new IndexOutOfBoundsException(MessageLocalization.getComposedMessage("the.text.is.too.big")); } segmentList = new SegmentList(); breakString(); //dumpList(); assemble(); segmentList = null; codewords[0] = lenCodewords = cwPtr; } maxErr = maxPossibleErrorLevel(MAX_DATA_CODEWORDS + 2 - lenCodewords); if ((options & PDF417_USE_ERROR_LEVEL) == 0) { if (lenCodewords < 41) errorLevel = 2; else if (lenCodewords < 161) errorLevel = 3; else if (lenCodewords < 321) errorLevel = 4; else errorLevel = 5; } if (errorLevel < 0) errorLevel = 0; else if (errorLevel > maxErr) errorLevel = maxErr; if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) codeRows = 90; lenErr = 2 << errorLevel; boolean fixedColumn = (options & PDF417_FIXED_ROWS) == 0; boolean skipRowColAdjust = false; tot = lenCodewords + lenErr; if ((options & PDF417_FIXED_RECTANGLE) != 0) { tot = codeColumns * codeRows; if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } if (tot < lenCodewords + lenErr) tot = lenCodewords + lenErr; else skipRowColAdjust = true; } else if ((options & (PDF417_FIXED_COLUMNS | PDF417_FIXED_ROWS)) == 0) { double c, b; fixedColumn = true; if (aspectRatio < 0.001) aspectRatio = 0.001f; else if (aspectRatio > 1000) aspectRatio = 1000; b = 73 * aspectRatio - 4; c = (-b + Math.sqrt(b * b + 4 * 17 * aspectRatio * (lenCodewords + lenErr) * yHeight)) / (2 * 17 * aspectRatio); codeColumns = (int)(c + 0.5); if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; } if (!skipRowColAdjust) { if (fixedColumn) { codeRows = (tot - 1) / codeColumns + 1; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) { codeRows = 90; codeColumns = (tot - 1) / 90 + 1; } } else { codeColumns = (tot - 1) / codeRows + 1; if (codeColumns > 30) { codeColumns = 30; codeRows = (tot - 1) / 30 + 1; } } tot = codeRows * codeColumns; } if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } errorLevel = maxPossibleErrorLevel(tot - lenCodewords); lenErr = 2 << errorLevel; pad = tot - lenErr - lenCodewords; if ((options & PDF417_USE_MACRO) != 0) { // the padding comes before the control block System.arraycopy(codewords, macroIndex, codewords, macroIndex + pad, pad); cwPtr = lenCodewords + pad; while (pad-- != 0) codewords[macroIndex++] = TEXT_MODE; } else { cwPtr = lenCodewords; while (pad-- != 0) codewords[cwPtr++] = TEXT_MODE; } codewords[0] = lenCodewords = cwPtr; calculateErrorCorrection(lenCodewords); lenCodewords = tot; outPaintCode(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/CrlClientOnline.java
public Collection<byte[]> getEncoded(X509Certificate checkCert, String url) { if (checkCert == null) return null; List<URL> urllist = new ArrayList<URL>(urls); if (urllist.size() == 0) { LOGGER.info("Looking for CRL for certificate " + checkCert.getSubjectDN()); try { if (url == null) url = CertificateUtil.getCRLURL(checkCert); if (url == null) throw new NullPointerException(); urllist.add(new URL(url)); LOGGER.info("Found CRL url: " + url); } catch (Exception e) { LOGGER.info("Skipped CRL url: " + e.getMessage()); } } ArrayList<byte[]> ar = new ArrayList<byte[]>(); for (URL urlt : urllist) { try { LOGGER.info("Checking CRL: " + urlt); HttpURLConnection con = (HttpURLConnection)urlt.openConnection(); if (con.getResponseCode() / 100 != 2) { throw new IOException(MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode())); } //Get Response InputStream inp = (InputStream) con.getContent(); byte[] buf = new byte[1024]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while (true) { int n = inp.read(buf, 0, buf.length); if (n <= 0) break; bout.write(buf, 0, n); } inp.close(); ar.add(bout.toByteArray()); LOGGER.info("Added CRL found at: " + urlt); } catch (Exception e) { LOGGER.info("Skipped CRL: " + e.getMessage() + " for " + urlt); } } return ar; }
0 0 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/FontFactoryImp.java
catch(NullPointerException npe) { // null was entered as fontname and/or encoding return new Font(FontFamily.UNDEFINED, size, style, color); }
0 0
unknown (Lib) NumberFormatException 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/factories/RomanAlphabetFactory.java
public static final String getString(int index) { if (index < 1) throw new NumberFormatException(MessageLocalization.getComposedMessage("you.can.t.translate.a.negative.number.into.an.alphabetical.value")); index--; int bytes = 1; int start = 0; int symbols = 26; while(index >= symbols + start) { bytes++; start += symbols; symbols *= 26; } int c = index - start; char[] value = new char[bytes]; while(bytes > 0) { value[--bytes] = (char)( 'a' + (c % 26)); c /= 26; } return new String(value); }
0 0 5
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/EntitiesToUnicode.java
catch(NumberFormatException nfe) { return '\0'; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/simpleparser/EntitiesToUnicode.java
catch(NumberFormatException nfe) { return '\0'; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/XMLUtil.java
catch (NumberFormatException nfe) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfNumber.java
catch (NumberFormatException nfe){ throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.number.2", content, nfe.toString())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/html/HtmlUtilities.java
catch (NumberFormatException nfe) { sIndex = 0; }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfNumber.java
catch (NumberFormatException nfe){ throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.number.2", content, nfe.toString())); }
1
unknown (Lib) OCSPException 0 0 2
            
// 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)); }
3
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch (OCSPException e) { throw new GeneralSecurityException(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch (OCSPException e) { continue; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch (OCSPException e) { return false; }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch (OCSPException e) { throw new GeneralSecurityException(e); }
0
unknown (Lib) OperatorCreationException 0 0 0 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch (OperatorCreationException e) { return false; }
0 0
unknown (Lib) ParserConfigurationException 0 0 1 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/xmp/XmpReader.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/xmp/XmpReader.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (ParserConfigurationException e) { throw new ExceptionConverter(e); }
2
checked (Domain) PdfException
public class PdfException extends DocumentException {
    
    // constructors
    
    private static final long serialVersionUID = 6767433960955483999L;

	public PdfException(Exception ex) {
        super(ex);
    }

 /**
 * Constructs a <CODE>PdfException</CODE> without a message.
 */
    
    PdfException() {
        super();
    }
    
/**
 * Constructs a <code>PdfException</code> with a message.
 *
 * @param		message			a message describing the exception
 */
    
    PdfException(String message) {
        super(message);
    }
}
4
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectReference add(final PdfPage page, final PdfContents contents) throws PdfException { if (!open) { throw new PdfException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfIndirectObject object; try { object = addToBody(contents); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } page.add(object.getIndirectReference()); // [U5] if (group != null) { page.put(PdfName.GROUP, group); group = null; } else if (rgbTransparencyBlending) { PdfDictionary pp = new PdfDictionary(); pp.put(PdfName.TYPE, PdfName.GROUP); pp.put(PdfName.S, PdfName.TRANSPARENCY); pp.put(PdfName.CS, PdfName.DEVICERGB); page.put(PdfName.GROUP, pp); } root.addPage(page); currentPageNumber++; return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void setPageAction(PdfName actionType, PdfAction action, int page) throws PdfException { if (!actionType.equals(PAGE_OPEN) && !actionType.equals(PAGE_CLOSE)) throw new PdfException(MessageLocalization.getComposedMessage("invalid.page.additional.action.type.1", actionType.toString())); PdfDictionary pg = reader.getPageN(page); PdfDictionary aa = (PdfDictionary)PdfReader.getPdfObject(pg.get(PdfName.AA), pg); if (aa == null) { aa = new PdfDictionary(); pg.put(PdfName.AA, aa); markUsed(pg); } aa.put(actionType, action); markUsed(aa); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setAdditionalAction(PdfName actionType, PdfAction action) throws PdfException { if (!(actionType.equals(DOCUMENT_CLOSE) || actionType.equals(WILL_SAVE) || actionType.equals(DID_SAVE) || actionType.equals(WILL_PRINT) || actionType.equals(DID_PRINT))) { throw new PdfException(MessageLocalization.getComposedMessage("invalid.additional.action.type.1", actionType.toString())); } PdfDictionary aa = reader.getCatalog().getAsDict(PdfName.AA); if (aa == null) { if (action == null) return; aa = new PdfDictionary(); reader.getCatalog().put(PdfName.AA, aa); } markUsed(aa); if (action == null) aa.remove(actionType); else aa.put(actionType, action); }
0 14
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectReference add(final PdfPage page, final PdfContents contents) throws PdfException { if (!open) { throw new PdfException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfIndirectObject object; try { object = addToBody(contents); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } page.add(object.getIndirectReference()); // [U5] if (group != null) { page.put(PdfName.GROUP, group); group = null; } else if (rgbTransparencyBlending) { PdfDictionary pp = new PdfDictionary(); pp.put(PdfName.TYPE, PdfName.GROUP); pp.put(PdfName.S, PdfName.TRANSPARENCY); pp.put(PdfName.CS, PdfName.DEVICERGB); page.put(PdfName.GROUP, pp); } root.addPage(page); currentPageNumber++; return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setThumbnail(final Image image) throws PdfException, DocumentException { pdf.setThumbnail(image); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfName addDirectImageSimple(final Image image) throws PdfException, DocumentException { return addDirectImageSimple(image, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfName addDirectImageSimple(final Image image, final PdfIndirectReference fixedRef) throws PdfException, DocumentException { PdfName name; // if the images is already added, just retrieve the name if (images.containsKey(image.getMySerialId())) { name = images.get(image.getMySerialId()); } // if it's a new image, add it to the document else { if (image.isImgTemplate()) { name = new PdfName("img" + images.size()); if(image instanceof ImgWMF){ try { ImgWMF wmf = (ImgWMF)image; wmf.readWMF(PdfTemplate.createTemplate(this, 0, 0)); } catch (Exception e) { throw new DocumentException(e); } } } else { PdfIndirectReference dref = image.getDirectReference(); if (dref != null) { PdfName rname = new PdfName("img" + images.size()); images.put(image.getMySerialId(), rname); imageDictionary.put(rname, dref); return rname; } Image maskImage = image.getImageMask(); PdfIndirectReference maskRef = null; if (maskImage != null) { PdfName mname = images.get(maskImage.getMySerialId()); maskRef = getImageReference(mname); } PdfImage i = new PdfImage(image, "img" + images.size(), maskRef); if (image instanceof ImgJBIG2) { byte[] globals = ((ImgJBIG2) image).getGlobalBytes(); if (globals != null) { PdfDictionary decodeparms = new PdfDictionary(); decodeparms.put(PdfName.JBIG2GLOBALS, getReferenceJBIG2Globals(globals)); i.put(PdfName.DECODEPARMS, decodeparms); } } if (image.hasICCProfile()) { PdfICCBased icc = new PdfICCBased(image.getICCProfile(), image.getCompressionLevel()); PdfIndirectReference iccRef = add(icc); PdfArray iccArray = new PdfArray(); iccArray.add(PdfName.ICCBASED); iccArray.add(iccRef); PdfArray colorspace = i.getAsArray(PdfName.COLORSPACE); if (colorspace != null) { if (colorspace.size() > 1 && PdfName.INDEXED.equals(colorspace.getPdfObject(0))) colorspace.set(1, iccArray); else i.put(PdfName.COLORSPACE, iccArray); } else i.put(PdfName.COLORSPACE, iccArray); } add(i, fixedRef); name = i.name(); } images.put(image.getMySerialId(), name); } return name; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
PdfIndirectReference add(final PdfImage pdfImage, PdfIndirectReference fixedRef) throws PdfException { if (! imageDictionary.contains(pdfImage.name())) { PdfWriter.checkPdfIsoConformance(this, PdfIsoKeys.PDFISOKEY_IMAGE, pdfImage); if (fixedRef instanceof PRIndirectReference) { PRIndirectReference r2 = (PRIndirectReference)fixedRef; fixedRef = new PdfIndirectReference(0, getNewObjectNumber(r2.getReader(), r2.getNumber(), r2.getGeneration())); } try { if (fixedRef == null) fixedRef = addToBody(pdfImage).getIndirectReference(); else addToBody(pdfImage, fixedRef); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } imageDictionary.put(pdfImage.name(), fixedRef); return fixedRef; } return (PdfIndirectReference) imageDictionary.get(pdfImage.name()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setPageAction(PdfName actionType, PdfAction action) throws PdfException { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.setpageaction.pdfname.actiontype.pdfaction.action.int.page")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void setPageAction(PdfName actionType, PdfAction action, int page) throws PdfException { if (!actionType.equals(PAGE_OPEN) && !actionType.equals(PAGE_CLOSE)) throw new PdfException(MessageLocalization.getComposedMessage("invalid.page.additional.action.type.1", actionType.toString())); PdfDictionary pg = reader.getPageN(page); PdfDictionary aa = (PdfDictionary)PdfReader.getPdfObject(pg.get(PdfName.AA), pg); if (aa == null) { aa = new PdfDictionary(); pg.put(PdfName.AA, aa); markUsed(pg); } aa.put(actionType, action); markUsed(aa); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setAdditionalAction(PdfName actionType, PdfAction action) throws PdfException { if (!(actionType.equals(DOCUMENT_CLOSE) || actionType.equals(WILL_SAVE) || actionType.equals(DID_SAVE) || actionType.equals(WILL_PRINT) || actionType.equals(DID_PRINT))) { throw new PdfException(MessageLocalization.getComposedMessage("invalid.additional.action.type.1", actionType.toString())); } PdfDictionary aa = reader.getCatalog().getAsDict(PdfName.AA); if (aa == null) { if (action == null) return; aa = new PdfDictionary(); reader.getCatalog().put(PdfName.AA, aa); } markUsed(aa); if (action == null) aa.remove(actionType); else aa.put(actionType, action); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void setThumbnail(Image image, int page) throws PdfException, DocumentException { PdfIndirectReference thumb = getImageReference(addDirectImageSimple(image)); reader.resetReleasePage(); PdfDictionary dic = reader.getPageN(page); dic.put(PdfName.THUMB, thumb); reader.resetReleasePage(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void setThumbnail(final Image image) throws PdfException, DocumentException { writer.addPageDictEntry(PdfName.THUMB, writer.getImageReference(writer.addDirectImageSimple(image))); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
protected void add(final Image image) throws PdfException, DocumentException { if (image.hasAbsoluteY()) { graphics.addImage(image); pageEmpty = false; return; } // if there isn't enough room for the image on this page, save it for the next page if (currentHeight != 0 && indentTop() - currentHeight - image.getScaledHeight() < indentBottom()) { if (!strictImageSequence && imageWait == null) { imageWait = image; return; } newPage(); if (currentHeight != 0 && indentTop() - currentHeight - image.getScaledHeight() < indentBottom()) { imageWait = image; return; } } pageEmpty = false; // avoid endless loops if (image == imageWait) imageWait = null; boolean textwrap = (image.getAlignment() & Image.TEXTWRAP) == Image.TEXTWRAP && !((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE); boolean underlying = (image.getAlignment() & Image.UNDERLYING) == Image.UNDERLYING; float diff = leading / 2; if (textwrap) { diff += leading; } float lowerleft = indentTop() - currentHeight - image.getScaledHeight() -diff; float mt[] = image.matrix(); float startPosition = indentLeft() - mt[4]; if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) startPosition = indentRight() - image.getScaledWidth() - mt[4]; if ((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE) startPosition = indentLeft() + (indentRight() - indentLeft() - image.getScaledWidth()) / 2 - mt[4]; if (image.hasAbsoluteX()) startPosition = image.getAbsoluteX(); if (textwrap) { if (imageEnd < 0 || imageEnd < currentHeight + image.getScaledHeight() + diff) { imageEnd = currentHeight + image.getScaledHeight() + diff; } if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) { // indentation suggested by Pelikan Stephan indentation.imageIndentRight += image.getScaledWidth() + image.getIndentationLeft(); } else { // indentation suggested by Pelikan Stephan indentation.imageIndentLeft += image.getScaledWidth() + image.getIndentationRight(); } } else { if ((image.getAlignment() & Image.RIGHT) == Image.RIGHT) startPosition -= image.getIndentationRight(); else if ((image.getAlignment() & Image.MIDDLE) == Image.MIDDLE) startPosition += image.getIndentationLeft() - image.getIndentationRight(); else startPosition += image.getIndentationLeft(); } graphics.addImage(image, mt[0], mt[1], mt[2], mt[3], startPosition, lowerleft - mt[5]); if (!(textwrap || underlying)) { currentHeight += image.getScaledHeight() + diff; flushLines(); text.moveText(0, - (image.getScaledHeight() + diff)); newLine(); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
Override PdfIndirectReference add(PdfPage page, PdfContents contents) throws PdfException { return null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setThumbnail(final Image image, final int page) throws PdfException, DocumentException { stamper.setThumbnail(image, page); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamper.java
public void setPageAction(final PdfName actionType, final PdfAction action, final int page) throws PdfException { stamper.setPageAction(actionType, action, page); }
0 0 0
runtime (Domain) PdfIsoConformanceException
public class PdfIsoConformanceException extends RuntimeException {

	/** Serial version UID */
	private static final long serialVersionUID = -8972376258066225871L;

	/** Creates a new instance of PdfIsoConformanceException. */
    public PdfIsoConformanceException() {
    }

    /**
     * Creates a new instance of PdfIsoConformanceException.
     * @param s
     */
    public PdfIsoConformanceException(String s) {
        super(s);
    }    
}
0 0 0 0 0 0
runtime (Domain) PdfXConformanceException
public class PdfXConformanceException extends PdfIsoConformanceException {
    
    private static final long serialVersionUID = 9199144538884293397L;

	/** Creates a new instance of PdfXConformanceException. */
    public PdfXConformanceException() {
    }
    
    /**
     * Creates a new instance of PdfXConformanceException.
     * @param s
     */
    public PdfXConformanceException(String s) {
        super(s);
    }    
}
14
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setPDFXConformance(final int pdfx) { if (!(pdfIsoConformance instanceof PdfXConformanceImp)) return; if (((PdfXConformance)pdfIsoConformance).getPDFXConformance() == pdfx) return; if (pdf.isOpen()) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("pdfx.conformance.can.only.be.set.before.opening.the.document")); if (crypto != null) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("a.pdfx.conforming.document.cannot.be.encrypted")); if (pdfx != PDFXNONE) setPdfVersion(VERSION_1_3); ((PdfXConformance)pdfIsoConformance).setPDFXConformance(pdfx); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/internal/PdfXConformanceImp.java
public static void checkPDFXConformance(PdfWriter writer, int key, Object obj1) { if (writer == null || !writer.isPdfX()) return; int conf = writer.getPDFXConformance(); switch (key) { case PdfIsoKeys.PDFISOKEY_COLOR: switch (conf) { case PdfWriter.PDFX1A2001: if (obj1 instanceof ExtendedColor) { ExtendedColor ec = (ExtendedColor)obj1; switch (ec.getType()) { case ExtendedColor.TYPE_CMYK: case ExtendedColor.TYPE_GRAY: return; case ExtendedColor.TYPE_RGB: throw new PdfXConformanceException(MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed")); case ExtendedColor.TYPE_SEPARATION: SpotColor sc = (SpotColor)ec; checkPDFXConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, sc.getPdfSpotColor().getAlternativeCS()); break; case ExtendedColor.TYPE_SHADING: ShadingColor xc = (ShadingColor)ec; checkPDFXConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, xc.getPdfShadingPattern().getShading().getColorSpace()); break; case ExtendedColor.TYPE_PATTERN: PatternColor pc = (PatternColor)ec; checkPDFXConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, pc.getPainter().getDefaultColor()); break; } } else if (obj1 instanceof BaseColor) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed")); break; } break; case PdfIsoKeys.PDFISOKEY_CMYK: break; case PdfIsoKeys.PDFISOKEY_RGB: if (conf == PdfWriter.PDFX1A2001) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed")); break; case PdfIsoKeys.PDFISOKEY_FONT: if (!((BaseFont)obj1).isEmbedded()) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("all.the.fonts.must.be.embedded.this.one.isn.t.1", ((BaseFont)obj1).getPostscriptFontName())); break; case PdfIsoKeys.PDFISOKEY_IMAGE: PdfImage image = (PdfImage)obj1; if (image.get(PdfName.SMASK) != null) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("the.smask.key.is.not.allowed.in.images")); switch (conf) { case PdfWriter.PDFX1A2001: PdfObject cs = image.get(PdfName.COLORSPACE); if (cs == null) return; if (cs.isName()) { if (PdfName.DEVICERGB.equals(cs)) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("colorspace.rgb.is.not.allowed")); } else if (cs.isArray()) { if (PdfName.CALRGB.equals(((PdfArray)cs).getPdfObject(0))) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("colorspace.calrgb.is.not.allowed")); } break; } break; case PdfIsoKeys.PDFISOKEY_GSTATE: PdfDictionary gs = (PdfDictionary)obj1; PdfObject obj = gs.get(PdfName.BM); if (obj != null && !PdfGState.BM_NORMAL.equals(obj) && !PdfGState.BM_COMPATIBLE.equals(obj)) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("blend.mode.1.not.allowed", obj.toString())); obj = gs.get(PdfName.CA); double v = 0.0; if (obj != null && (v = ((PdfNumber)obj).doubleValue()) != 1.0) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("transparency.is.not.allowed.ca.eq.1", String.valueOf(v))); obj = gs.get(PdfName.ca); v = 0.0; if (obj != null && (v = ((PdfNumber)obj).doubleValue()) != 1.0) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("transparency.is.not.allowed.ca.eq.1", String.valueOf(v))); break; case PdfIsoKeys.PDFISOKEY_LAYER: throw new PdfXConformanceException(MessageLocalization.getComposedMessage("layers.are.not.allowed")); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public boolean newPage() { try { flushFloatingElements(); } catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } lastElementType = -1; if (isPageEmpty()) { setNewPageSizeAndMargins(); return false; } if (!open || close) { throw new RuntimeException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) pageEvent.onEndPage(writer, this); //Added to inform any listeners that we are moving to a new page (added by David Freels) super.newPage(); // the following 2 lines were added by Pelikan Stephan indentation.imageIndentLeft = 0; indentation.imageIndentRight = 0; try { // we flush the arraylist with recently written lines flushLines(); // we prepare the elements of the page dictionary // [U1] page size and rotation int rotation = pageSize.getRotation(); // [C10] if (writer.isPdfIso()) { if (thisBoxSize.containsKey("art") && thisBoxSize.containsKey("trim")) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("only.one.of.artbox.or.trimbox.can.exist.in.the.page")); if (!thisBoxSize.containsKey("art") && !thisBoxSize.containsKey("trim")) { if (thisBoxSize.containsKey("crop")) thisBoxSize.put("trim", thisBoxSize.get("crop")); else thisBoxSize.put("trim", new PdfRectangle(pageSize, pageSize.getRotation())); } } // [M1] pageResources.addDefaultColorDiff(writer.getDefaultColorspace()); if (writer.isRgbTransparencyBlending()) { PdfDictionary dcs = new PdfDictionary(); dcs.put(PdfName.CS, PdfName.DEVICERGB); pageResources.addDefaultColorDiff(dcs); } PdfDictionary resources = pageResources.getResources(); // we create the page dictionary PdfPage page = new PdfPage(new PdfRectangle(pageSize, rotation), thisBoxSize, resources, rotation); if (isTagged(writer)) { page.put(PdfName.TABS, PdfName.S); } else { page.put(PdfName.TABS, writer.getTabs()); } page.putAll(writer.getPageDictEntries()); writer.resetPageDictEntries(); // we complete the page dictionary // [U3] page actions: additional actions if (pageAA != null) { page.put(PdfName.AA, writer.addToBody(pageAA).getIndirectReference()); pageAA = null; } // [C5] and [C8] we add the annotations if (annotationsImp.hasUnusedAnnotations()) { PdfArray array = annotationsImp.rotateAnnotations(writer, pageSize); if (array.size() != 0) page.put(PdfName.ANNOTS, array); } // [F12] we add tag info if (isTagged(writer)) page.put(PdfName.STRUCTPARENTS, new PdfNumber(writer.getCurrentPageNumber() - 1)); if (text.size() > textEmptySize || isTagged(writer)) text.endText(); else text = null; ArrayList<IAccessibleElement> mcBlocks = null; if (isTagged(writer)) { mcBlocks = writer.getDirectContent().saveMCBlocks(); } writer.add(page, new PdfContents(writer.getDirectContentUnder(), graphics, !isTagged(writer) ? text : null, writer.getDirectContent(), pageSize)); // we initialize the new page initPage(); if (isTagged(writer)) { writer.getDirectContentUnder().restoreMCBlocks(mcBlocks); } } catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } catch (IOException ioe) { throw new ExceptionConverter(ioe); } return true; }
0 0 0 0 0
checked (Domain) ReedSolomonException
public final class ReedSolomonException extends Exception {

  /**
   * Serial version UID.
   */
   private static final long serialVersionUID = 2168232776886684292L;

public ReedSolomonException(String message) {
    super(message);
  }

}
0 0 0 0 0 0
runtime (Lib) RuntimeException 95
            
// 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 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/TIFFFaxDecoder.java
public void decodeNextScanline(byte[] buffer, int lineOffset, int bitOffset) { int bits = 0, code = 0, isT = 0; int current, entry, twoBits; boolean isWhite = true; // Initialize starting of the changing elements array changingElemSize = 0; // While scanline not complete while (bitOffset < w) { while (isWhite) { // White run current = nextNBits(10); entry = white[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x0f; if (bits == 12) { // Additional Make up code // Get the next 2 bits twoBits = nextLesserThan8Bits(2); // Consolidate the 2 new bits and last 2 bits into 4 bits current = ((current << 2) & 0x000c) | twoBits; entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits bitOffset += code; // Skip white run updatePointer(4 - bits); } else if (bits == 0) { // ERROR throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.encountered")); } else if (bits == 15) { // EOL throw new RuntimeException(MessageLocalization.getComposedMessage("eol.code.word.encountered.in.white.run")); } else { // 11 bits - 0000 0111 1111 1111 = 0x07ff code = (entry >>> 5) & 0x07ff; bitOffset += code; updatePointer(10 - bits); if (isT == 0) { isWhite = false; currChangingElems[changingElemSize++] = bitOffset; } } } // Check whether this run completed one width, if so // advance to next byte boundary for compression = 2. if (bitOffset == w) { if (compression == 2) { advancePointer(); } break; } while (!isWhite) { // Black run current = nextLesserThan8Bits(4); entry = initBlack[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (code == 100) { current = nextNBits(9); entry = black[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (bits == 12) { // Additional makeup codes updatePointer(5); current = nextLesserThan8Bits(4); entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits setToBlack(buffer, lineOffset, bitOffset, code); bitOffset += code; updatePointer(4 - bits); } else if (bits == 15) { // EOL code throw new RuntimeException(MessageLocalization.getComposedMessage("eol.code.word.encountered.in.black.run")); } else { setToBlack(buffer, lineOffset, bitOffset, code); bitOffset += code; updatePointer(9 - bits); if (isT == 0) { isWhite = true; currChangingElems[changingElemSize++] = bitOffset; } } } else if (code == 200) { // Is a Terminating code current = nextLesserThan8Bits(2); entry = twoBitBlack[current]; code = (entry >>> 5) & 0x07ff; bits = (entry >>> 1) & 0x0f; setToBlack(buffer, lineOffset, bitOffset, code); bitOffset += code; updatePointer(2 - bits); isWhite = true; currChangingElems[changingElemSize++] = bitOffset; } else { // Is a Terminating code setToBlack(buffer, lineOffset, bitOffset, code); bitOffset += code; updatePointer(4 - bits); isWhite = true; currChangingElems[changingElemSize++] = bitOffset; } } // Check whether this run completed one width if (bitOffset == w) { if (compression == 2) { advancePointer(); } break; } } currChangingElems[changingElemSize++] = bitOffset; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
public void decode2D(byte[] buffer, byte compData[], int startX, int height, long tiffT4Options) { this.data = compData; compression = 3; bitPointer = 0; bytePointer = 0; int scanlineStride = (w + 7)/8; int a0, a1, b1, b2; int[] b = new int[2]; int entry, code, bits; boolean isWhite; int currIndex = 0; int temp[]; // fillBits - dealt with this in readEOL // 1D/2D encoding - dealt with this in readEOL // uncompressedMode - haven't dealt with this yet. oneD = (int)(tiffT4Options & 0x01); uncompressedMode = (int)((tiffT4Options & 0x02) >> 1); fillBits = (int)((tiffT4Options & 0x04) >> 2); // The data must start with an EOL code if (readEOL(true) != 1) { throw new RuntimeException(MessageLocalization.getComposedMessage("first.scanline.must.be.1d.encoded")); } int lineOffset = 0; int bitOffset; // Then the 1D encoded scanline data will occur, changing elements // array gets set. decodeNextScanline(buffer, lineOffset, startX); lineOffset += scanlineStride; for (int lines = 1; lines < height; lines++) { // Every line must begin with an EOL followed by a bit which // indicates whether the following scanline is 1D or 2D encoded. if (readEOL(false) == 0) { // 2D encoded scanline follows // Initialize previous scanlines changing elements, and // initialize current scanline's changing elements array temp = prevChangingElems; prevChangingElems = currChangingElems; currChangingElems = temp; currIndex = 0; // a0 has to be set just before the start of this scanline. a0 = -1; isWhite = true; bitOffset = startX; lastChangingElement = 0; while (bitOffset < w) { // Get the next changing element getNextChangingElement(a0, isWhite, b); b1 = b[0]; b2 = b[1]; // Get the next seven bits entry = nextLesserThan8Bits(7); // Run these through the 2DCodes table entry = twoDCodes[entry] & 0xff; // Get the code and the number of bits used up code = (entry & 0x78) >>> 3; bits = entry & 0x07; if (code == 0) { if (!isWhite) { setToBlack(buffer, lineOffset, bitOffset, b2 - bitOffset); } bitOffset = a0 = b2; // Set pointer to consume the correct number of bits. updatePointer(7 - bits); } else if (code == 1) { // Horizontal updatePointer(7 - bits); // identify the next 2 codes. int number; if (isWhite) { number = decodeWhiteCodeWord(); bitOffset += number; currChangingElems[currIndex++] = bitOffset; number = decodeBlackCodeWord(); setToBlack(buffer, lineOffset, bitOffset, number); bitOffset += number; currChangingElems[currIndex++] = bitOffset; } else { number = decodeBlackCodeWord(); setToBlack(buffer, lineOffset, bitOffset, number); bitOffset += number; currChangingElems[currIndex++] = bitOffset; number = decodeWhiteCodeWord(); bitOffset += number; currChangingElems[currIndex++] = bitOffset; } a0 = bitOffset; } else if (code <= 8) { // Vertical a1 = b1 + (code - 5); currChangingElems[currIndex++] = a1; // We write the current color till a1 - 1 pos, // since a1 is where the next color starts if (!isWhite) { setToBlack(buffer, lineOffset, bitOffset, a1 - bitOffset); } bitOffset = a0 = a1; isWhite = !isWhite; updatePointer(7 - bits); } else { throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.encountered.while.decoding.2d.group.3.compressed.data")); } } // Add the changing element beyond the current scanline for the // other color too currChangingElems[currIndex++] = bitOffset; changingElemSize = currIndex; } else { // 1D encoded scanline follows decodeNextScanline(buffer, lineOffset, startX); } lineOffset += scanlineStride; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
public void decodeT6(byte[] buffer, byte[] compData, int startX, int height, long tiffT6Options) { this.data = compData; compression = 4; bitPointer = 0; bytePointer = 0; int scanlineStride = (w + 7)/8; int a0, a1, b1, b2; int entry, code, bits; boolean isWhite; int currIndex; int temp[]; // Return values from getNextChangingElement int[] b = new int[2]; // uncompressedMode - have written some code for this, but this // has not been tested due to lack of test images using this optional uncompressedMode = (int)((tiffT6Options & 0x02) >> 1); // Local cached reference int[] cce = currChangingElems; // Assume invisible preceding row of all white pixels and insert // both black and white changing elements beyond the end of this // imaginary scanline. changingElemSize = 0; cce[changingElemSize++] = w; cce[changingElemSize++] = w; int lineOffset = 0; int bitOffset; for (int lines = 0; lines < height; lines++) { // a0 has to be set just before the start of the scanline. a0 = -1; isWhite = true; // Assign the changing elements of the previous scanline to // prevChangingElems and start putting this new scanline's // changing elements into the currChangingElems. temp = prevChangingElems; prevChangingElems = currChangingElems; cce = currChangingElems = temp; currIndex = 0; // Start decoding the scanline at startX in the raster bitOffset = startX; // Reset search start position for getNextChangingElement lastChangingElement = 0; // Till one whole scanline is decoded while (bitOffset < w) { // Get the next changing element getNextChangingElement(a0, isWhite, b); b1 = b[0]; b2 = b[1]; // Get the next seven bits entry = nextLesserThan8Bits(7); // Run these through the 2DCodes table entry = twoDCodes[entry] & 0xff; // Get the code and the number of bits used up code = (entry & 0x78) >>> 3; bits = entry & 0x07; if (code == 0) { // Pass // We always assume WhiteIsZero format for fax. if (!isWhite) { setToBlack(buffer, lineOffset, bitOffset, b2 - bitOffset); } bitOffset = a0 = b2; // Set pointer to only consume the correct number of bits. updatePointer(7 - bits); } else if (code == 1) { // Horizontal // Set pointer to only consume the correct number of bits. updatePointer(7 - bits); // identify the next 2 alternating color codes. int number; if (isWhite) { // Following are white and black runs number = decodeWhiteCodeWord(); bitOffset += number; cce[currIndex++] = bitOffset; number = decodeBlackCodeWord(); setToBlack(buffer, lineOffset, bitOffset, number); bitOffset += number; cce[currIndex++] = bitOffset; } else { // First a black run and then a white run follows number = decodeBlackCodeWord(); setToBlack(buffer, lineOffset, bitOffset, number); bitOffset += number; cce[currIndex++] = bitOffset; number = decodeWhiteCodeWord(); bitOffset += number; cce[currIndex++] = bitOffset; } a0 = bitOffset; } else if (code <= 8) { // Vertical a1 = b1 + (code - 5); cce[currIndex++] = a1; // We write the current color till a1 - 1 pos, // since a1 is where the next color starts if (!isWhite) { setToBlack(buffer, lineOffset, bitOffset, a1 - bitOffset); } bitOffset = a0 = a1; isWhite = !isWhite; updatePointer(7 - bits); } else if (code == 11) { if (nextLesserThan8Bits(3) != 7) { throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.encountered.while.decoding.2d.group.4.compressed.data")); } int zeros = 0; boolean exit = false; while (!exit) { while (nextLesserThan8Bits(1) != 1) { zeros++; } if (zeros > 5) { // Exit code // Zeros before exit code zeros = zeros - 6; if (!isWhite && (zeros > 0)) { cce[currIndex++] = bitOffset; } // Zeros before the exit code bitOffset += zeros; if (zeros > 0) { // Some zeros have been written isWhite = true; } // Read in the bit which specifies the color of // the following run if (nextLesserThan8Bits(1) == 0) { if (!isWhite) { cce[currIndex++] = bitOffset; } isWhite = true; } else { if (isWhite) { cce[currIndex++] = bitOffset; } isWhite = false; } exit = true; } if (zeros == 5) { if (!isWhite) { cce[currIndex++] = bitOffset; } bitOffset += zeros; // Last thing written was white isWhite = true; } else { bitOffset += zeros; cce[currIndex++] = bitOffset; setToBlack(buffer, lineOffset, bitOffset, 1); ++bitOffset; // Last thing written was black isWhite = false; } } } else { //micah_tessler@yahoo.com //Microsoft TIFF renderers seem to treat unknown codes as line-breaks //That is, they give up on the current line and move on to the next one //set bitOffset to w to move on to the next scan line. bitOffset = w; updatePointer(7 - bits); } } // Add the changing element beyond the current scanline for the // other color too //make sure that the index does not exceed the bounds of the array if(currIndex < cce.length) cce[currIndex++] = bitOffset; // Number of changing elements in this scanline. changingElemSize = currIndex; lineOffset += scanlineStride; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
private int decodeWhiteCodeWord() { int current, entry, bits, isT, twoBits, code = -1; int runLength = 0; boolean isWhite = true; while (isWhite) { current = nextNBits(10); entry = white[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x0f; if (bits == 12) { // Additional Make up code // Get the next 2 bits twoBits = nextLesserThan8Bits(2); // Consolidate the 2 new bits and last 2 bits into 4 bits current = ((current << 2) & 0x000c) | twoBits; entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits runLength += code; updatePointer(4 - bits); } else if (bits == 0) { // ERROR throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.encountered")); } else if (bits == 15) { // EOL throw new RuntimeException(MessageLocalization.getComposedMessage("eol.code.word.encountered.in.white.run")); } else { // 11 bits - 0000 0111 1111 1111 = 0x07ff code = (entry >>> 5) & 0x07ff; runLength += code; updatePointer(10 - bits); if (isT == 0) { isWhite = false; } } } return runLength; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
private int decodeBlackCodeWord() { int current, entry, bits, isT, code = -1; int runLength = 0; boolean isWhite = false; while (!isWhite) { current = nextLesserThan8Bits(4); entry = initBlack[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (code == 100) { current = nextNBits(9); entry = black[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (bits == 12) { // Additional makeup codes updatePointer(5); current = nextLesserThan8Bits(4); entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits runLength += code; updatePointer(4 - bits); } else if (bits == 15) { // EOL code throw new RuntimeException(MessageLocalization.getComposedMessage("eol.code.word.encountered.in.black.run")); } else { runLength += code; updatePointer(9 - bits); if (isT == 0) { isWhite = true; } } } else if (code == 200) { // Is a Terminating code current = nextLesserThan8Bits(2); entry = twoBitBlack[current]; code = (entry >>> 5) & 0x07ff; runLength += code; bits = (entry >>> 1) & 0x0f; updatePointer(2 - bits); isWhite = true; } else { // Is a Terminating code runLength += code; updatePointer(4 - bits); isWhite = true; } } return runLength; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
private int readEOL(boolean isFirstEOL) { if (fillBits == 0) { int next12Bits = nextNBits(12); if (isFirstEOL && next12Bits == 0) { // Might have the case of EOL padding being used even // though it was not flagged in the T4Options field. // This was observed to be the case in TIFFs produced // by a well known vendor who shall remain nameless. if(nextNBits(4) == 1) { // EOL must be padded: reset the fillBits flag. fillBits = 1; return 1; } } if(next12Bits != 1) { throw new RuntimeException(MessageLocalization.getComposedMessage("scanline.must.begin.with.eol.code.word")); } } else if (fillBits == 1) { // First EOL code word xxxx 0000 0000 0001 will occur // As many fill bits will be present as required to make // the EOL code of 12 bits end on a byte boundary. int bitsLeft = 8 - bitPointer; if (nextNBits(bitsLeft) != 0) { throw new RuntimeException(MessageLocalization.getComposedMessage("all.fill.bits.preceding.eol.code.must.be.0")); } // If the number of bitsLeft is less than 8, then to have a 12 // bit EOL sequence, two more bytes are certainly going to be // required. The first of them has to be all zeros, so ensure // that. if (bitsLeft < 4) { if (nextNBits(8) != 0) { throw new RuntimeException(MessageLocalization.getComposedMessage("all.fill.bits.preceding.eol.code.must.be.0")); } } // There might be a random number of fill bytes with 0s, so // loop till the EOL of 0000 0001 is found, as long as all // the bytes preceding it are 0's. int n; while ((n = nextNBits(8)) != 1) { // If not all zeros if (n != 0) { throw new RuntimeException(MessageLocalization.getComposedMessage("all.fill.bits.preceding.eol.code.must.be.0")); } } } // If one dimensional encoding mode, then always return 1 if (oneD == 0) { return 1; } else { // Otherwise for 2D encoding mode, // The next one bit signifies 1D/2D encoding of next line. return nextLesserThan8Bits(1); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
private int nextNBits(int bitsToGet) { byte b, next, next2next; int l = data.length - 1; int bp = this.bytePointer; if (fillOrder == 1) { b = data[bp]; if (bp == l) { next = 0x00; next2next = 0x00; } else if ((bp + 1) == l) { next = data[bp + 1]; next2next = 0x00; } else { next = data[bp + 1]; next2next = data[bp + 2]; } } else if (fillOrder == 2) { b = flipTable[data[bp] & 0xff]; if (bp == l) { next = 0x00; next2next = 0x00; } else if ((bp + 1) == l) { next = flipTable[data[bp + 1] & 0xff]; next2next = 0x00; } else { next = flipTable[data[bp + 1] & 0xff]; next2next = flipTable[data[bp + 2] & 0xff]; } } else { throw new RuntimeException(MessageLocalization.getComposedMessage("tiff.fill.order.tag.must.be.either.1.or.2")); } int bitsLeft = 8 - bitPointer; int bitsFromNextByte = bitsToGet - bitsLeft; int bitsFromNext2NextByte = 0; if (bitsFromNextByte > 8) { bitsFromNext2NextByte = bitsFromNextByte - 8; bitsFromNextByte = 8; } bytePointer++; int i1 = (b & table1[bitsLeft]) << (bitsToGet - bitsLeft); int i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte); int i3 = 0; if (bitsFromNext2NextByte != 0) { i2 <<= bitsFromNext2NextByte; i3 = (next2next & table2[bitsFromNext2NextByte]) >>> (8 - bitsFromNext2NextByte); i2 |= i3; bytePointer++; bitPointer = bitsFromNext2NextByte; } else { if (bitsFromNextByte == 8) { bitPointer = 0; bytePointer++; } else { bitPointer = bitsFromNextByte; } } int i = i1 | i2; return i; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecoder.java
private int nextLesserThan8Bits(int bitsToGet) { byte b, next; int l = data.length - 1; int bp = this.bytePointer; if (fillOrder == 1) { b = data[bp]; if (bp == l) { next = 0x00; } else { next = data[bp + 1]; } } else if (fillOrder == 2) { b = flipTable[data[bp] & 0xff]; if (bp == l) { next = 0x00; } else { next = flipTable[data[bp + 1] & 0xff]; } } else { throw new RuntimeException(MessageLocalization.getComposedMessage("tiff.fill.order.tag.must.be.either.1.or.2")); } int bitsLeft = 8 - bitPointer; int bitsFromNextByte = bitsToGet - bitsLeft; int shift = bitsLeft - bitsToGet; int i1, i2; if (shift >= 0) { i1 = (b & table1[bitsLeft]) >>> shift; bitPointer += bitsToGet; if (bitPointer == 8) { bitPointer = 0; bytePointer++; } } else { i1 = (b & table1[bitsLeft]) << (-shift); i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte); i1 |= i2; bytePointer++; bitPointer = bitsFromNextByte; } return i1; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
void decodePass( int xOffset, int yOffset, int xStep, int yStep, int passWidth, int passHeight) { if ((passWidth == 0) || (passHeight == 0)) { return; } int bytesPerRow = (inputBands*passWidth*bitDepth + 7)/8; byte[] curr = new byte[bytesPerRow]; byte[] prior = new byte[bytesPerRow]; // Decode the (sub)image row-by-row int srcY, dstY; for (srcY = 0, dstY = yOffset; srcY < passHeight; srcY++, dstY += yStep) { // Read the filter type byte and a row of data int filter = 0; try { filter = dataStream.read(); dataStream.readFully(curr, 0, bytesPerRow); } catch (Exception e) { // empty on purpose } switch (filter) { case PNG_FILTER_NONE: break; case PNG_FILTER_SUB: decodeSubFilter(curr, bytesPerRow, bytesPerPixel); break; case PNG_FILTER_UP: decodeUpFilter(curr, prior, bytesPerRow); break; case PNG_FILTER_AVERAGE: decodeAverageFilter(curr, prior, bytesPerRow, bytesPerPixel); break; case PNG_FILTER_PAETH: decodePaethFilter(curr, prior, bytesPerRow, bytesPerPixel); break; default: // Error -- uknown filter type throw new RuntimeException(MessageLocalization.getComposedMessage("png.filter.unknown")); } processPixels(curr, xOffset, xStep, dstY, passWidth); // Swap curr and prior byte[] tmp = prior; prior = curr; curr = tmp; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
public void decodeRaw(byte[] buffer, byte[] compData, int w, int h) { this.buffer = buffer; this.data = compData; this.w = w; this.h = h; this.bitsPerScanline = w; this.lineBitNum = 0; this.bitPointer = 0; this.bytePointer = 0; this.prevChangingElems = new int[w + 1]; this.currChangingElems = new int[w + 1]; fails = 0; try { if (compression == TIFFConstants.COMPRESSION_CCITTRLE) { decodeRLE(); } else if (compression == TIFFConstants.COMPRESSION_CCITTFAX3) { decodeT4(); } else if (compression == TIFFConstants.COMPRESSION_CCITTFAX4) { this.uncompressedMode = (int) ((t6Options & 0x02) >> 1); decodeT6(); } else { throw new RuntimeException("Unknown compression type " + compression); } } catch (ArrayIndexOutOfBoundsException e) { //ignore } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
public void decodeT4() { int height = h; int a0, a1, b1, b2; int[] b = new int[2]; int entry, code, bits, color; boolean isWhite; int currIndex = 0; int temp[]; if (data.length < 2) { throw new RuntimeException("Insufficient data to read initial EOL."); } // The data should start with an EOL code int next12 = nextNBits(12); if (next12 != 1) { ++fails; } updatePointer(12); // Find the first one-dimensionally encoded line. int modeFlag = 0; int lines = -1; // indicates imaginary line before first actual line. while (modeFlag != 1) { try { modeFlag = findNextLine(); lines++; // Normally 'lines' will be 0 on exiting loop. } catch (Exception eofe) { throw new RuntimeException("No reference line present."); } } int bitOffset; // Then the 1D encoded scanline data will occur, changing elements // array gets set. decodeNextScanline(); lines++; lineBitNum += bitsPerScanline; while (lines < height) { // Every line must begin with an EOL followed by a bit which // indicates whether the following scanline is 1D or 2D encoded. try { modeFlag = findNextLine(); } catch (Exception eofe) { ++fails; break; } if (modeFlag == 0) { // 2D encoded scanline follows // Initialize previous scanlines changing elements, and // initialize current scanline's changing elements array temp = prevChangingElems; prevChangingElems = currChangingElems; currChangingElems = temp; currIndex = 0; // a0 has to be set just before the start of this scanline. a0 = -1; isWhite = true; bitOffset = 0; lastChangingElement = 0; while (bitOffset < w) { // Get the next changing element getNextChangingElement(a0, isWhite, b); b1 = b[0]; b2 = b[1]; // Get the next seven bits entry = nextLesserThan8Bits(7); // Run these through the 2DCodes table entry = (int) (twoDCodes[entry] & 0xff); // Get the code and the number of bits used up code = (entry & 0x78) >>> 3; bits = entry & 0x07; if (code == 0) { if (!isWhite) { setToBlack(bitOffset, b2 - bitOffset); } bitOffset = a0 = b2; // Set pointer to consume the correct number of bits. updatePointer(7 - bits); } else if (code == 1) { // Horizontal updatePointer(7 - bits); // identify the next 2 codes. int number; if (isWhite) { number = decodeWhiteCodeWord(); bitOffset += number; currChangingElems[currIndex++] = bitOffset; number = decodeBlackCodeWord(); setToBlack(bitOffset, number); bitOffset += number; currChangingElems[currIndex++] = bitOffset; } else { number = decodeBlackCodeWord(); setToBlack(bitOffset, number); bitOffset += number; currChangingElems[currIndex++] = bitOffset; number = decodeWhiteCodeWord(); bitOffset += number; currChangingElems[currIndex++] = bitOffset; } a0 = bitOffset; } else if (code <= 8) { // Vertical a1 = b1 + (code - 5); currChangingElems[currIndex++] = a1; // We write the current color till a1 - 1 pos, // since a1 is where the next color starts if (!isWhite) { setToBlack(bitOffset, a1 - bitOffset); } bitOffset = a0 = a1; isWhite = !isWhite; updatePointer(7 - bits); } else { ++fails; // Find the next one-dimensionally encoded line. int numLinesTested = 0; while (modeFlag != 1) { try { modeFlag = findNextLine(); numLinesTested++; } catch (Exception eofe) { return; } } lines += numLinesTested - 1; updatePointer(13); break; } } // Add the changing element beyond the current scanline for the // other color too currChangingElems[currIndex++] = bitOffset; changingElemSize = currIndex; } else { // modeFlag == 1 // 1D encoded scanline follows decodeNextScanline(); } lineBitNum += bitsPerScanline; lines++; } // while(lines < height) }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
private int decodeWhiteCodeWord() { int current, entry, bits, isT, twoBits, code = -1; int runLength = 0; boolean isWhite = true; while (isWhite) { current = nextNBits(10); entry = white[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x0f; if (bits == 12) { // Additional Make up code // Get the next 2 bits twoBits = nextLesserThan8Bits(2); // Consolidate the 2 new bits and last 2 bits into 4 bits current = ((current << 2) & 0x000c) | twoBits; entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits runLength += code; updatePointer(4 - bits); } else if (bits == 0) { // ERROR throw new RuntimeException("Error 0"); } else if (bits == 15) { // EOL throw new RuntimeException("Error 1"); } else { // 11 bits - 0000 0111 1111 1111 = 0x07ff code = (entry >>> 5) & 0x07ff; runLength += code; updatePointer(10 - bits); if (isT == 0) { isWhite = false; } } } return runLength; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
private int decodeBlackCodeWord() { int current, entry, bits, isT, twoBits, code = -1; int runLength = 0; boolean isWhite = false; while (!isWhite) { current = nextLesserThan8Bits(4); entry = initBlack[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (code == 100) { current = nextNBits(9); entry = black[current]; // Get the 3 fields from the entry isT = entry & 0x0001; bits = (entry >>> 1) & 0x000f; code = (entry >>> 5) & 0x07ff; if (bits == 12) { // Additional makeup codes updatePointer(5); current = nextLesserThan8Bits(4); entry = additionalMakeup[current]; bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111 code = (entry >>> 4) & 0x0fff; // 12 bits runLength += code; updatePointer(4 - bits); } else if (bits == 15) { // EOL code throw new RuntimeException("Error 2"); } else { runLength += code; updatePointer(9 - bits); if (isT == 0) { isWhite = true; } } } else if (code == 200) { // Is a Terminating code current = nextLesserThan8Bits(2); entry = twoBitBlack[current]; code = (entry >>> 5) & 0x07ff; runLength += code; bits = (entry >>> 1) & 0x0f; updatePointer(2 - bits); isWhite = true; } else { // Is a Terminating code runLength += code; updatePointer(4 - bits); isWhite = true; } } return runLength; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
private int findNextLine() { // Set maximum and current bit index into the compressed data. int bitIndexMax = data.length * 8 - 1; int bitIndexMax12 = bitIndexMax - 12; int bitIndex = bytePointer * 8 + bitPointer; // Loop while at least 12 bits are available. while (bitIndex <= bitIndexMax12) { // Get the next 12 bits. int next12Bits = nextNBits(12); bitIndex += 12; // Loop while the 12 bits are not unity, i.e., while the EOL // has not been reached, and there is at least one bit left. while (next12Bits != 1 && bitIndex < bitIndexMax) { next12Bits = ((next12Bits & 0x000007ff) << 1) | (nextLesserThan8Bits(1) & 0x00000001); bitIndex++; } if (next12Bits == 1) { // now positioned just after EOL if (oneD == 1) { // two-dimensional coding if (bitIndex < bitIndexMax) { // check next bit against type of line being sought return nextLesserThan8Bits(1); } } else { return 1; } } } // EOL not found. throw new RuntimeException(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
private int nextNBits(int bitsToGet) { byte b, next, next2next; int l = data.length - 1; int bp = this.bytePointer; if (fillOrder == 1) { b = data[bp]; if (bp == l) { next = 0x00; next2next = 0x00; } else if ((bp + 1) == l) { next = data[bp + 1]; next2next = 0x00; } else { next = data[bp + 1]; next2next = data[bp + 2]; } } else if (fillOrder == 2) { b = flipTable[data[bp] & 0xff]; if (bp == l) { next = 0x00; next2next = 0x00; } else if ((bp + 1) == l) { next = flipTable[data[bp + 1] & 0xff]; next2next = 0x00; } else { next = flipTable[data[bp + 1] & 0xff]; next2next = flipTable[data[bp + 2] & 0xff]; } } else { throw new RuntimeException("Invalid FillOrder"); } int bitsLeft = 8 - bitPointer; int bitsFromNextByte = bitsToGet - bitsLeft; int bitsFromNext2NextByte = 0; if (bitsFromNextByte > 8) { bitsFromNext2NextByte = bitsFromNextByte - 8; bitsFromNextByte = 8; } bytePointer++; int i1 = (b & table1[bitsLeft]) << (bitsToGet - bitsLeft); int i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte); int i3 = 0; if (bitsFromNext2NextByte != 0) { i2 <<= bitsFromNext2NextByte; i3 = (next2next & table2[bitsFromNext2NextByte]) >>> (8 - bitsFromNext2NextByte); i2 |= i3; bytePointer++; bitPointer = bitsFromNext2NextByte; } else { if (bitsFromNextByte == 8) { bitPointer = 0; bytePointer++; } else { bitPointer = bitsFromNextByte; } } int i = i1 | i2; return i; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
private int nextLesserThan8Bits(int bitsToGet) { byte b, next; int l = data.length - 1; int bp = this.bytePointer; if (fillOrder == 1) { b = data[bp]; if (bp == l) { next = 0x00; } else { next = data[bp + 1]; } } else if (fillOrder == 2) { b = flipTable[data[bp] & 0xff]; if (bp == l) { next = 0x00; } else { next = flipTable[data[bp + 1] & 0xff]; } } else { throw new RuntimeException("Invalid FillOrder"); } int bitsLeft = 8 - bitPointer; int bitsFromNextByte = bitsToGet - bitsLeft; int shift = bitsLeft - bitsToGet; int i1, i2; if (shift >= 0) { i1 = (b & table1[bitsLeft]) >>> shift; bitPointer += bitsToGet; if (bitPointer == 8) { bitPointer = 0; bytePointer++; } } else { i1 = (b & table1[bitsLeft]) << (-shift); i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte); i1 |= i2; bytePointer++; bitPointer = bitsFromNextByte; } return i1; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
protected static Image getTiffImageColor(TIFFDirectory dir, RandomAccessFileOrArray s) { try { int compression = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_COMPRESSION); int predictor = 1; TIFFLZWDecoder lzwDecoder = null; switch (compression) { case TIFFConstants.COMPRESSION_NONE: case TIFFConstants.COMPRESSION_LZW: case TIFFConstants.COMPRESSION_PACKBITS: case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: case TIFFConstants.COMPRESSION_OJPEG: case TIFFConstants.COMPRESSION_JPEG: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.compression.1.is.not.supported", compression)); } int photometric = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_PHOTOMETRIC); switch (photometric) { case TIFFConstants.PHOTOMETRIC_MINISWHITE: case TIFFConstants.PHOTOMETRIC_MINISBLACK: case TIFFConstants.PHOTOMETRIC_RGB: case TIFFConstants.PHOTOMETRIC_SEPARATED: case TIFFConstants.PHOTOMETRIC_PALETTE: break; default: if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("the.photometric.1.is.not.supported", photometric)); } float rotation = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ORIENTATION)) { int rot = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ORIENTATION); if (rot == TIFFConstants.ORIENTATION_BOTRIGHT || rot == TIFFConstants.ORIENTATION_BOTLEFT) rotation = (float)Math.PI; else if (rot == TIFFConstants.ORIENTATION_LEFTTOP || rot == TIFFConstants.ORIENTATION_LEFTBOT) rotation = (float)(Math.PI / 2.0); else if (rot == TIFFConstants.ORIENTATION_RIGHTTOP || rot == TIFFConstants.ORIENTATION_RIGHTBOT) rotation = -(float)(Math.PI / 2.0); } if (dir.isTagPresent(TIFFConstants.TIFFTAG_PLANARCONFIG) && dir.getFieldAsLong(TIFFConstants.TIFFTAG_PLANARCONFIG) == TIFFConstants.PLANARCONFIG_SEPARATE) throw new IllegalArgumentException(MessageLocalization.getComposedMessage("planar.images.are.not.supported")); int extraSamples = 0; if (dir.isTagPresent(TIFFConstants.TIFFTAG_EXTRASAMPLES)) extraSamples = 1; int samplePerPixel = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL)) // 1,3,4 samplePerPixel = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_SAMPLESPERPIXEL); int bitsPerSample = 1; if (dir.isTagPresent(TIFFConstants.TIFFTAG_BITSPERSAMPLE)) bitsPerSample = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_BITSPERSAMPLE); switch (bitsPerSample) { case 1: case 2: case 4: case 8: break; default: throw new IllegalArgumentException(MessageLocalization.getComposedMessage("bits.per.sample.1.is.not.supported", bitsPerSample)); } Image img = null; int h = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGELENGTH); int w = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_IMAGEWIDTH); int dpiX = 0; int dpiY = 0; int resolutionUnit = TIFFConstants.RESUNIT_INCH; if (dir.isTagPresent(TIFFConstants.TIFFTAG_RESOLUTIONUNIT)) resolutionUnit = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_RESOLUTIONUNIT); dpiX = getDpi(dir.getField(TIFFConstants.TIFFTAG_XRESOLUTION), resolutionUnit); dpiY = getDpi(dir.getField(TIFFConstants.TIFFTAG_YRESOLUTION), resolutionUnit); int fillOrder = 1; boolean reverse = false; TIFFField fillOrderField = dir.getField(TIFFConstants.TIFFTAG_FILLORDER); if (fillOrderField != null) fillOrder = fillOrderField.getAsInt(0); reverse = (fillOrder == TIFFConstants.FILLORDER_LSB2MSB); int rowsStrip = h; if (dir.isTagPresent(TIFFConstants.TIFFTAG_ROWSPERSTRIP)) //another hack for broken tiffs rowsStrip = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_ROWSPERSTRIP); if (rowsStrip <= 0 || rowsStrip > h) rowsStrip = h; long offset[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPOFFSETS); long size[] = getArrayLongShort(dir, TIFFConstants.TIFFTAG_STRIPBYTECOUNTS); if ((size == null || (size.length == 1 && (size[0] == 0 || size[0] + offset[0] > s.length()))) && h == rowsStrip) { // some TIFF producers are really lousy, so... size = new long[]{s.length() - (int)offset[0]}; } if (compression == TIFFConstants.COMPRESSION_LZW || compression == TIFFConstants.COMPRESSION_DEFLATE || compression == TIFFConstants.COMPRESSION_ADOBE_DEFLATE) { TIFFField predictorField = dir.getField(TIFFConstants.TIFFTAG_PREDICTOR); if (predictorField != null) { predictor = predictorField.getAsInt(0); if (predictor != 1 && predictor != 2) { throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.value.for.predictor.in.tiff.file")); } if (predictor == 2 && bitsPerSample != 8) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.bit.samples.are.not.supported.for.horizontal.differencing.predictor", bitsPerSample)); } } } if (compression == TIFFConstants.COMPRESSION_LZW) { lzwDecoder = new TIFFLZWDecoder(w, predictor, samplePerPixel); } int rowsLeft = h; ByteArrayOutputStream stream = null; ByteArrayOutputStream mstream = null; DeflaterOutputStream zip = null; DeflaterOutputStream mzip = null; if (extraSamples > 0) { mstream = new ByteArrayOutputStream(); mzip = new DeflaterOutputStream(mstream); } CCITTG4Encoder g4 = null; if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4 = new CCITTG4Encoder(w); } else { stream = new ByteArrayOutputStream(); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) zip = new DeflaterOutputStream(stream); } if (compression == TIFFConstants.COMPRESSION_OJPEG) { // Assume that the TIFFTAG_JPEGIFBYTECOUNT tag is optional, since it's obsolete and // is often missing if ((!dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFOFFSET))) { throw new IOException(MessageLocalization.getComposedMessage("missing.tag.s.for.ojpeg.compression")); } int jpegOffset = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFOFFSET); int jpegLength = (int)s.length() - jpegOffset; if (dir.isTagPresent(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT)) { jpegLength = (int)dir.getFieldAsLong(TIFFConstants.TIFFTAG_JPEGIFBYTECOUNT) + (int)size[0]; } byte[] jpeg = new byte[Math.min(jpegLength, (int)s.length() - jpegOffset)]; int posFilePointer = (int)s.getFilePointer(); posFilePointer += jpegOffset; s.seek(posFilePointer); s.readFully(jpeg); img = new Jpeg(jpeg); } else if (compression == TIFFConstants.COMPRESSION_JPEG) { if (size.length > 1) throw new IOException(MessageLocalization.getComposedMessage("compression.jpeg.is.only.supported.with.a.single.strip.this.image.has.1.strips", size.length)); byte[] jpeg = new byte[(int)size[0]]; s.seek(offset[0]); s.readFully(jpeg); // if quantization and/or Huffman tables are stored separately in the tiff, // we need to add them to the jpeg data TIFFField jpegtables = dir.getField(TIFFConstants.TIFFTAG_JPEGTABLES); if (jpegtables != null) { byte[] temp = jpegtables.getAsBytes(); int tableoffset = 0; int tablelength = temp.length; // remove FFD8 from start if (temp[0] == (byte) 0xFF && temp[1] == (byte) 0xD8) { tableoffset = 2; tablelength -= 2; } // remove FFD9 from end if (temp[temp.length-2] == (byte) 0xFF && temp[temp.length-1] == (byte) 0xD9) tablelength -= 2; byte[] tables = new byte[tablelength]; System.arraycopy(temp, tableoffset, tables, 0, tablelength); // TODO insert after JFIF header, instead of at the start byte[] jpegwithtables = new byte[jpeg.length + tables.length]; System.arraycopy(jpeg, 0, jpegwithtables, 0, 2); System.arraycopy(tables, 0, jpegwithtables, 2, tables.length); System.arraycopy(jpeg, 2, jpegwithtables, tables.length+2, jpeg.length-2); jpeg = jpegwithtables; } img = new Jpeg(jpeg); } else { for (int k = 0; k < offset.length; ++k) { byte im[] = new byte[(int)size[k]]; s.seek(offset[k]); s.readFully(im); int height = Math.min(rowsStrip, rowsLeft); byte outBuf[] = null; if (compression != TIFFConstants.COMPRESSION_NONE) outBuf = new byte[(w * bitsPerSample * samplePerPixel + 7) / 8 * height]; if (reverse) TIFFFaxDecoder.reverseBits(im); switch (compression) { case TIFFConstants.COMPRESSION_DEFLATE: case TIFFConstants.COMPRESSION_ADOBE_DEFLATE: inflate(im, outBuf); applyPredictor(outBuf, predictor, w, height, samplePerPixel); break; case TIFFConstants.COMPRESSION_NONE: outBuf = im; break; case TIFFConstants.COMPRESSION_PACKBITS: decodePackbits(im, outBuf); break; case TIFFConstants.COMPRESSION_LZW: lzwDecoder.decode(im, outBuf, height); break; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { g4.fax4Encode(outBuf, height); } else { if (extraSamples > 0) ProcessExtraSamples(zip, mzip, outBuf, samplePerPixel, bitsPerSample, w, height); else zip.write(outBuf); } rowsLeft -= rowsStrip; } if (bitsPerSample == 1 && samplePerPixel == 1 && photometric != TIFFConstants.PHOTOMETRIC_PALETTE) { img = Image.getInstance(w, h, false, Image.CCITTG4, photometric == TIFFConstants.PHOTOMETRIC_MINISBLACK ? Image.CCITT_BLACKIS1 : 0, g4.close()); } else { zip.close(); img = new ImgRaw(w, h, samplePerPixel - extraSamples, bitsPerSample, stream.toByteArray()); img.setDeflated(true); } } img.setDpi(dpiX, dpiY); if (compression != TIFFConstants.COMPRESSION_OJPEG && compression != TIFFConstants.COMPRESSION_JPEG) { if (dir.isTagPresent(TIFFConstants.TIFFTAG_ICCPROFILE)) { try { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_ICCPROFILE); ICC_Profile icc_prof = ICC_Profile.getInstance(fd.getAsBytes()); if (samplePerPixel - extraSamples == icc_prof.getNumComponents()) img.tagICC(icc_prof); } catch (RuntimeException e) { //empty } } if (dir.isTagPresent(TIFFConstants.TIFFTAG_COLORMAP)) { TIFFField fd = dir.getField(TIFFConstants.TIFFTAG_COLORMAP); char rgb[] = fd.getAsChars(); byte palette[] = new byte[rgb.length]; int gColor = rgb.length / 3; int bColor = gColor * 2; for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)(rgb[k] >>> 8); palette[k * 3 + 1] = (byte)(rgb[k + gColor] >>> 8); palette[k * 3 + 2] = (byte)(rgb[k + bColor] >>> 8); } // Colormap components are supposed to go from 0 to 655535 but, // as usually, some tiff producers just put values from 0 to 255. // Let's check for these broken tiffs. boolean colormapBroken = true; for (int k = 0; k < palette.length; ++k) { if (palette[k] != 0) { colormapBroken = false; break; } } if (colormapBroken) { for (int k = 0; k < gColor; ++k) { palette[k * 3] = (byte)rgb[k]; palette[k * 3 + 1] = (byte)rgb[k + gColor]; palette[k * 3 + 2] = (byte)rgb[k + bColor]; } } PdfArray indexed = new PdfArray(); indexed.add(PdfName.INDEXED); indexed.add(PdfName.DEVICERGB); indexed.add(new PdfNumber(gColor - 1)); indexed.add(new PdfString(palette)); PdfDictionary additional = new PdfDictionary(); additional.put(PdfName.COLORSPACE, indexed); img.setAdditional(additional); } img.setOriginalType(Image.ORIGINAL_TIFF); } if (photometric == TIFFConstants.PHOTOMETRIC_MINISWHITE) img.setInverted(true); if (rotation != 0) img.setInitialRotation(rotation); if (extraSamples > 0) { mzip.close(); Image mimg = Image.getInstance(w, h, 1, bitsPerSample, mstream.toByteArray()); mimg.makeMask(); mimg.setDeflated(true); img.setImageMask(mimg); } return img; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleBookmark.java
public void startElement(String tag, Map<String, String> h) { if (topList == null) { if (tag.equals("Bookmark")) { topList = new ArrayList<HashMap<String, Object>>(); return; } else throw new RuntimeException(MessageLocalization.getComposedMessage("root.element.is.not.bookmark.1", tag)); } if (!tag.equals("Title")) throw new RuntimeException(MessageLocalization.getComposedMessage("tag.1.not.allowed", tag)); HashMap<String, Object> attributes = new HashMap<String, Object>(h); attributes.put("Title", ""); attributes.remove("Kids"); attr.push(attributes); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEAN.java
public Rectangle getBarcodeSize() { float width = 0; float height = barHeight; if (font != null) { if (baseline <= 0) height += -baseline + size; else height += baseline - font.getFontDescriptor(BaseFont.DESCENT, size); } switch (codeType) { case EAN13: width = x * (11 + 12 * 7); if (font != null) { width += font.getWidthPoint(code.charAt(0), size); } break; case EAN8: width = x * (11 + 8 * 7); break; case UPCA: width = x * (11 + 12 * 7); if (font != null) { width += font.getWidthPoint(code.charAt(0), size) + font.getWidthPoint(code.charAt(11), size); } break; case UPCE: width = x * (9 + 6 * 7); if (font != null) { width += font.getWidthPoint(code.charAt(0), size) + font.getWidthPoint(code.charAt(7), size); } break; case SUPP2: width = x * (6 + 2 * 7); break; case SUPP5: width = x * (4 + 5 * 7 + 4 * 2); break; default: throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.type")); } return new Rectangle(width, height); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEAN.java
public java.awt.Image createAwtImage(java.awt.Color foreground, java.awt.Color background) { int f = foreground.getRGB(); int g = background.getRGB(); java.awt.Canvas canvas = new java.awt.Canvas(); int width = 0; byte bars[] = null; switch (codeType) { case EAN13: bars = getBarsEAN13(code); width = 11 + 12 * 7; break; case EAN8: bars = getBarsEAN8(code); width = 11 + 8 * 7; break; case UPCA: bars = getBarsEAN13("0" + code); width = 11 + 12 * 7; break; case UPCE: bars = getBarsUPCE(code); width = 9 + 6 * 7; break; case SUPP2: bars = getBarsSupplemental2(code); width = 6 + 2 * 7; break; case SUPP5: bars = getBarsSupplemental5(code); width = 4 + 5 * 7 + 4 * 2; break; default: throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.code.type")); } boolean print = true; int ptr = 0; int height = (int)barHeight; int pix[] = new int[width * height]; for (int k = 0; k < bars.length; ++k) { int w = bars[k]; int c = g; if (print) c = f; print = !print; for (int j = 0; j < w; ++j) pix[ptr++] = c; } for (int k = width; k < pix.length; k += width) { System.arraycopy(pix, 0, pix, k, width); } java.awt.Image img = canvas.createImage(new java.awt.image.MemoryImageSource(width, height, pix, 0, width)); return img; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSpotColor.java
protected PdfObject getSpotObject(PdfWriter writer) { PdfArray array = new PdfArray(PdfName.SEPARATION); array.add(name); PdfFunction func = null; if (altcs instanceof ExtendedColor) { int type = ((ExtendedColor)altcs).type; switch (type) { case ExtendedColor.TYPE_GRAY: array.add(PdfName.DEVICEGRAY); func = PdfFunction.type2(writer, new float[]{0, 1}, null, new float[]{0}, new float[]{((GrayColor)altcs).getGray()}, 1); break; case ExtendedColor.TYPE_CMYK: array.add(PdfName.DEVICECMYK); CMYKColor cmyk = (CMYKColor)altcs; func = PdfFunction.type2(writer, new float[]{0, 1}, null, new float[]{0, 0, 0, 0}, new float[]{cmyk.getCyan(), cmyk.getMagenta(), cmyk.getYellow(), cmyk.getBlack()}, 1); break; default: throw new RuntimeException(MessageLocalization.getComposedMessage("only.rgb.gray.and.cmyk.are.supported.as.alternative.color.spaces")); } } else { array.add(PdfName.DEVICERGB); func = PdfFunction.type2(writer, new float[]{0, 1}, null, new float[]{1, 1, 1}, new float[]{(float)altcs.getRed() / 255, (float)altcs.getGreen() / 255, (float)altcs.getBlue() / 255}, 1); } array.add(func.getReference()); return array; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
protected ArrayList<float []> convertColumn(final float cLine[]) { if (cLine.length < 4) throw new RuntimeException(MessageLocalization.getComposedMessage("no.valid.column.line.found")); ArrayList<float []> cc = new ArrayList<float []>(); for (int k = 0; k < cLine.length - 2; k += 2) { float x1 = cLine[k]; float y1 = cLine[k + 1]; float x2 = cLine[k + 2]; float y2 = cLine[k + 3]; if (y1 == y2) continue; // x = ay + b float a = (x1 - x2) / (y1 - y2); float b = x1 - a * y1; float r[] = new float[4]; r[0] = Math.min(y1, y2); r[1] = Math.max(y1, y2); r[2] = a; r[3] = b; cc.add(r); maxY = Math.max(maxY, r[1]); minY = Math.min(minY, r[0]); } if (cc.isEmpty()) throw new RuntimeException(MessageLocalization.getComposedMessage("no.valid.column.line.found")); return cc; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ColumnText.java
public void setRunDirection(final int runDirection) { if (runDirection < PdfWriter.RUN_DIRECTION_DEFAULT || runDirection > PdfWriter.RUN_DIRECTION_RTL) throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.run.direction.1", runDirection)); this.runDirection = runDirection; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setFieldProperty(String field, String name, Object value, int inst[]) { if (writer == null) throw new RuntimeException(MessageLocalization.getComposedMessage("this.acrofields.instance.is.read.only")); try { Item item = fields.get(field); if (item == null) return false; InstHit hit = new InstHit(inst); PdfDictionary merged; PdfString da; if (name.equalsIgnoreCase("textfont")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); PdfDictionary dr = merged.getAsDict(PdfName.DR); if (da != null) { if (dr == null) { dr = new PdfDictionary(); merged.put(PdfName.DR, dr); } Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { BaseFont bf = (BaseFont)value; PdfName psn = PdfAppearance.stdFieldFontNames.get(bf.getPostscriptFontName()); if (psn == null) { psn = new PdfName(bf.getPostscriptFontName()); } PdfDictionary fonts = dr.getAsDict(PdfName.FONT); if (fonts == null) { fonts = new PdfDictionary(); dr.put(PdfName.FONT, fonts); } PdfIndirectReference fref = (PdfIndirectReference)fonts.get(psn); PdfDictionary top = reader.getCatalog().getAsDict(PdfName.ACROFORM); markUsed(top); dr = top.getAsDict(PdfName.DR); if (dr == null) { dr = new PdfDictionary(); top.put(PdfName.DR, dr); } markUsed(dr); PdfDictionary fontsTop = dr.getAsDict(PdfName.FONT); if (fontsTop == null) { fontsTop = new PdfDictionary(); dr.put(PdfName.FONT, fontsTop); } markUsed(fontsTop); PdfIndirectReference frefTop = (PdfIndirectReference)fontsTop.get(psn); if (frefTop != null) { if (fref == null) fonts.put(psn, frefTop); } else if (fref == null) { FontDetails fd; if (bf.getFontType() == BaseFont.FONT_TYPE_DOCUMENT) { fd = new FontDetails(null, ((DocumentFont)bf).getIndirectReference(), bf); } else { bf.setSubset(false); fd = writer.addSimple(bf); localFonts.put(psn.toString().substring(1), bf); } fontsTop.put(psn, fd.getIndirectReference()); fonts.put(psn, fd.getIndirectReference()); } ByteBuffer buf = cb.getInternalBuffer(); buf.append(psn.getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf "); if (dao[DA_COLOR] != null) cb.setColorFill((BaseColor)dao[DA_COLOR]); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("textcolor")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); if (da != null) { Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { ByteBuffer buf = cb.getInternalBuffer(); buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)dao[DA_SIZE]).floatValue()).append(" Tf "); cb.setColorFill((BaseColor)value); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("textsize")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); da = merged.getAsString(PdfName.DA); if (da != null) { Object dao[] = splitDAelements(da.toUnicodeString()); PdfAppearance cb = new PdfAppearance(); if (dao[DA_FONT] != null) { ByteBuffer buf = cb.getInternalBuffer(); buf.append(new PdfName((String)dao[DA_FONT]).getBytes()).append(' ').append(((Float)value).floatValue()).append(" Tf "); if (dao[DA_COLOR] != null) cb.setColorFill((BaseColor)dao[DA_COLOR]); PdfString s = new PdfString(cb.toString()); item.getMerged(k).put(PdfName.DA, s); item.getWidget(k).put(PdfName.DA, s); markUsed(item.getWidget(k)); } } } } } else if (name.equalsIgnoreCase("bgcolor") || name.equalsIgnoreCase("bordercolor")) { PdfName dname = name.equalsIgnoreCase("bgcolor") ? PdfName.BG : PdfName.BC; for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { merged = item.getMerged( k ); PdfDictionary mk = merged.getAsDict(PdfName.MK); if (mk == null) { if (value == null) return true; mk = new PdfDictionary(); item.getMerged(k).put(PdfName.MK, mk); item.getWidget(k).put(PdfName.MK, mk); markUsed(item.getWidget(k)); } else { markUsed( mk ); } if (value == null) mk.remove(dname); else mk.put(dname, PdfFormField.getMKColor((BaseColor)value)); } } } else return false; return true; } catch (Exception e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/AcroFields.java
public boolean setFieldProperty(String field, String name, int value, int inst[]) { if (writer == null) throw new RuntimeException(MessageLocalization.getComposedMessage("this.acrofields.instance.is.read.only")); Item item = fields.get(field); if (item == null) return false; InstHit hit = new InstHit(inst); if (name.equalsIgnoreCase("flags")) { PdfNumber num = new PdfNumber(value); for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { item.getMerged(k).put(PdfName.F, num); item.getWidget(k).put(PdfName.F, num); markUsed(item.getWidget(k)); } } } else if (name.equalsIgnoreCase("setflags")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { PdfNumber num = item.getWidget(k).getAsNumber(PdfName.F); int val = 0; if (num != null) val = num.intValue(); num = new PdfNumber(val | value); item.getMerged(k).put(PdfName.F, num); item.getWidget(k).put(PdfName.F, num); markUsed(item.getWidget(k)); } } } else if (name.equalsIgnoreCase("clrflags")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { PdfDictionary widget = item.getWidget( k ); PdfNumber num = widget.getAsNumber(PdfName.F); int val = 0; if (num != null) val = num.intValue(); num = new PdfNumber(val & ~value); item.getMerged(k).put(PdfName.F, num); widget.put(PdfName.F, num); markUsed(widget); } } } else if (name.equalsIgnoreCase("fflags")) { PdfNumber num = new PdfNumber(value); for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { item.getMerged(k).put(PdfName.FF, num); item.getValue(k).put(PdfName.FF, num); markUsed(item.getValue(k)); } } } else if (name.equalsIgnoreCase("setfflags")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { PdfDictionary valDict = item.getValue( k ); PdfNumber num = valDict.getAsNumber( PdfName.FF ); int val = 0; if (num != null) val = num.intValue(); num = new PdfNumber(val | value); item.getMerged(k).put(PdfName.FF, num); valDict.put(PdfName.FF, num); markUsed(valDict); } } } else if (name.equalsIgnoreCase("clrfflags")) { for (int k = 0; k < item.size(); ++k) { if (hit.isHit(k)) { PdfDictionary valDict = item.getValue( k ); PdfNumber num = valDict.getAsNumber(PdfName.FF); int val = 0; if (num != null) val = num.intValue(); num = new PdfNumber(val & ~value); item.getMerged(k).put(PdfName.FF, num); valDict.put(PdfName.FF, num); markUsed(valDict); } } } else return false; return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
public void endElement(String tag) { if (tag.equals("Destination")) { if (xmlLast == null && xmlNames != null) return; else throw new RuntimeException(MessageLocalization.getComposedMessage("destination.end.tag.out.of.place")); } if (!tag.equals("Name")) throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.end.tag.1", tag)); if (xmlLast == null || xmlNames == null) throw new RuntimeException(MessageLocalization.getComposedMessage("name.end.tag.out.of.place")); if (!xmlLast.containsKey("Page")) throw new RuntimeException(MessageLocalization.getComposedMessage("page.attribute.missing")); xmlNames.put(unEscapeBinaryString(xmlLast.get("Name")), xmlLast.get("Page")); xmlLast = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/SimpleNamedDestination.java
public void startElement(String tag, Map<String, String> h) { if (xmlNames == null) { if (tag.equals("Destination")) { xmlNames = new HashMap<String, String>(); return; } else throw new RuntimeException(MessageLocalization.getComposedMessage("root.element.is.not.destination")); } if (!tag.equals("Name")) throw new RuntimeException(MessageLocalization.getComposedMessage("tag.1.not.allowed", tag)); if (xmlLast != null) throw new RuntimeException(MessageLocalization.getComposedMessage("nested.tags.are.not.allowed")); xmlLast = new HashMap<String, String>(h); xmlLast.put("Name", ""); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStream.java
public void flateCompress(int compressionLevel) { if (!Document.compress) return; // check if the flateCompress-method has already been if (compressed) { return; } this.compressionLevel = compressionLevel; if (inputStream != null) { compressed = true; return; } // check if a filter already exists PdfObject filter = PdfReader.getPdfObject(get(PdfName.FILTER)); if (filter != null) { if (filter.isName()) { if (PdfName.FLATEDECODE.equals(filter)) return; } else if (filter.isArray()) { if (((PdfArray) filter).contains(PdfName.FLATEDECODE)) return; } else { throw new RuntimeException(MessageLocalization.getComposedMessage("stream.could.not.be.compressed.filter.is.not.a.name.or.array")); } } try { // compress ByteArrayOutputStream stream = new ByteArrayOutputStream(); Deflater deflater = new Deflater(compressionLevel); DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater); if (streamBytes != null) streamBytes.writeTo(zip); else zip.write(bytes); zip.close(); deflater.end(); // update the object streamBytes = stream; bytes = null; put(PdfName.LENGTH, new PdfNumber(streamBytes.size())); if (filter == null) { put(PdfName.FILTER, PdfName.FLATEDECODE); } else { PdfArray filters = new PdfArray(filter); filters.add(PdfName.FLATEDECODE); put(PdfName.FILTER, filters); } compressed = true; } catch(IOException ioe) { throw new ExceptionConverter(ioe); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPages.java
void setLinearMode(PdfIndirectReference topParent) { if (parents.size() > 1) throw new RuntimeException(MessageLocalization.getComposedMessage("linear.page.mode.can.only.be.called.with.a.single.parent")); if (topParent != null) { this.topParent = topParent; parents.clear(); parents.add(topParent); } leafSize = 10000000; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAction.java
static PdfArray buildArray(Object names[]) { PdfArray array = new PdfArray(); for (int k = 0; k < names.length; ++k) { Object obj = names[k]; if (obj instanceof String) array.add(new PdfString((String)obj)); else if (obj instanceof PdfAnnotation) array.add(((PdfAnnotation)obj).getIndirectReference()); else throw new RuntimeException(MessageLocalization.getComposedMessage("the.array.must.contain.string.or.pdfannotation")); } return array; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfContentByte getDirectContent() { if (!open) throw new RuntimeException(MessageLocalization.getComposedMessage("the.document.is.not.open")); return directContent; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public PdfContentByte getDirectContentUnder() { if (!open) throw new RuntimeException(MessageLocalization.getComposedMessage("the.document.is.not.open")); return directContentUnder; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
Override public void close() { if (open) { if (currentPageNumber - 1 != pageReferences.size()) throw new RuntimeException("The page " + pageReferences.size() + " was requested but the document has only " + (currentPageNumber - 1) + " pages."); pdf.close(); try { addSharedObjectsToBody(); for (PdfOCG layer : documentOCG) { addToBody(layer.getPdfObject(), layer.getRef()); } // add the root to the body PdfIndirectReference rootRef = root.writePageTree(); // make the catalog-object and add it to the body PdfDictionary catalog = getCatalog(rootRef); // [C9] if there is XMP data to add: add it if (xmpMetadata != null) { PdfStream xmp = new PdfStream(xmpMetadata); 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); } catalog.put(PdfName.METADATA, body.add(xmp).getIndirectReference()); } // [C10] make pdfx conformant if (isPdfX()) { completeInfoDictionary(getInfo()); completeExtraCatalog(getExtraCatalog()); } // [C11] Output Intents if (extraCatalog != null) { catalog.mergeDifferent(extraCatalog); } writeOutlines(catalog, false); // add the Catalog to the body PdfIndirectObject indirectCatalog = addToBody(catalog, false); // add the info-object to the body PdfIndirectObject infoObj = addToBody(getInfo(), false); // [F1] encryption PdfIndirectReference encryption = null; PdfObject fileID = null; body.flushObjStm(); if (crypto != null) { PdfIndirectObject encryptionObject = addToBody(crypto.getEncryptionDictionary(), false); encryption = encryptionObject.getIndirectReference(); fileID = crypto.getFileID(); } else fileID = PdfEncryption.createInfoId(PdfEncryption.createDocumentId()); // write the cross-reference table of the body body.writeCrossReferenceTable(os, indirectCatalog.getIndirectReference(), infoObj.getIndirectReference(), encryption, fileID, prevxref); // make the trailer // [F2] full compression 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(), indirectCatalog.getIndirectReference(), infoObj.getIndirectReference(), encryption, fileID, prevxref); trailer.toPdf(this, os); } super.close(); } catch(IOException ioe) { throw new ExceptionConverter(ioe); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
public void setRunDirection(final int runDirection) { if (runDirection < RUN_DIRECTION_NO_BIDI || runDirection > RUN_DIRECTION_RTL) throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.run.direction.1", runDirection)); this.runDirection = runDirection; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
ColorDetails addSimplePatternColorspace(final BaseColor color) { int type = ExtendedColor.getType(color); if (type == ExtendedColor.TYPE_PATTERN || type == ExtendedColor.TYPE_SHADING) throw new RuntimeException(MessageLocalization.getComposedMessage("an.uncolored.tile.pattern.can.not.have.another.pattern.or.shading.as.color")); try { switch (type) { case ExtendedColor.TYPE_RGB: if (patternColorspaceRGB == null) { patternColorspaceRGB = new ColorDetails(getColorspaceName(), body.getPdfIndirectReference(), null); PdfArray array = new PdfArray(PdfName.PATTERN); array.add(PdfName.DEVICERGB); addToBody(array, patternColorspaceRGB.getIndirectReference()); } return patternColorspaceRGB; case ExtendedColor.TYPE_CMYK: if (patternColorspaceCMYK == null) { patternColorspaceCMYK = new ColorDetails(getColorspaceName(), body.getPdfIndirectReference(), null); PdfArray array = new PdfArray(PdfName.PATTERN); array.add(PdfName.DEVICECMYK); addToBody(array, patternColorspaceCMYK.getIndirectReference()); } return patternColorspaceCMYK; case ExtendedColor.TYPE_GRAY: if (patternColorspaceGRAY == null) { patternColorspaceGRAY = new ColorDetails(getColorspaceName(), body.getPdfIndirectReference(), null); PdfArray array = new PdfArray(PdfName.PATTERN); array.add(PdfName.DEVICEGRAY); addToBody(array, patternColorspaceGRAY.getIndirectReference()); } return patternColorspaceGRAY; case ExtendedColor.TYPE_SEPARATION: { ColorDetails details = addSimple(((SpotColor)color).getPdfSpotColor()); ColorDetails patternDetails = documentSpotPatterns.get(details); if (patternDetails == null) { patternDetails = new ColorDetails(getColorspaceName(), body.getPdfIndirectReference(), null); PdfArray array = new PdfArray(PdfName.PATTERN); array.add(details.getIndirectReference()); addToBody(array, patternDetails.getIndirectReference()); documentSpotPatterns.put(details, patternDetails); } return patternDetails; } default: throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.color.type")); } } catch (Exception e) { throw new RuntimeException(e.getMessage()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfImportedPage.java
void throwError() { throw new RuntimeException(MessageLocalization.getComposedMessage("content.can.not.be.added.to.a.pdfimportedpage")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfSignatureAppearance.java
public void setRunDirection(int runDirection) { if (runDirection < PdfWriter.RUN_DIRECTION_DEFAULT || runDirection > PdfWriter.RUN_DIRECTION_RTL) throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.run.direction.1", runDirection)); this.runDirection = runDirection; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
void insertPage(int pageNumber, Rectangle mediabox) { Rectangle media = new Rectangle(mediabox); int rotation = media.getRotation() % 360; PdfDictionary page = new PdfDictionary(PdfName.PAGE); PdfDictionary resources = new PdfDictionary(); PdfArray procset = new PdfArray(); procset.add(PdfName.PDF); procset.add(PdfName.TEXT); procset.add(PdfName.IMAGEB); procset.add(PdfName.IMAGEC); procset.add(PdfName.IMAGEI); resources.put(PdfName.PROCSET, procset); page.put(PdfName.RESOURCES, resources); page.put(PdfName.ROTATE, new PdfNumber(rotation)); page.put(PdfName.MEDIABOX, new PdfRectangle(media, rotation)); PRIndirectReference pref = reader.addPdfObject(page); PdfDictionary parent; PRIndirectReference parentRef; if (pageNumber > reader.getNumberOfPages()) { PdfDictionary lastPage = reader.getPageNRelease(reader.getNumberOfPages()); parentRef = (PRIndirectReference)lastPage.get(PdfName.PARENT); parentRef = new PRIndirectReference(reader, parentRef.getNumber()); parent = (PdfDictionary)PdfReader.getPdfObject(parentRef); PdfArray kids = (PdfArray)PdfReader.getPdfObject(parent.get(PdfName.KIDS), parent); kids.add(pref); markUsed(kids); reader.pageRefs.insertPage(pageNumber, pref); } else { if (pageNumber < 1) pageNumber = 1; PdfDictionary firstPage = reader.getPageN(pageNumber); PRIndirectReference firstPageRef = reader.getPageOrigRef(pageNumber); reader.releasePage(pageNumber); parentRef = (PRIndirectReference)firstPage.get(PdfName.PARENT); parentRef = new PRIndirectReference(reader, parentRef.getNumber()); parent = (PdfDictionary)PdfReader.getPdfObject(parentRef); PdfArray kids = (PdfArray)PdfReader.getPdfObject(parent.get(PdfName.KIDS), parent); int len = kids.size(); int num = firstPageRef.getNumber(); for (int k = 0; k < len; ++k) { PRIndirectReference cur = (PRIndirectReference)kids.getPdfObject(k); if (num == cur.getNumber()) { kids.add(k, pref); break; } } if (len == kids.size()) throw new RuntimeException(MessageLocalization.getComposedMessage("internal.inconsistence")); markUsed(kids); reader.pageRefs.insertPage(pageNumber, pref); correctAcroFieldPages(pageNumber); } page.put(PdfName.PARENT, parentRef); while (parent != null) { markUsed(parent); PdfNumber count = (PdfNumber)PdfReader.getPdfObjectRelease(parent.get(PdfName.COUNT)); parent.put(PdfName.COUNT, new PdfNumber(count.intValue() + 1)); parent = parent.getAsDict(PdfName.PARENT); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void addAnnotation(PdfAnnotation annot) { throw new RuntimeException(MessageLocalization.getComposedMessage("unsupported.in.this.context.use.pdfstamper.addannotation")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfShadingPattern.java
public void setMatrix(float matrix[]) { if (matrix.length != 6) throw new RuntimeException(MessageLocalization.getComposedMessage("the.matrix.size.must.be.6")); this.matrix = matrix; }
// 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/LZWDecoder.java
public void decode(byte data[], OutputStream uncompData) { if(data[0] == (byte)0x00 && data[1] == (byte)0x01) { throw new RuntimeException(MessageLocalization.getComposedMessage("lzw.flavour.not.supported")); } initializeStringTable(); this.data = data; this.uncompData = uncompData; // Initialize pointers bytePointer = 0; bitPointer = 0; nextData = 0; nextBits = 0; int code, oldCode = 0; byte string[]; while ((code = getNextCode()) != 257) { if (code == 256) { initializeStringTable(); code = getNextCode(); if (code == 257) { break; } writeString(stringTable[code]); oldCode = code; } else { if (code < tableIndex) { string = stringTable[code]; writeString(string); addStringToTable(stringTable[oldCode], string[0]); oldCode = code; } else { string = stringTable[oldCode]; string = composeString(string, string[0]); writeString(string); addStringToTable(string); oldCode = code; } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] decodePredictor(final byte in[], final PdfObject dicPar) { if (dicPar == null || !dicPar.isDictionary()) return in; PdfDictionary dic = (PdfDictionary)dicPar; PdfObject obj = getPdfObject(dic.get(PdfName.PREDICTOR)); if (obj == null || !obj.isNumber()) return in; int predictor = ((PdfNumber)obj).intValue(); if (predictor < 10 && predictor != 2) return in; int width = 1; obj = getPdfObject(dic.get(PdfName.COLUMNS)); if (obj != null && obj.isNumber()) width = ((PdfNumber)obj).intValue(); int colors = 1; obj = getPdfObject(dic.get(PdfName.COLORS)); if (obj != null && obj.isNumber()) colors = ((PdfNumber)obj).intValue(); int bpc = 8; obj = getPdfObject(dic.get(PdfName.BITSPERCOMPONENT)); if (obj != null && obj.isNumber()) bpc = ((PdfNumber)obj).intValue(); DataInputStream dataStream = new DataInputStream(new ByteArrayInputStream(in)); ByteArrayOutputStream fout = new ByteArrayOutputStream(in.length); int bytesPerPixel = colors * bpc / 8; int bytesPerRow = (colors*width*bpc + 7)/8; byte[] curr = new byte[bytesPerRow]; byte[] prior = new byte[bytesPerRow]; if (predictor == 2) { if (bpc == 8) { int numRows = in.length / bytesPerRow; for (int row = 0; row < numRows; row++) { int rowStart = row * bytesPerRow; for (int col = 0 + bytesPerPixel; col < bytesPerRow; col++) { in[rowStart + col] = (byte)(in[rowStart + col] + in[rowStart + col - bytesPerPixel]); } } } return in; } // Decode the (sub)image row-by-row while (true) { // Read the filter type byte and a row of data int filter = 0; try { filter = dataStream.read(); if (filter < 0) { return fout.toByteArray(); } dataStream.readFully(curr, 0, bytesPerRow); } catch (Exception e) { return fout.toByteArray(); } switch (filter) { case 0: //PNG_FILTER_NONE break; case 1: //PNG_FILTER_SUB for (int i = bytesPerPixel; i < bytesPerRow; i++) { curr[i] += curr[i - bytesPerPixel]; } break; case 2: //PNG_FILTER_UP for (int i = 0; i < bytesPerRow; i++) { curr[i] += prior[i]; } break; case 3: //PNG_FILTER_AVERAGE for (int i = 0; i < bytesPerPixel; i++) { curr[i] += prior[i] / 2; } for (int i = bytesPerPixel; i < bytesPerRow; i++) { curr[i] += ((curr[i - bytesPerPixel] & 0xff) + (prior[i] & 0xff))/2; } break; case 4: //PNG_FILTER_PAETH for (int i = 0; i < bytesPerPixel; i++) { curr[i] += prior[i]; } for (int i = bytesPerPixel; i < bytesPerRow; i++) { int a = curr[i - bytesPerPixel] & 0xff; int b = prior[i] & 0xff; int c = prior[i - bytesPerPixel] & 0xff; int p = a + b - c; int pa = Math.abs(p - a); int pb = Math.abs(p - b); int pc = Math.abs(p - c); int ret; if (pa <= pb && pa <= pc) { ret = a; } else if (pb <= pc) { ret = b; } else { ret = c; } curr[i] += (byte)ret; } break; default: // Error -- unknown filter type throw new RuntimeException(MessageLocalization.getComposedMessage("png.filter.unknown")); } try { fout.write(curr); } catch (IOException ioe) { // Never happens } // Swap curr and prior byte[] tmp = prior; prior = curr; curr = tmp; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] ASCIIHexDecode(final byte in[]) { ByteArrayOutputStream out = new ByteArrayOutputStream(); boolean first = true; int n1 = 0; for (int k = 0; k < in.length; ++k) { int ch = in[k] & 0xff; if (ch == '>') break; if (PRTokeniser.isWhitespace(ch)) continue; int n = PRTokeniser.getHex(ch); if (n == -1) throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.character.in.asciihexdecode")); if (first) n1 = n; else out.write((byte)((n1 << 4) + n)); first = !first; } if (!first) out.write((byte)(n1 << 4)); return out.toByteArray(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfReader.java
public static byte[] ASCII85Decode(final byte in[]) { ByteArrayOutputStream out = new ByteArrayOutputStream(); int state = 0; int chn[] = new int[5]; for (int k = 0; k < in.length; ++k) { int ch = in[k] & 0xff; if (ch == '~') break; if (PRTokeniser.isWhitespace(ch)) continue; if (ch == 'z' && state == 0) { out.write(0); out.write(0); out.write(0); out.write(0); continue; } if (ch < '!' || ch > 'u') throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.character.in.ascii85decode")); chn[state] = ch - '!'; ++state; if (state == 5) { state = 0; int r = 0; for (int j = 0; j < 5; ++j) r = r * 85 + chn[j]; out.write((byte)(r >> 24)); out.write((byte)(r >> 16)); out.write((byte)(r >> 8)); out.write((byte)r); } } int r = 0; // We'll ignore the next two lines for the sake of perpetuating broken PDFs // if (state == 1) // throw new RuntimeException(MessageLocalization.getComposedMessage("illegal.length.in.ascii85decode")); if (state == 2) { r = chn[0] * 85 * 85 * 85 * 85 + chn[1] * 85 * 85 * 85 + 85 * 85 * 85 + 85 * 85 + 85; out.write((byte)(r >> 24)); } else if (state == 3) { r = chn[0] * 85 * 85 * 85 * 85 + chn[1] * 85 * 85 * 85 + chn[2] * 85 * 85 + 85 * 85 + 85; out.write((byte)(r >> 24)); out.write((byte)(r >> 16)); } else if (state == 4) { r = chn[0] * 85 * 85 * 85 * 85 + chn[1] * 85 * 85 * 85 + chn[2] * 85 * 85 + chn[3] * 85 + 85; out.write((byte)(r >> 24)); out.write((byte)(r >> 16)); out.write((byte)(r >> 8)); } return out.toByteArray(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/BitMatrix.java
public int getDimension() { if (width != height) { throw new RuntimeException("Can't call getDimension() on a non-square matrix"); } return width; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/QRCode.java
public int at(int x, int y) { // The value must be zero or one. int value = matrix.get(x, y); if (!(value == 0 || value == 1)) { // this is really like an assert... not sure what better exception to use? throw new RuntimeException("Bad value"); } return value; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void add(final PdfContentByte other) { if (other.writer != null && writer != other.writer) throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.writers.are.you.mixing.two.documents")); content.append(other.content); markedContentSize += other.markedContentSize; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public PdfPatternPainter createPattern(final float width, final float height, final float xstep, final float ystep) { checkWriter(); if ( xstep == 0.0f || ystep == 0.0f ) throw new RuntimeException(MessageLocalization.getComposedMessage("xstep.or.ystep.can.not.be.zero")); PdfPatternPainter painter = new PdfPatternPainter(writer); painter.setWidth(width); painter.setHeight(height); painter.setXStep(xstep); painter.setYStep(ystep); writer.addSimplePattern(painter); return painter; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public PdfPatternPainter createPattern(final float width, final float height, final float xstep, final float ystep, final BaseColor color) { checkWriter(); if ( xstep == 0.0f || ystep == 0.0f ) throw new RuntimeException(MessageLocalization.getComposedMessage("xstep.or.ystep.can.not.be.zero")); PdfPatternPainter painter = new PdfPatternPainter(writer, color); painter.setWidth(width); painter.setHeight(height); painter.setXStep(xstep); painter.setYStep(ystep); writer.addSimplePattern(painter); return painter; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
void outputColorNumbers(final BaseColor color, final float tint) { PdfWriter.checkPdfIsoConformance(writer, PdfIsoKeys.PDFISOKEY_COLOR, color); int type = ExtendedColor.getType(color); switch (type) { case ExtendedColor.TYPE_RGB: content.append((float)color.getRed() / 0xFF); content.append(' '); content.append((float)color.getGreen() / 0xFF); content.append(' '); content.append((float)color.getBlue() / 0xFF); break; case ExtendedColor.TYPE_GRAY: content.append(((GrayColor)color).getGray()); break; case ExtendedColor.TYPE_CMYK: { CMYKColor cmyk = (CMYKColor)color; content.append(cmyk.getCyan()).append(' ').append(cmyk.getMagenta()); content.append(' ').append(cmyk.getYellow()).append(' ').append(cmyk.getBlack()); break; } case ExtendedColor.TYPE_SEPARATION: content.append(tint); break; default: throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.color.type")); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void setPatternFill(final PdfPatternPainter p, final BaseColor color, final float tint) { checkWriter(); if (!p.isStencil()) throw new RuntimeException(MessageLocalization.getComposedMessage("an.uncolored.pattern.was.expected")); PageResources prs = getPageResources(); PdfName name = writer.addSimplePattern(p); name = prs.addPattern(name, p.getIndirectReference()); ColorDetails csDetail = writer.addSimplePatternColorspace(color); PdfName cName = prs.addColor(csDetail.getColorName(), csDetail.getIndirectReference()); saveColor(new UncoloredPattern(p, color, tint), true); content.append(cName.getBytes()).append(" cs").append_i(separator); outputColorNumbers(color, tint); content.append(' ').append(name.getBytes()).append(" scn").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
public void setPatternStroke(final PdfPatternPainter p, final BaseColor color, final float tint) { checkWriter(); if (!p.isStencil()) throw new RuntimeException(MessageLocalization.getComposedMessage("an.uncolored.pattern.was.expected")); PageResources prs = getPageResources(); PdfName name = writer.addSimplePattern(p); name = prs.addPattern(name, p.getIndirectReference()); ColorDetails csDetail = writer.addSimplePatternColorspace(color); PdfName cName = prs.addColor(csDetail.getColorName(), csDetail.getIndirectReference()); saveColor(new UncoloredPattern(p, color, tint), false); content.append(cName.getBytes()).append(" CS").append_i(separator); outputColorNumbers(color, tint); content.append(' ').append(name.getBytes()).append(" SCN").append_i(separator); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfContentByte.java
void checkNoPattern(final PdfTemplate t) { if (t.getType() == PdfTemplate.TYPE_PATTERN) throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.use.of.a.pattern.a.template.was.expected")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public void close() { if (close) { return; } try { if (isTagged(writer)) { flushFloatingElements(); flushLines(); writer.getDirectContent().closeMCBlock(this); writer.flushTaggedObjects(); } boolean wasImage = imageWait != null; newPage(); if (imageWait != null || wasImage) newPage(); if (annotationsImp.hasUnusedAnnotations()) throw new RuntimeException(MessageLocalization.getComposedMessage("not.all.annotations.could.be.added.to.the.document.the.document.doesn.t.have.enough.pages")); PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) pageEvent.onCloseDocument(writer, this); super.close(); writer.addLocalDestinations(localDestinations); calculateOutlineCount(); writeOutlines(); } catch(Exception e) { throw ExceptionConverter.convertException(e); } writer.close(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
Override public boolean newPage() { try { flushFloatingElements(); } catch (DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } lastElementType = -1; if (isPageEmpty()) { setNewPageSizeAndMargins(); return false; } if (!open || close) { throw new RuntimeException(MessageLocalization.getComposedMessage("the.document.is.not.open")); } PdfPageEvent pageEvent = writer.getPageEvent(); if (pageEvent != null) pageEvent.onEndPage(writer, this); //Added to inform any listeners that we are moving to a new page (added by David Freels) super.newPage(); // the following 2 lines were added by Pelikan Stephan indentation.imageIndentLeft = 0; indentation.imageIndentRight = 0; try { // we flush the arraylist with recently written lines flushLines(); // we prepare the elements of the page dictionary // [U1] page size and rotation int rotation = pageSize.getRotation(); // [C10] if (writer.isPdfIso()) { if (thisBoxSize.containsKey("art") && thisBoxSize.containsKey("trim")) throw new PdfXConformanceException(MessageLocalization.getComposedMessage("only.one.of.artbox.or.trimbox.can.exist.in.the.page")); if (!thisBoxSize.containsKey("art") && !thisBoxSize.containsKey("trim")) { if (thisBoxSize.containsKey("crop")) thisBoxSize.put("trim", thisBoxSize.get("crop")); else thisBoxSize.put("trim", new PdfRectangle(pageSize, pageSize.getRotation())); } } // [M1] pageResources.addDefaultColorDiff(writer.getDefaultColorspace()); if (writer.isRgbTransparencyBlending()) { PdfDictionary dcs = new PdfDictionary(); dcs.put(PdfName.CS, PdfName.DEVICERGB); pageResources.addDefaultColorDiff(dcs); } PdfDictionary resources = pageResources.getResources(); // we create the page dictionary PdfPage page = new PdfPage(new PdfRectangle(pageSize, rotation), thisBoxSize, resources, rotation); if (isTagged(writer)) { page.put(PdfName.TABS, PdfName.S); } else { page.put(PdfName.TABS, writer.getTabs()); } page.putAll(writer.getPageDictEntries()); writer.resetPageDictEntries(); // we complete the page dictionary // [U3] page actions: additional actions if (pageAA != null) { page.put(PdfName.AA, writer.addToBody(pageAA).getIndirectReference()); pageAA = null; } // [C5] and [C8] we add the annotations if (annotationsImp.hasUnusedAnnotations()) { PdfArray array = annotationsImp.rotateAnnotations(writer, pageSize); if (array.size() != 0) page.put(PdfName.ANNOTS, array); } // [F12] we add tag info if (isTagged(writer)) page.put(PdfName.STRUCTPARENTS, new PdfNumber(writer.getCurrentPageNumber() - 1)); if (text.size() > textEmptySize || isTagged(writer)) text.endText(); else text = null; ArrayList<IAccessibleElement> mcBlocks = null; if (isTagged(writer)) { mcBlocks = writer.getDirectContent().saveMCBlocks(); } writer.add(page, new PdfContents(writer.getDirectContentUnder(), graphics, !isTagged(writer) ? text : null, writer.getDirectContent(), pageSize)); // we initialize the new page initPage(); if (isTagged(writer)) { writer.getDirectContentUnder().restoreMCBlocks(mcBlocks); } } catch(DocumentException de) { // maybe this never happens, but it's better to check. throw new ExceptionConverter(de); } catch (IOException ioe) { throw new ExceptionConverter(ioe); } return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addJavaScript(final PdfAction js) { if (js.get(PdfName.JS) == null) throw new RuntimeException(MessageLocalization.getComposedMessage("only.javascript.actions.are.allowed")); try { documentLevelJS.put(SIXTEEN_DIGITS.format(jsCounter++), writer.addToBody(js).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDocument.java
void addJavaScript(final String name, final PdfAction js) { if (js.get(PdfName.JS) == null) throw new RuntimeException(MessageLocalization.getComposedMessage("only.javascript.actions.are.allowed")); try { documentLevelJS.put(name, writer.addToBody(js).getIndirectReference()); } catch (IOException e) { throw new ExceptionConverter(e); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfdfReader.java
public void startElement(String tag, Map<String, String> h) { if ( !foundRoot ) { if (!tag.equals("xfdf")) throw new RuntimeException(MessageLocalization.getComposedMessage("root.element.is.not.xfdf.1", tag)); else foundRoot = true; } if ( tag.equals("xfdf") ){ } else if ( tag.equals("f") ) { fileSpec = h.get( "href" ); } else if ( tag.equals("fields") ) { fields = new HashMap<String, String>(); // init it! listFields = new HashMap<String, List<String>>(); } else if ( tag.equals("field") ) { String fName = h.get( "name" ); fieldNames.push( fName ); } else if ( tag.equals("value") ) { fieldValues.push( "" ); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPatternPainter.java
void checkNoColor() { if (stencil) throw new RuntimeException(MessageLocalization.getComposedMessage("colors.are.not.allowed.in.uncolored.tile.patterns")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfAnnotation.java
public static PdfArray getMKColor(BaseColor color) { PdfArray array = new PdfArray(); int type = ExtendedColor.getType(color); switch (type) { case ExtendedColor.TYPE_GRAY: { array.add(new PdfNumber(((GrayColor)color).getGray())); break; } case ExtendedColor.TYPE_CMYK: { CMYKColor cmyk = (CMYKColor)color; array.add(new PdfNumber(cmyk.getCyan())); array.add(new PdfNumber(cmyk.getMagenta())); array.add(new PdfNumber(cmyk.getYellow())); array.add(new PdfNumber(cmyk.getBlack())); break; } case ExtendedColor.TYPE_SEPARATION: case ExtendedColor.TYPE_PATTERN: case ExtendedColor.TYPE_SHADING: throw new RuntimeException(MessageLocalization.getComposedMessage("separations.patterns.and.shadings.are.not.allowed.in.mk.dictionary")); default: array.add(new PdfNumber(color.getRed() / 255f)); array.add(new PdfNumber(color.getGreen() / 255f)); array.add(new PdfNumber(color.getBlue() / 255f)); } return array; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapByteCid.java
private void encodeSequence(byte seqs[], char cid) { int size = seqs.length - 1; int nextPlane = 0; for (int idx = 0; idx < size; ++idx) { char plane[] = planes.get(nextPlane); int one = seqs[idx] & 0xff; char c = plane[one]; if (c != 0 && (c & 0x8000) == 0) throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.mapping")); if (c == 0) { planes.add(new char[256]); c = (char)(planes.size() - 1 | 0x8000); plane[one] = c; } nextPlane = c & 0x7fff; } char plane[] = planes.get(nextPlane); int one = seqs[size] & 0xff; char c = plane[one]; if ((c & 0x8000) != 0) throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.mapping")); plane[one] = cid; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/fonts/cmaps/CMapParserEx.java
private static void encodeSequence(int size, byte seqs[], char cid, ArrayList<char[]> planes) { --size; int nextPlane = 0; for (int idx = 0; idx < size; ++idx) { char plane[] = planes.get(nextPlane); int one = seqs[idx] & 0xff; char c = plane[one]; if (c != 0 && (c & 0x8000) == 0) throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.mapping")); if (c == 0) { planes.add(new char[256]); c = (char)(planes.size() - 1 | 0x8000); plane[one] = c; } nextPlane = c & 0x7fff; } char plane[] = planes.get(nextPlane); int one = seqs[size] & 0xff; char c = plane[one]; if ((c & 0x8000) != 0) throw new RuntimeException(MessageLocalization.getComposedMessage("inconsistent.mapping")); plane[one] = cid; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public float writeSelectedRows(int colStart, int colEnd, int rowStart, int rowEnd, final float xPos, float yPos, final PdfContentByte[] canvases, final boolean reusable) { if (totalWidth <= 0) throw new RuntimeException(MessageLocalization.getComposedMessage("the.table.width.must.be.greater.than.zero")); int totalRows = rows.size(); if (rowStart < 0) rowStart = 0; if (rowEnd < 0) rowEnd = totalRows; else rowEnd = Math.min(rowEnd, totalRows); if (rowStart >= rowEnd) return yPos; int totalCols = getNumberOfColumns(); if (colStart < 0) colStart = 0; else colStart = Math.min(colStart, totalCols); if (colEnd < 0) colEnd = totalCols; else colEnd = Math.min(colEnd, totalCols); LOGGER.info(String.format("Writing row %s to %s; column %s to %s", rowStart, rowEnd, colStart, colEnd)); float yPosStart = yPos; PdfPTableBody currentBlock = null; for (int k = rowStart; k < rowEnd; ++k) { PdfPRow row = rows.get(k); if (getHeader().rows != null && getHeader().rows.contains(row) && currentBlock == null) { currentBlock = openTableBlock(getHeader(), canvases[TEXTCANVAS]); } else if (getBody().rows != null && getBody().rows.contains(row) && currentBlock == null) { currentBlock = openTableBlock(getBody(), canvases[TEXTCANVAS]); } else if (getFooter().rows != null && getFooter().rows.contains(row) && currentBlock == null) { currentBlock = openTableBlock(getFooter(), canvases[TEXTCANVAS]); } if (row != null) { row.writeCells(colStart, colEnd, xPos, yPos, canvases, reusable); yPos -= row.getMaxHeights(); } if (getHeader().rows != null && getHeader().rows.contains(row) && (k == rowEnd - 1 || !getHeader().rows.contains(rows.get(k + 1)))) { currentBlock = closeTableBlock(getHeader(), canvases[TEXTCANVAS]); } else if (getBody().rows != null && getBody().rows.contains(row) && (k == rowEnd - 1 || !getBody().rows.contains(rows.get(k + 1)))) { currentBlock = closeTableBlock(getBody(), canvases[TEXTCANVAS]); } else if (getFooter().rows != null && getFooter().rows.contains(row) && (k == rowEnd - 1 || !getFooter().rows.contains(rows.get(k + 1)))) { currentBlock = closeTableBlock(getFooter(), canvases[TEXTCANVAS]); } } if (tableEvent != null && colStart == 0 && colEnd == totalCols) { float heights[] = new float[rowEnd - rowStart + 1]; heights[0] = yPosStart; for (int k = rowStart; k < rowEnd; ++k) { PdfPRow row = rows.get(k); float hr = 0; if (row != null) hr = row.getMaxHeights(); heights[k - rowStart + 1] = heights[k - rowStart] - hr; } tableEvent.tableLayout(this, getEventWidths(xPos, rowStart, rowEnd, headersInEvent), heights, headersInEvent ? headerRows : 0, rowStart, canvases); } return yPos; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfPTable.java
public void setRunDirection(final int runDirection) { switch (runDirection) { case PdfWriter.RUN_DIRECTION_DEFAULT: case PdfWriter.RUN_DIRECTION_NO_BIDI: case PdfWriter.RUN_DIRECTION_LTR: case PdfWriter.RUN_DIRECTION_RTL: this.runDirection = runDirection; break; default: throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.run.direction.1", runDirection)); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/Barcode128.java
public static String getRawText(String text, boolean ucc) { String out = ""; int tLen = text.length(); if (tLen == 0) { out += START_B; if (ucc) out += FNC1_INDEX; return out; } int c = 0; for (int k = 0; k < tLen; ++k) { c = text.charAt(k); if (c > 127 && c != FNC1) throw new RuntimeException(MessageLocalization.getComposedMessage("there.are.illegal.characters.for.barcode.128.in.1", text)); } c = text.charAt(0); char currentCode = START_B; int index = 0; if (isNextDigits(text, index, 2)) { currentCode = START_C; out += currentCode; if (ucc) out += FNC1_INDEX; String out2 = getPackedRawDigits(text, index, 2); index += out2.charAt(0); out += out2.substring(1); } else if (c < ' ') { currentCode = START_A; out += currentCode; if (ucc) out += FNC1_INDEX; out += (char)(c + 64); ++index; } else { out += currentCode; if (ucc) out += FNC1_INDEX; if (c == FNC1) out += FNC1_INDEX; else out += (char)(c - ' '); ++index; } while (index < tLen) { switch (currentCode) { case START_A: { if (isNextDigits(text, index, 4)) { currentCode = START_C; out += CODE_AB_TO_C; String out2 = getPackedRawDigits(text, index, 4); index += out2.charAt(0); out += out2.substring(1); } else { c = text.charAt(index++); if (c == FNC1) out += FNC1_INDEX; else if (c > '_') { currentCode = START_B; out += CODE_AC_TO_B; out += (char)(c - ' '); } else if (c < ' ') out += (char)(c + 64); else out += (char)(c - ' '); } } break; case START_B: { if (isNextDigits(text, index, 4)) { currentCode = START_C; out += CODE_AB_TO_C; String out2 = getPackedRawDigits(text, index, 4); index += out2.charAt(0); out += out2.substring(1); } else { c = text.charAt(index++); if (c == FNC1) out += FNC1_INDEX; else if (c < ' ') { currentCode = START_A; out += CODE_BC_TO_A; out += (char)(c + 64); } else { out += (char)(c - ' '); } } } break; case START_C: { if (isNextDigits(text, index, 2)) { String out2 = getPackedRawDigits(text, index, 2); index += out2.charAt(0); out += out2.substring(1); } else { c = text.charAt(index++); if (c == FNC1) out += FNC1_INDEX; else if (c < ' ') { currentCode = START_A; out += CODE_BC_TO_A; out += (char)(c + 64); } else { currentCode = START_B; out += CODE_AC_TO_B; out += (char)(c - ' '); } } } break; } } return out; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
public static Rectangle getRectangle(String name) { name = name.trim().toUpperCase(); int pos = name.indexOf(' '); if (pos == -1) { try { Field field = PageSize.class.getDeclaredField(name.toUpperCase()); return (Rectangle) field.get(null); } catch (Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name)); } } else { try { String width = name.substring(0, pos); String height = name.substring(pos + 1); return new Rectangle(Float.parseFloat(width), Float.parseFloat(height)); } catch(Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage())); } } }
5
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFFaxDecompressor.java
catch (Exception eofe) { throw new RuntimeException("No reference line present."); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfWriter.java
catch (Exception e) { throw new RuntimeException(e.getMessage()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfNumber.java
catch (NumberFormatException nfe){ throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.number.2", content, nfe.toString())); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch (Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("can.t.find.page.size.1", name)); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/PageSize.java
catch(Exception e) { throw new RuntimeException(MessageLocalization.getComposedMessage("1.is.not.a.valid.page.size.format.2", name, e.getMessage())); }
0 8
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/BmpImage.java
catch (RuntimeException e) { //empty on purpose }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/PngImage.java
catch (RuntimeException e) { icc_profile = null; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e) { // let's flip the fill bits and try again... tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS; try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e2) { throw e; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e2) { throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e) { //empty }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e) { //empty }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfDestination.java
catch (RuntimeException e) { add(new PdfNull()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (RuntimeException e){ close(); throw e; }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e) { // let's flip the fill bits and try again... tiffT4Options ^= TIFFConstants.GROUP3OPT_FILLBITS; try { decoder.decode2D(outBuf, im, 0, height, tiffT4Options); } catch (RuntimeException e2) { throw e; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TiffImage.java
catch (RuntimeException e2) { throw e; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
catch (RuntimeException e){ close(); throw e; }
0
unknown (Lib) SAXException 0 0 2 2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
catch(SAXException e) { xmp = new PdfStream(altMetadata); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (SAXException e) { throw new ExceptionConverter(e); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/XfaForm.java
catch (SAXException e) { throw new ExceptionConverter(e); }
1
checked (Lib) Throwable 0 0 1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/MappedRandomAccessFile.java
Override protected void finalize() throws Throwable { close(); super.finalize(); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BaseFont.java
catch (Throwable e) {}
0 0
unknown (Lib) UnsupportedEncodingException 0 0 4
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/xml/XmlDomWriter.java
public void setOutput(OutputStream stream, String encoding) throws UnsupportedEncodingException { if (encoding == null) { encoding = "UTF8"; } java.io.Writer writer = new OutputStreamWriter(stream, encoding); fOut = new PrintWriter(writer); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
private byte[] convertToBytesAfterGlyphSubstitution(final String text) throws UnsupportedEncodingException { if (!canApplyGlyphSubstitution()) { throw new IllegalArgumentException("Make sure the font type if TTF Unicode and a valid GlyphSubstitutionTable exists!"); } Map<String, Glyph> glyphSubstitutionMap = ttu.getGlyphSubstitutionMap(); // generate a regex from the characters to be substituted // for Indic languages: push back the CompositeCharacters with smaller length Set<String> compositeCharacters = new TreeSet<String>(new IndicCompositeCharacterComparator()); compositeCharacters.addAll(glyphSubstitutionMap.keySet()); // convert the text to a list of Glyph, also take care of the substitution ArrayBasedStringTokenizer tokenizer = new ArrayBasedStringTokenizer(compositeCharacters.toArray(new String[0])); String[] tokens = tokenizer.tokenize(text); List<Glyph> glyphList = new ArrayList<Glyph>(50); for (String token : tokens) { // first check whether this is in the substitution map Glyph subsGlyph = glyphSubstitutionMap.get(token); if (subsGlyph != null) { glyphList.add(subsGlyph); } else { // break up the string into individual characters for (char c : token.toCharArray()) { int[] metrics = ttu.getMetricsTT(c); int glyphCode = metrics[0]; int glyphWidth = metrics[1]; glyphList.add(new Glyph(glyphCode, glyphWidth, String.valueOf(c))); } } } GlyphRepositioner glyphRepositioner = getGlyphRepositioner(); if (glyphRepositioner != null) { glyphRepositioner.repositionGlyphs(glyphList); } char[] charEncodedGlyphCodes = new char[glyphList.size()]; // process each Glyph thus obtained for (int i = 0; i < glyphList.size(); i++) { Glyph glyph = glyphList.get(i); charEncodedGlyphCodes[i] = (char) glyph.code; Integer glyphCode = Integer.valueOf(glyph.code); if (!longTag.containsKey(glyphCode)) { // FIXME: this is buggy as the 3rd arg. should be a String as a Glyph can represent more than 1 char longTag.put(glyphCode, new int[]{glyph.code, glyph.width, glyph.chars.charAt(0)}); } } return new String(charEncodedGlyphCodes).getBytes(CJKFont.CJK_ENCODING); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeDatamatrix.java
public int generate(String text) throws UnsupportedEncodingException { byte[] t = text.getBytes("iso-8859-1"); return generate(t, 0, t.length); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ByteBuffer.java
public String toString(String enc) throws UnsupportedEncodingException { return new String(buf, 0, count, enc); }
14
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch (java.io.UnsupportedEncodingException uue) { return new String( outBuff, 0, e ); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/Base64.java
catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaFont.java
catch (UnsupportedEncodingException e) { faceName = new String(name, 0, k); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
catch (UnsupportedEncodingException e) { s = new String(text, 0, k); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/wmf/MetaDo.java
catch (UnsupportedEncodingException e) { s = new String(text, 0, k); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { return false; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
6
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfEncodings.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/FontDetails.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/ICC_Profile.java
catch (UnsupportedEncodingException e) { throw new ExceptionConverter(e); }
4
runtime (Lib) UnsupportedOperationException 18
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/WritableDirectElement.java
public boolean process(final ElementListener listener) { throw new UnsupportedOperationException(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/WritableDirectElement.java
public boolean isNestable() { throw new UnsupportedOperationException(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/codec/TIFFLZWDecoder.java
public byte[] decode(byte data[], byte uncompData[], int h) { if(data[0] == (byte)0x00 && data[1] == (byte)0x01) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("tiff.5.0.style.lzw.codes.are.not.supported")); } initializeStringTable(); this.data = data; this.h = h; this.uncompData = uncompData; // Initialize pointers bytePointer = 0; bitPointer = 0; dstIndex = 0; nextData = 0; nextBits = 0; int code, oldCode = 0; byte string[]; while ( ((code = getNextCode()) != 257) && dstIndex < uncompData.length) { if (code == 256) { initializeStringTable(); code = getNextCode(); if (code == 257) { break; } writeString(stringTable[code]); oldCode = code; } else { if (code < tableIndex) { string = stringTable[code]; writeString(string); addStringToTable(stringTable[oldCode], string[0]); oldCode = code; } else { string = stringTable[oldCode]; string = composeString(string, string[0]); writeString(string); addStringToTable(string); oldCode = code; } } } // Horizontal Differencing Predictor if (predictor == 2) { int count; for (int j = 0; j < h; j++) { count = samplesPerPixel * (j * w + 1); for (int i = samplesPerPixel; i < w * samplesPerPixel; i++) { uncompData[count] += uncompData[count - samplesPerPixel]; count++; } } } return uncompData; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/LongHashtable.java
public void remove() { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("remove.not.supported")); }
// 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/IntHashtable.java
public void remove() { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("remove.not.supported")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
boolean partialFormFlattening(String name) { getAcroFields(); if (acroFields.getXfa().isXfaPresent()) throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("partial.form.flattening.is.not.supported.with.xfa.forms")); if (!acroFields.getFields().containsKey(name)) return false; partialFlattening.add(name); return true; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setPageAction(PdfName actionType, PdfAction action) throws PdfException { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.setpageaction.pdfname.actiontype.pdfaction.action.int.page")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setDuration(int seconds) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.setpageaction.pdfname.actiontype.pdfaction.action.int.page")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setTransition(PdfTransition transition) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.setpageaction.pdfname.actiontype.pdfaction.action.int.page")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setOpenAction(String name) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("open.actions.by.name.are.not.supported")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public void setThumbnail(com.itextpdf.text.Image image) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.pdfstamper.setthumbnail")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public PdfContentByte getDirectContentUnder() { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.pdfstamper.getundercontent.or.pdfstamper.getovercontent")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfStamperImp.java
Override public PdfContentByte getDirectContent() { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("use.pdfstamper.getundercontent.or.pdfstamper.getovercontent")); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/PdfCopy.java
Override public void setPageEvent(PdfPageEvent event) { throw new UnsupportedOperationException(); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeEANSUPP.java
public java.awt.Image createAwtImage(java.awt.Color foreground, java.awt.Color background) { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("the.two.barcodes.must.be.composed.externally")); }
// 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/RectangleReadOnly.java
private void throwReadOnlyError() { throw new UnsupportedOperationException(MessageLocalization.getComposedMessage("rectanglereadonly.this.rectangle.is.read.only")); }
0 0 0 0 0
checked (Domain) UnsupportedPdfException
public class UnsupportedPdfException extends InvalidPdfException {

	/** a serial version UID */
	private static final long serialVersionUID = 2180764250839096628L;

	/**
	 * Creates an instance of an UnsupportedPdfException.
	 * @param	message	the reason why the document isn't a PDF document according to iText.
	 */
	public UnsupportedPdfException(String message) {
		super(message);
	}
}
12
            
// 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/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/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; }
0 0 0 0 0
unknown (Domain) VerificationException
public class VerificationException extends GeneralSecurityException {

	/** A Serial Version UID */
	private static final long serialVersionUID = 2978604513926438256L;
	
	/**
	 * Creates a VerificationException
	 */
	public VerificationException(Certificate cert, String message) {
		super(String.format("Certificate %s failed: %s", cert == null ? "Unknown" : ((X509Certificate)cert).getSubjectDN().getName(), message));
	}
}
6
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
protected PdfPKCS7 coversWholeDocument() throws GeneralSecurityException { PdfPKCS7 pkcs7 = fields.verifySignature(signatureName); if (fields.signatureCoversWholeDocument(signatureName)) { LOGGER.info("The timestamp covers whole document."); } else { throw new VerificationException(null, "Signature doesn't cover whole document."); } if (pkcs7.verify()) { LOGGER.info("The signed document has not been modified."); return pkcs7; } else { throw new VerificationException(null, "The document was altered after the final signature was applied."); } }
// 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/CRLVerifier.java
public boolean verify(X509CRL crl, X509Certificate signCert, X509Certificate issuerCert, Date signDate) throws GeneralSecurityException { if (crl == null || signDate == null) return false; // We only check CRLs valid on the signing date for which the issuer matches if (crl.getIssuerX500Principal().equals(signCert.getIssuerX500Principal()) && signDate.after(crl.getThisUpdate()) && signDate.before(crl.getNextUpdate())) { // the signing certificate may not be revoked if (isSignatureValid(crl, issuerCert) && crl.isRevoked(signCert)) { throw new VerificationException(signCert, "The certificate has been revoked."); } 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"); }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/LtvVerifier.java
catch(GeneralSecurityException e) { throw new VerificationException(signCert, "Couldn't verify with CRL or OCSP or trusted anchor"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/security/OCSPVerifier.java
catch(GeneralSecurityException e) { if (super.verify(responderCert, issuerCert, null).size() == 0) throw new VerificationException(responderCert, "Responder certificate couldn't be verified"); }
0 0 0 0
checked (Domain) WriterException
public final class WriterException extends Exception {

	/**
	 * A serial version UID.
	 */
	private static final long serialVersionUID = 1L;
	
	public WriterException() {
		super();
	}
	
	public WriterException(String message) {
		super(message);
	}

}
34
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void embedDataBits(BitVector dataBits, int maskPattern, ByteMatrix matrix) throws WriterException { int bitIndex = 0; int direction = -1; // Start from the right bottom cell. int x = matrix.getWidth() - 1; int y = matrix.getHeight() - 1; while (x > 0) { // Skip the vertical timing pattern. if (x == 6) { x -= 1; } while (y >= 0 && y < matrix.getHeight()) { for (int i = 0; i < 2; ++i) { int xx = x - i; // Skip the cell if it's not empty. if (!isEmpty(matrix.get(xx, y))) { continue; } int bit; if (bitIndex < dataBits.size()) { bit = dataBits.at(bitIndex); ++bitIndex; } else { // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described // in 8.4.9 of JISX0510:2004 (p. 24). bit = 0; } // Skip masking if mask_pattern is -1. if (maskPattern != -1) { if (MaskUtil.getDataMaskBit(maskPattern, xx, y)) { bit ^= 0x1; } } matrix.set(xx, y, bit); } y += direction; } direction = -direction; // Reverse the direction. y += direction; x -= 2; // Move to the left. } // All bits should be consumed. if (bitIndex != dataBits.size()) { throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitVector bits) throws WriterException { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new WriterException("Invalid mask pattern"); } int typeInfo = (ecLevel.getBits() << 3) | maskPattern; bits.appendBits(typeInfo, 5); int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); bits.appendBits(bchCode, 10); BitVector maskBits = new BitVector(); maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); bits.xor(maskBits); if (bits.size() != 15) { // Just in case. throw new WriterException("should not happen but we got: " + bits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void makeVersionInfoBits(int version, BitVector bits) throws WriterException { bits.appendBits(version, 6); int bchCode = calculateBCHCode(version, VERSION_INFO_POLY); bits.appendBits(bchCode, 12); if (bits.size() != 18) { // Just in case. throw new WriterException("should not happen but we got: " + bits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedTimingPatterns(ByteMatrix matrix) throws WriterException { // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical // separation patterns (size 1). Thus, 8 = 7 + 1. for (int i = 8; i < matrix.getWidth() - 8; ++i) { int bit = (i + 1) % 2; // Horizontal line. if (!isValidValue(matrix.get(i, 6))) { throw new WriterException(); } if (isEmpty(matrix.get(i, 6))) { matrix.set(i, 6, bit); } // Vertical line. if (!isValidValue(matrix.get(6, i))) { throw new WriterException(); } if (isEmpty(matrix.get(6, i))) { matrix.set(6, i, bit); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) throws WriterException { if (matrix.get(8, matrix.getHeight() - 8) == 0) { throw new WriterException(); } matrix.set(8, matrix.getHeight() - 8, 1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedHorizontalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (HORIZONTAL_SEPARATION_PATTERN[0].length != 8 || HORIZONTAL_SEPARATION_PATTERN.length != 1) { throw new WriterException("Bad horizontal separation pattern"); } for (int x = 0; x < 8; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart))) { throw new WriterException(); } matrix.set(xStart + x, yStart, HORIZONTAL_SEPARATION_PATTERN[0][x]); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedVerticalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (VERTICAL_SEPARATION_PATTERN[0].length != 1 || VERTICAL_SEPARATION_PATTERN.length != 7) { throw new WriterException("Bad vertical separation pattern"); } for (int y = 0; y < 7; ++y) { if (!isEmpty(matrix.get(xStart, yStart + y))) { throw new WriterException(); } matrix.set(xStart, yStart + y, VERTICAL_SEPARATION_PATTERN[y][0]); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedPositionAdjustmentPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (POSITION_ADJUSTMENT_PATTERN[0].length != 5 || POSITION_ADJUSTMENT_PATTERN.length != 5) { throw new WriterException("Bad position adjustment"); } for (int y = 0; y < 5; ++y) { for (int x = 0; x < 5; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart + y))) { throw new WriterException(); } matrix.set(xStart + x, yStart + y, POSITION_ADJUSTMENT_PATTERN[y][x]); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedPositionDetectionPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (POSITION_DETECTION_PATTERN[0].length != 7 || POSITION_DETECTION_PATTERN.length != 7) { throw new WriterException("Bad position detection pattern"); } for (int y = 0; y < 7; ++y) { for (int x = 0; x < 7; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart + y))) { throw new WriterException(); } matrix.set(xStart + x, yStart + y, POSITION_DETECTION_PATTERN[y][x]); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
public static void encode(String content, ErrorCorrectionLevel ecLevel, Map<EncodeHintType,Object> hints, QRCode qrCode) throws WriterException { String encoding = hints == null ? null : (String) hints.get(EncodeHintType.CHARACTER_SET); if (encoding == null) { encoding = DEFAULT_BYTE_MODE_ENCODING; } // Step 1: Choose the mode (encoding). Mode mode = chooseMode(content, encoding); // Step 2: Append "bytes" into "dataBits" in appropriate encoding. BitVector dataBits = new BitVector(); appendBytes(content, mode, dataBits, encoding); // Step 3: Initialize QR code that can contain "dataBits". int numInputBytes = dataBits.sizeInBytes(); initQRCode(numInputBytes, ecLevel, mode, qrCode); // Step 4: Build another bit vector that contains header and data. BitVector headerAndDataBits = new BitVector(); // Step 4.5: Append ECI message if applicable if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.equals(encoding)) { CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding); if (eci != null) { appendECI(eci, headerAndDataBits); } } appendModeInfo(mode, headerAndDataBits); int numLetters = mode.equals(Mode.BYTE) ? dataBits.sizeInBytes() : content.length(); appendLengthInfo(numLetters, qrCode.getVersion(), mode, headerAndDataBits); headerAndDataBits.appendBitVector(dataBits); // Step 5: Terminate the bits properly. terminateBits(qrCode.getNumDataBytes(), headerAndDataBits); // Step 6: Interleave data bits with error correction code. BitVector finalBits = new BitVector(); interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(), qrCode.getNumRSBlocks(), finalBits); // Step 7: Choose the mask pattern and set to "qrCode". ByteMatrix matrix = new ByteMatrix(qrCode.getMatrixWidth(), qrCode.getMatrixWidth()); qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(), matrix)); // Step 8. Build the matrix and set it to "qrCode". MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(), qrCode.getMaskPattern(), matrix); qrCode.setMatrix(matrix); // Step 9. Make sure we have a valid QR Code. if (!qrCode.isValid()) { throw new WriterException("Invalid QR code: " + qrCode.toString()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode) throws WriterException { qrCode.setECLevel(ecLevel); qrCode.setMode(mode); // In the following comments, we use numbers of Version 7-H. for (int versionNum = 1; versionNum <= 40; versionNum++) { Version version = Version.getVersionForNumber(versionNum); // numBytes = 196 int numBytes = version.getTotalCodewords(); // getNumECBytes = 130 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); int numEcBytes = ecBlocks.getTotalECCodewords(); // getNumRSBlocks = 5 int numRSBlocks = ecBlocks.getNumBlocks(); // getNumDataBytes = 196 - 130 = 66 int numDataBytes = numBytes - numEcBytes; // We want to choose the smallest version which can contain data of "numInputBytes" + some // extra bits for the header (mode info and length info). The header can be three bytes // (precisely 4 + 16 bits) at most. Hence we do +3 here. if (numDataBytes >= numInputBytes + 3) { // Yay, we found the proper rs block info! qrCode.setVersion(versionNum); qrCode.setNumTotalBytes(numBytes); qrCode.setNumDataBytes(numDataBytes); qrCode.setNumRSBlocks(numRSBlocks); // getNumECBytes = 196 - 66 = 130 qrCode.setNumECBytes(numEcBytes); // matrix width = 21 + 6 * 4 = 45 qrCode.setMatrixWidth(version.getDimensionForVersion()); return; } } throw new WriterException("Cannot find proper rs block info (input data too big?)"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void terminateBits(int numDataBytes, BitVector bits) throws WriterException { int capacity = numDataBytes << 3; if (bits.size() > capacity) { throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity); } // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes // either way. for (int i = 0; i < 4 && bits.size() < capacity; ++i) { bits.appendBit(0); } int numBitsInLastByte = bits.size() % 8; // If the last byte isn't 8-bit aligned, we'll add padding bits. if (numBitsInLastByte > 0) { int numPaddingBits = 8 - numBitsInLastByte; for (int i = 0; i < numPaddingBits; ++i) { bits.appendBit(0); } } // Should be 8-bit aligned here. if (bits.size() % 8 != 0) { throw new WriterException("Number of bits is not a multiple of 8"); } // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). int numPaddingBytes = numDataBytes - bits.sizeInBytes(); for (int i = 0; i < numPaddingBytes; ++i) { if (i % 2 == 0) { bits.appendBits(0xec, 8); } else { bits.appendBits(0x11, 8); } } if (bits.size() != capacity) { throw new WriterException("Bits size does not equal capacity"); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock) throws WriterException { if (blockID >= numRSBlocks) { throw new WriterException("Block ID too large"); } // numRsBlocksInGroup2 = 196 % 5 = 1 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; // numRsBlocksInGroup1 = 5 - 1 = 4 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; // numTotalBytesInGroup1 = 196 / 5 = 39 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; // numTotalBytesInGroup2 = 39 + 1 = 40 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; // numDataBytesInGroup1 = 66 / 5 = 13 int numDataBytesInGroup1 = numDataBytes / numRSBlocks; // numDataBytesInGroup2 = 13 + 1 = 14 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; // numEcBytesInGroup1 = 39 - 13 = 26 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; // numEcBytesInGroup2 = 40 - 14 = 26 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; // Sanity checks. // 26 = 26 if (numEcBytesInGroup1 != numEcBytesInGroup2) { throw new WriterException("EC bytes mismatch"); } // 5 = 4 + 1. if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) { throw new WriterException("RS blocks mismatch"); } // 196 = (13 + 26) * 4 + (14 + 26) * 1 if (numTotalBytes != ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2)) { throw new WriterException("Total bytes mismatch"); } if (blockID < numRsBlocksInGroup1) { numDataBytesInBlock[0] = numDataBytesInGroup1; numECBytesInBlock[0] = numEcBytesInGroup1; } else { numDataBytesInBlock[0] = numDataBytesInGroup2; numECBytesInBlock[0] = numEcBytesInGroup2; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void interleaveWithECBytes(BitVector bits, int numTotalBytes, int numDataBytes, int numRSBlocks, BitVector result) throws WriterException { // "bits" must have "getNumDataBytes" bytes of data. if (bits.sizeInBytes() != numDataBytes) { throw new WriterException("Number of bits and data bytes does not match"); } // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll // store the divided data bytes blocks and error correction bytes blocks into "blocks". int dataBytesOffset = 0; int maxNumDataBytes = 0; int maxNumEcBytes = 0; // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. ArrayList<BlockPair> blocks = new ArrayList<BlockPair>(numRSBlocks); for (int i = 0; i < numRSBlocks; ++i) { int[] numDataBytesInBlock = new int[1]; int[] numEcBytesInBlock = new int[1]; getNumDataBytesAndNumECBytesForBlockID( numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock); ByteArray dataBytes = new ByteArray(); dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]); ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); blocks.add(new BlockPair(dataBytes, ecBytes)); maxNumDataBytes = Math.max(maxNumDataBytes, dataBytes.size()); maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.size()); dataBytesOffset += numDataBytesInBlock[0]; } if (numDataBytes != dataBytesOffset) { throw new WriterException("Data bytes does not match offset"); } // First, place data blocks. for (int i = 0; i < maxNumDataBytes; ++i) { for (int j = 0; j < blocks.size(); ++j) { ByteArray dataBytes = blocks.get(j).getDataBytes(); if (i < dataBytes.size()) { result.appendBits(dataBytes.at(i), 8); } } } // Then, place error correction blocks. for (int i = 0; i < maxNumEcBytes; ++i) { for (int j = 0; j < blocks.size(); ++j) { ByteArray ecBytes = blocks.get(j).getErrorCorrectionBytes(); if (i < ecBytes.size()) { result.appendBits(ecBytes.at(i), 8); } } } if (numTotalBytes != result.sizeInBytes()) { // Should be same. throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() + " differ."); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits) throws WriterException { int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version)); if (numLetters > ((1 << numBits) - 1)) { throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1)); } bits.appendBits(numLetters, numBits); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendBytes(String content, Mode mode, BitVector bits, String encoding) throws WriterException { if (mode.equals(Mode.NUMERIC)) { appendNumericBytes(content, bits); } else if (mode.equals(Mode.ALPHANUMERIC)) { appendAlphanumericBytes(content, bits); } else if (mode.equals(Mode.BYTE)) { append8BitBytes(content, bits, encoding); } else if (mode.equals(Mode.KANJI)) { appendKanjiBytes(content, bits); } else { throw new WriterException("Invalid mode: " + mode); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendAlphanumericBytes(String content, BitVector bits) throws WriterException { int length = content.length(); int i = 0; while (i < length) { int code1 = getAlphanumericCode(content.charAt(i)); if (code1 == -1) { throw new WriterException(); } if (i + 1 < length) { int code2 = getAlphanumericCode(content.charAt(i + 1)); if (code2 == -1) { throw new WriterException(); } // Encode two alphanumeric letters in 11 bits. bits.appendBits(code1 * 45 + code2, 11); i += 2; } else { // Encode one alphanumeric letter in six bits. bits.appendBits(code1, 6); i++; } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void append8BitBytes(String content, BitVector bits, String encoding) throws WriterException { byte[] bytes; try { bytes = content.getBytes(encoding); } catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); } for (int i = 0; i < bytes.length; ++i) { bits.appendBits(bytes[i], 8); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendKanjiBytes(String content, BitVector bits) throws WriterException { byte[] bytes; try { bytes = content.getBytes("Shift_JIS"); } catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); } int length = bytes.length; for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; int byte2 = bytes[i + 1] & 0xFF; int code = (byte1 << 8) | byte2; int subtracted = -1; if (code >= 0x8140 && code <= 0x9ffc) { subtracted = code - 0x8140; } else if (code >= 0xe040 && code <= 0xebbf) { subtracted = code - 0xc140; } if (subtracted == -1) { throw new WriterException("Invalid byte sequence"); } int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded, 13); } }
2
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); }
29
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void buildMatrix(BitVector dataBits, ErrorCorrectionLevel ecLevel, int version, int maskPattern, ByteMatrix matrix) throws WriterException { clearMatrix(matrix); embedBasicPatterns(version, matrix); // Type information appear with any version. embedTypeInfo(ecLevel, maskPattern, matrix); // Version info appear if version >= 7. maybeEmbedVersionInfo(version, matrix); // Data should be embedded at end. embedDataBits(dataBits, maskPattern, matrix); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void embedBasicPatterns(int version, ByteMatrix matrix) throws WriterException { // Let's get started with embedding big squares at corners. embedPositionDetectionPatternsAndSeparators(matrix); // Then, embed the dark dot at the left bottom corner. embedDarkDotAtLeftBottomCorner(matrix); // Position adjustment patterns appear if version >= 2. maybeEmbedPositionAdjustmentPatterns(version, matrix); // Timing patterns should be embedded after position adj. patterns. embedTimingPatterns(matrix); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void embedTypeInfo(ErrorCorrectionLevel ecLevel, int maskPattern, ByteMatrix matrix) throws WriterException { BitVector typeInfoBits = new BitVector(); makeTypeInfoBits(ecLevel, maskPattern, typeInfoBits); for (int i = 0; i < typeInfoBits.size(); ++i) { // Place bits in LSB to MSB order. LSB (least significant bit) is the last value in // "typeInfoBits". int bit = typeInfoBits.at(typeInfoBits.size() - 1 - i); // Type info bits at the left top corner. See 8.9 of JISX0510:2004 (p.46). int x1 = TYPE_INFO_COORDINATES[i][0]; int y1 = TYPE_INFO_COORDINATES[i][1]; matrix.set(x1, y1, bit); if (i < 8) { // Right top corner. int x2 = matrix.getWidth() - i - 1; int y2 = 8; matrix.set(x2, y2, bit); } else { // Left bottom corner. int x2 = 8; int y2 = matrix.getHeight() - 7 + (i - 8); matrix.set(x2, y2, bit); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void maybeEmbedVersionInfo(int version, ByteMatrix matrix) throws WriterException { if (version < 7) { // Version info is necessary if version >= 7. return; // Don't need version info. } BitVector versionInfoBits = new BitVector(); makeVersionInfoBits(version, versionInfoBits); int bitIndex = 6 * 3 - 1; // It will decrease from 17 to 0. for (int i = 0; i < 6; ++i) { for (int j = 0; j < 3; ++j) { // Place bits in LSB (least significant bit) to MSB order. int bit = versionInfoBits.at(bitIndex); bitIndex--; // Left bottom corner. matrix.set(i, matrix.getHeight() - 11 + j, bit); // Right bottom corner. matrix.set(matrix.getHeight() - 11 + j, i, bit); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void embedDataBits(BitVector dataBits, int maskPattern, ByteMatrix matrix) throws WriterException { int bitIndex = 0; int direction = -1; // Start from the right bottom cell. int x = matrix.getWidth() - 1; int y = matrix.getHeight() - 1; while (x > 0) { // Skip the vertical timing pattern. if (x == 6) { x -= 1; } while (y >= 0 && y < matrix.getHeight()) { for (int i = 0; i < 2; ++i) { int xx = x - i; // Skip the cell if it's not empty. if (!isEmpty(matrix.get(xx, y))) { continue; } int bit; if (bitIndex < dataBits.size()) { bit = dataBits.at(bitIndex); ++bitIndex; } else { // Padding bit. If there is no bit left, we'll fill the left cells with 0, as described // in 8.4.9 of JISX0510:2004 (p. 24). bit = 0; } // Skip masking if mask_pattern is -1. if (maskPattern != -1) { if (MaskUtil.getDataMaskBit(maskPattern, xx, y)) { bit ^= 0x1; } } matrix.set(xx, y, bit); } y += direction; } direction = -direction; // Reverse the direction. y += direction; x -= 2; // Move to the left. } // All bits should be consumed. if (bitIndex != dataBits.size()) { throw new WriterException("Not all bits consumed: " + bitIndex + '/' + dataBits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitVector bits) throws WriterException { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new WriterException("Invalid mask pattern"); } int typeInfo = (ecLevel.getBits() << 3) | maskPattern; bits.appendBits(typeInfo, 5); int bchCode = calculateBCHCode(typeInfo, TYPE_INFO_POLY); bits.appendBits(bchCode, 10); BitVector maskBits = new BitVector(); maskBits.appendBits(TYPE_INFO_MASK_PATTERN, 15); bits.xor(maskBits); if (bits.size() != 15) { // Just in case. throw new WriterException("should not happen but we got: " + bits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
public static void makeVersionInfoBits(int version, BitVector bits) throws WriterException { bits.appendBits(version, 6); int bchCode = calculateBCHCode(version, VERSION_INFO_POLY); bits.appendBits(bchCode, 12); if (bits.size() != 18) { // Just in case. throw new WriterException("should not happen but we got: " + bits.size()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedTimingPatterns(ByteMatrix matrix) throws WriterException { // -8 is for skipping position detection patterns (size 7), and two horizontal/vertical // separation patterns (size 1). Thus, 8 = 7 + 1. for (int i = 8; i < matrix.getWidth() - 8; ++i) { int bit = (i + 1) % 2; // Horizontal line. if (!isValidValue(matrix.get(i, 6))) { throw new WriterException(); } if (isEmpty(matrix.get(i, 6))) { matrix.set(i, 6, bit); } // Vertical line. if (!isValidValue(matrix.get(6, i))) { throw new WriterException(); } if (isEmpty(matrix.get(6, i))) { matrix.set(6, i, bit); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedDarkDotAtLeftBottomCorner(ByteMatrix matrix) throws WriterException { if (matrix.get(8, matrix.getHeight() - 8) == 0) { throw new WriterException(); } matrix.set(8, matrix.getHeight() - 8, 1); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedHorizontalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (HORIZONTAL_SEPARATION_PATTERN[0].length != 8 || HORIZONTAL_SEPARATION_PATTERN.length != 1) { throw new WriterException("Bad horizontal separation pattern"); } for (int x = 0; x < 8; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart))) { throw new WriterException(); } matrix.set(xStart + x, yStart, HORIZONTAL_SEPARATION_PATTERN[0][x]); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedVerticalSeparationPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (VERTICAL_SEPARATION_PATTERN[0].length != 1 || VERTICAL_SEPARATION_PATTERN.length != 7) { throw new WriterException("Bad vertical separation pattern"); } for (int y = 0; y < 7; ++y) { if (!isEmpty(matrix.get(xStart, yStart + y))) { throw new WriterException(); } matrix.set(xStart, yStart + y, VERTICAL_SEPARATION_PATTERN[y][0]); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedPositionAdjustmentPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (POSITION_ADJUSTMENT_PATTERN[0].length != 5 || POSITION_ADJUSTMENT_PATTERN.length != 5) { throw new WriterException("Bad position adjustment"); } for (int y = 0; y < 5; ++y) { for (int x = 0; x < 5; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart + y))) { throw new WriterException(); } matrix.set(xStart + x, yStart + y, POSITION_ADJUSTMENT_PATTERN[y][x]); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedPositionDetectionPattern(int xStart, int yStart, ByteMatrix matrix) throws WriterException { // We know the width and height. if (POSITION_DETECTION_PATTERN[0].length != 7 || POSITION_DETECTION_PATTERN.length != 7) { throw new WriterException("Bad position detection pattern"); } for (int y = 0; y < 7; ++y) { for (int x = 0; x < 7; ++x) { if (!isEmpty(matrix.get(xStart + x, yStart + y))) { throw new WriterException(); } matrix.set(xStart + x, yStart + y, POSITION_DETECTION_PATTERN[y][x]); } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void embedPositionDetectionPatternsAndSeparators(ByteMatrix matrix) throws WriterException { // Embed three big squares at corners. int pdpWidth = POSITION_DETECTION_PATTERN[0].length; // Left top corner. embedPositionDetectionPattern(0, 0, matrix); // Right top corner. embedPositionDetectionPattern(matrix.getWidth() - pdpWidth, 0, matrix); // Left bottom corner. embedPositionDetectionPattern(0, matrix.getWidth() - pdpWidth, matrix); // Embed horizontal separation patterns around the squares. int hspWidth = HORIZONTAL_SEPARATION_PATTERN[0].length; // Left top corner. embedHorizontalSeparationPattern(0, hspWidth - 1, matrix); // Right top corner. embedHorizontalSeparationPattern(matrix.getWidth() - hspWidth, hspWidth - 1, matrix); // Left bottom corner. embedHorizontalSeparationPattern(0, matrix.getWidth() - hspWidth, matrix); // Embed vertical separation patterns around the squares. int vspSize = VERTICAL_SEPARATION_PATTERN.length; // Left top corner. embedVerticalSeparationPattern(vspSize, 0, matrix); // Right top corner. embedVerticalSeparationPattern(matrix.getHeight() - vspSize - 1, 0, matrix); // Left bottom corner. embedVerticalSeparationPattern(vspSize, matrix.getHeight() - vspSize, matrix); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/MatrixUtil.java
private static void maybeEmbedPositionAdjustmentPatterns(int version, ByteMatrix matrix) throws WriterException { if (version < 2) { // The patterns appear if version >= 2 return; } int index = version - 1; int[] coordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index]; int numCoordinates = POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index].length; for (int i = 0; i < numCoordinates; ++i) { for (int j = 0; j < numCoordinates; ++j) { int y = coordinates[i]; int x = coordinates[j]; if (x == -1 || y == -1) { continue; } // If the cell is unset, we embed the position adjustment pattern here. if (isEmpty(matrix.get(x, y))) { // -2 is necessary since the x/y coordinates point to the center of the pattern, not the // left top corner. embedPositionAdjustmentPattern(x - 2, y - 2, matrix); } } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/QRCodeWriter.java
public ByteMatrix encode(String contents, int width, int height) throws WriterException { return encode(contents, width, height, null); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/QRCodeWriter.java
public ByteMatrix encode(String contents, int width, int height, Map<EncodeHintType,Object> hints) throws WriterException { if (contents == null || contents.length() == 0) { throw new IllegalArgumentException("Found empty contents"); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height); } ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; if (hints != null) { ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints.get(EncodeHintType.ERROR_CORRECTION); if (requestedECLevel != null) { errorCorrectionLevel = requestedECLevel; } } QRCode code = new QRCode(); Encoder.encode(contents, errorCorrectionLevel, hints, code); return renderResult(code, width, height); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
public static void encode(String content, ErrorCorrectionLevel ecLevel, QRCode qrCode) throws WriterException { encode(content, ecLevel, null, qrCode); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
public static void encode(String content, ErrorCorrectionLevel ecLevel, Map<EncodeHintType,Object> hints, QRCode qrCode) throws WriterException { String encoding = hints == null ? null : (String) hints.get(EncodeHintType.CHARACTER_SET); if (encoding == null) { encoding = DEFAULT_BYTE_MODE_ENCODING; } // Step 1: Choose the mode (encoding). Mode mode = chooseMode(content, encoding); // Step 2: Append "bytes" into "dataBits" in appropriate encoding. BitVector dataBits = new BitVector(); appendBytes(content, mode, dataBits, encoding); // Step 3: Initialize QR code that can contain "dataBits". int numInputBytes = dataBits.sizeInBytes(); initQRCode(numInputBytes, ecLevel, mode, qrCode); // Step 4: Build another bit vector that contains header and data. BitVector headerAndDataBits = new BitVector(); // Step 4.5: Append ECI message if applicable if (mode == Mode.BYTE && !DEFAULT_BYTE_MODE_ENCODING.equals(encoding)) { CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding); if (eci != null) { appendECI(eci, headerAndDataBits); } } appendModeInfo(mode, headerAndDataBits); int numLetters = mode.equals(Mode.BYTE) ? dataBits.sizeInBytes() : content.length(); appendLengthInfo(numLetters, qrCode.getVersion(), mode, headerAndDataBits); headerAndDataBits.appendBitVector(dataBits); // Step 5: Terminate the bits properly. terminateBits(qrCode.getNumDataBytes(), headerAndDataBits); // Step 6: Interleave data bits with error correction code. BitVector finalBits = new BitVector(); interleaveWithECBytes(headerAndDataBits, qrCode.getNumTotalBytes(), qrCode.getNumDataBytes(), qrCode.getNumRSBlocks(), finalBits); // Step 7: Choose the mask pattern and set to "qrCode". ByteMatrix matrix = new ByteMatrix(qrCode.getMatrixWidth(), qrCode.getMatrixWidth()); qrCode.setMaskPattern(chooseMaskPattern(finalBits, qrCode.getECLevel(), qrCode.getVersion(), matrix)); // Step 8. Build the matrix and set it to "qrCode". MatrixUtil.buildMatrix(finalBits, qrCode.getECLevel(), qrCode.getVersion(), qrCode.getMaskPattern(), matrix); qrCode.setMatrix(matrix); // Step 9. Make sure we have a valid QR Code. if (!qrCode.isValid()) { throw new WriterException("Invalid QR code: " + qrCode.toString()); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
private static int chooseMaskPattern(BitVector bits, ErrorCorrectionLevel ecLevel, int version, ByteMatrix matrix) throws WriterException { int minPenalty = Integer.MAX_VALUE; // Lower penalty is better. int bestMaskPattern = -1; // We try all mask patterns to choose the best one. for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) { MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); int penalty = calculateMaskPenalty(matrix); if (penalty < minPenalty) { minPenalty = penalty; bestMaskPattern = maskPattern; } } return bestMaskPattern; }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
private static void initQRCode(int numInputBytes, ErrorCorrectionLevel ecLevel, Mode mode, QRCode qrCode) throws WriterException { qrCode.setECLevel(ecLevel); qrCode.setMode(mode); // In the following comments, we use numbers of Version 7-H. for (int versionNum = 1; versionNum <= 40; versionNum++) { Version version = Version.getVersionForNumber(versionNum); // numBytes = 196 int numBytes = version.getTotalCodewords(); // getNumECBytes = 130 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); int numEcBytes = ecBlocks.getTotalECCodewords(); // getNumRSBlocks = 5 int numRSBlocks = ecBlocks.getNumBlocks(); // getNumDataBytes = 196 - 130 = 66 int numDataBytes = numBytes - numEcBytes; // We want to choose the smallest version which can contain data of "numInputBytes" + some // extra bits for the header (mode info and length info). The header can be three bytes // (precisely 4 + 16 bits) at most. Hence we do +3 here. if (numDataBytes >= numInputBytes + 3) { // Yay, we found the proper rs block info! qrCode.setVersion(versionNum); qrCode.setNumTotalBytes(numBytes); qrCode.setNumDataBytes(numDataBytes); qrCode.setNumRSBlocks(numRSBlocks); // getNumECBytes = 196 - 66 = 130 qrCode.setNumECBytes(numEcBytes); // matrix width = 21 + 6 * 4 = 45 qrCode.setMatrixWidth(version.getDimensionForVersion()); return; } } throw new WriterException("Cannot find proper rs block info (input data too big?)"); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void terminateBits(int numDataBytes, BitVector bits) throws WriterException { int capacity = numDataBytes << 3; if (bits.size() > capacity) { throw new WriterException("data bits cannot fit in the QR Code" + bits.size() + " > " + capacity); } // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. // TODO: srowen says we can remove this for loop, since the 4 terminator bits are optional if // the last byte has less than 4 bits left. So it amounts to padding the last byte with zeroes // either way. for (int i = 0; i < 4 && bits.size() < capacity; ++i) { bits.appendBit(0); } int numBitsInLastByte = bits.size() % 8; // If the last byte isn't 8-bit aligned, we'll add padding bits. if (numBitsInLastByte > 0) { int numPaddingBits = 8 - numBitsInLastByte; for (int i = 0; i < numPaddingBits; ++i) { bits.appendBit(0); } } // Should be 8-bit aligned here. if (bits.size() % 8 != 0) { throw new WriterException("Number of bits is not a multiple of 8"); } // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). int numPaddingBytes = numDataBytes - bits.sizeInBytes(); for (int i = 0; i < numPaddingBytes; ++i) { if (i % 2 == 0) { bits.appendBits(0xec, 8); } else { bits.appendBits(0x11, 8); } } if (bits.size() != capacity) { throw new WriterException("Bits size does not equal capacity"); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock) throws WriterException { if (blockID >= numRSBlocks) { throw new WriterException("Block ID too large"); } // numRsBlocksInGroup2 = 196 % 5 = 1 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; // numRsBlocksInGroup1 = 5 - 1 = 4 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; // numTotalBytesInGroup1 = 196 / 5 = 39 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; // numTotalBytesInGroup2 = 39 + 1 = 40 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; // numDataBytesInGroup1 = 66 / 5 = 13 int numDataBytesInGroup1 = numDataBytes / numRSBlocks; // numDataBytesInGroup2 = 13 + 1 = 14 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; // numEcBytesInGroup1 = 39 - 13 = 26 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; // numEcBytesInGroup2 = 40 - 14 = 26 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; // Sanity checks. // 26 = 26 if (numEcBytesInGroup1 != numEcBytesInGroup2) { throw new WriterException("EC bytes mismatch"); } // 5 = 4 + 1. if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) { throw new WriterException("RS blocks mismatch"); } // 196 = (13 + 26) * 4 + (14 + 26) * 1 if (numTotalBytes != ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2)) { throw new WriterException("Total bytes mismatch"); } if (blockID < numRsBlocksInGroup1) { numDataBytesInBlock[0] = numDataBytesInGroup1; numECBytesInBlock[0] = numEcBytesInGroup1; } else { numDataBytesInBlock[0] = numDataBytesInGroup2; numECBytesInBlock[0] = numEcBytesInGroup2; } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void interleaveWithECBytes(BitVector bits, int numTotalBytes, int numDataBytes, int numRSBlocks, BitVector result) throws WriterException { // "bits" must have "getNumDataBytes" bytes of data. if (bits.sizeInBytes() != numDataBytes) { throw new WriterException("Number of bits and data bytes does not match"); } // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll // store the divided data bytes blocks and error correction bytes blocks into "blocks". int dataBytesOffset = 0; int maxNumDataBytes = 0; int maxNumEcBytes = 0; // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. ArrayList<BlockPair> blocks = new ArrayList<BlockPair>(numRSBlocks); for (int i = 0; i < numRSBlocks; ++i) { int[] numDataBytesInBlock = new int[1]; int[] numEcBytesInBlock = new int[1]; getNumDataBytesAndNumECBytesForBlockID( numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock); ByteArray dataBytes = new ByteArray(); dataBytes.set(bits.getArray(), dataBytesOffset, numDataBytesInBlock[0]); ByteArray ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); blocks.add(new BlockPair(dataBytes, ecBytes)); maxNumDataBytes = Math.max(maxNumDataBytes, dataBytes.size()); maxNumEcBytes = Math.max(maxNumEcBytes, ecBytes.size()); dataBytesOffset += numDataBytesInBlock[0]; } if (numDataBytes != dataBytesOffset) { throw new WriterException("Data bytes does not match offset"); } // First, place data blocks. for (int i = 0; i < maxNumDataBytes; ++i) { for (int j = 0; j < blocks.size(); ++j) { ByteArray dataBytes = blocks.get(j).getDataBytes(); if (i < dataBytes.size()) { result.appendBits(dataBytes.at(i), 8); } } } // Then, place error correction blocks. for (int i = 0; i < maxNumEcBytes; ++i) { for (int j = 0; j < blocks.size(); ++j) { ByteArray ecBytes = blocks.get(j).getErrorCorrectionBytes(); if (i < ecBytes.size()) { result.appendBits(ecBytes.at(i), 8); } } } if (numTotalBytes != result.sizeInBytes()) { // Should be same. throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.sizeInBytes() + " differ."); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendLengthInfo(int numLetters, int version, Mode mode, BitVector bits) throws WriterException { int numBits = mode.getCharacterCountBits(Version.getVersionForNumber(version)); if (numLetters > ((1 << numBits) - 1)) { throw new WriterException(numLetters + "is bigger than" + ((1 << numBits) - 1)); } bits.appendBits(numLetters, numBits); }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendBytes(String content, Mode mode, BitVector bits, String encoding) throws WriterException { if (mode.equals(Mode.NUMERIC)) { appendNumericBytes(content, bits); } else if (mode.equals(Mode.ALPHANUMERIC)) { appendAlphanumericBytes(content, bits); } else if (mode.equals(Mode.BYTE)) { append8BitBytes(content, bits, encoding); } else if (mode.equals(Mode.KANJI)) { appendKanjiBytes(content, bits); } else { throw new WriterException("Invalid mode: " + mode); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendAlphanumericBytes(String content, BitVector bits) throws WriterException { int length = content.length(); int i = 0; while (i < length) { int code1 = getAlphanumericCode(content.charAt(i)); if (code1 == -1) { throw new WriterException(); } if (i + 1 < length) { int code2 = getAlphanumericCode(content.charAt(i + 1)); if (code2 == -1) { throw new WriterException(); } // Encode two alphanumeric letters in 11 bits. bits.appendBits(code1 * 45 + code2, 11); i += 2; } else { // Encode one alphanumeric letter in six bits. bits.appendBits(code1, 6); i++; } } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void append8BitBytes(String content, BitVector bits, String encoding) throws WriterException { byte[] bytes; try { bytes = content.getBytes(encoding); } catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); } for (int i = 0; i < bytes.length; ++i) { bits.appendBits(bytes[i], 8); } }
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/qrcode/Encoder.java
static void appendKanjiBytes(String content, BitVector bits) throws WriterException { byte[] bytes; try { bytes = content.getBytes("Shift_JIS"); } catch (UnsupportedEncodingException uee) { throw new WriterException(uee.toString()); } int length = bytes.length; for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; int byte2 = bytes[i + 1] & 0xFF; int code = (byte1 << 8) | byte2; int subtracted = -1; if (code >= 0x8140 && code <= 0x9ffc) { subtracted = code - 0x8140; } else if (code >= 0xe040 && code <= 0xebbf) { subtracted = code - 0xc140; } if (subtracted == -1) { throw new WriterException("Invalid byte sequence"); } int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded, 13); } }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeQRCode.java
catch (WriterException ex) { throw new ExceptionConverter(ex); }
1
            
// in /home/martin-no-backup/testoss/itext/src/com/itextpdf/text/pdf/BarcodeQRCode.java
catch (WriterException ex) { throw new ExceptionConverter(ex); }
1

Miscellanous Metrics

nF = Number of Finally 63
nF = Number of Try-Finally (without catch) 43
Number of Methods with Finally (nMF) 54 / 6964 (0.8%)
Number of Finally with a Continue 0
Number of Finally with a Return 0
Number of Finally with a Throw 1
Number of Finally with a Break 0
Number of different exception types thrown 36
Number of Domain exception types thrown 16
Number of different exception types caught 33
Number of Domain exception types caught 5
Number of exception declarations in signatures 1171
Number of different exceptions types declared in method signatures 32
Number of library exceptions types declared in method signatures 24
Number of Domain exceptions types declared in method signatures 8
Number of Catch with a continue 7
Number of Catch with a return 59
Number of Catch with a Break 4
nbIf = Number of If 7990
nbFor = Number of For 1482
Number of Method with an if 2261 / 6964
Number of Methods with a for 910 / 6964
Number of Method starting with a try 116 / 6964 (1.7%)
Number of Expressions 120379
Number of Expressions in try 9198 (7.6%)