Example usage for org.apache.pdfbox.cos COSDictionary getItem

List of usage examples for org.apache.pdfbox.cos COSDictionary getItem

Introduction

In this page you can find the example usage for org.apache.pdfbox.cos COSDictionary getItem.

Prototype

public COSBase getItem(String key) 

Source Link

Document

This will do a lookup into the dictionary.

Usage

From source file:net.padaf.preflight.font.Type3FontValidator.java

License:Apache License

/**
 * For a Type3 font, the mapping between the Character Code and the Character
 * name is entirely defined in the Encoding Entry. The Encoding Entry can be a
 * Name (For the 5 predefined Encoding) or a Dictionary. If it is a
 * dictionary, the "Differences" array contains the correspondence between a
 * character code and a set of character name which are different from the
 * encoding entry of the dictionary.//  w  w  w.  j  a  v a 2 s  .com
 * 
 * This method checks that the encoding is :
 * <UL>
 * <li>An existing encoding name.
 * <li>A dictionary with an existing encoding name (the name is optional) and
 * a well formed "Differences" array (the array is optional)
 * </UL>
 * 
 * @return
 */
private boolean checkEncoding() {
    COSDocument cDoc = this.handler.getDocument().getDocument();

    EncodingManager emng = new EncodingManager();
    if (COSUtils.isString(this.fontEncoding, cDoc)) {
        // ---- Encoding is a Name, check if it is an Existing Encoding
        String enc = COSUtils.getAsString(this.fontEncoding, cDoc);
        try {
            type3Encoding = emng.getEncoding(COSName.getPDFName(enc));
        } catch (IOException e) {
            // ---- the encoding doesn't exist
            this.fontContainer.addError(new ValidationError(ERROR_FONTS_ENCODING));
            return false;
        }
    } else if (COSUtils.isDictionary(this.fontEncoding, cDoc)) {
        COSDictionary encodingDictionary = COSUtils.getAsDictionary(this.fontEncoding, cDoc);
        try {
            type3Encoding = new DictionaryEncoding(encodingDictionary);
        } catch (IOException e) {
            // ---- the encoding doesn't exist
            this.fontContainer.addError(new ValidationError(ERROR_FONTS_ENCODING));
            return false;
        }

        COSBase diff = encodingDictionary.getItem(COSName.getPDFName(FONT_DICTIONARY_KEY_DIFFERENCES));
        if (diff != null) {
            if (!COSUtils.isArray(diff, cDoc)) {
                this.fontContainer.addError(new ValidationError(ERROR_FONTS_TYPE3_DAMAGED,
                        "The differences element of the encoding dictionary isn't an array"));
                return false;
            }

            // ---- The DictionaryEncoding object doesn't throw exception if the
            // Differences isn't well formed.
            // So check if the array has the right format.
            COSArray differences = COSUtils.getAsArray(diff, cDoc);
            for (int i = 0; i < differences.size(); ++i) {
                COSBase item = differences.get(i);
                if (!(item instanceof COSInteger || item instanceof COSName)) {
                    // ---- Error, the Differences array is invalid
                    this.fontContainer.addError(new ValidationError(ERROR_FONTS_TYPE3_DAMAGED,
                            "Differences Array should contain COSInt or COSName, no other type"));
                    return false;
                }
            }
        }
    } else {
        // ---- the encoding entry is invalid
        this.fontContainer.addError(new ValidationError(ERROR_FONTS_TYPE3_DAMAGED,
                "The Encoding entry doesn't have the right type"));
        return false;
    }

    return true;
}

From source file:net.padaf.preflight.font.Type3FontValidator.java

License:Apache License

/**
 * CharProcs is a dictionary where the key is a character name and the value
 * is a Stream which contains the glyph representation of the key.
 * //from  w  w w . ja va  2 s.  co  m
 * This method checks that all character code defined in the Widths Array
 * exist in the CharProcs dictionary. If the CharProcs doesn't know the
 * Character, it is mapped with the .notdef one.
 * 
 * For each character, the Glyph width must be the same as the Width value
 * declared in the Widths array.
 * 
 * @param errors
 * @return
 */
private boolean checkCharProcsAndMetrics() throws ValidationException {
    COSDocument cDoc = this.handler.getDocument().getDocument();

    // ---- the Widths value can be a reference to an object
    // ---- Access the object using the COSkey
    COSArray wArr = COSUtils.getAsArray(this.widths, cDoc);
    if (wArr == null) {
        this.fontContainer.addError(
                new ValidationError(ERROR_FONTS_DICTIONARY_INVALID, "The Witdhs array is unreachable"));
        return false;
    }

    COSDictionary charProcsDictionary = COSUtils.getAsDictionary(this.charProcs, cDoc);
    if (charProcsDictionary == null) {
        this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID,
                "The CharProcs element isn't a dictionary"));
        return false;
    }

    // ---- firstChar and lastChar must be integer.
    int fc = ((COSInteger) this.firstChar).intValue();
    int lc = ((COSInteger) this.lastChar).intValue();

    // ---- wArr length = (lc - fc) +1 and it is an array of int.
    // ---- If FirstChar is greater than LastChar, the validation will fail
    // because of
    // ---- the array will have an expected size <= 0.
    int expectedLength = (lc - fc) + 1;
    if (wArr.size() != expectedLength) {
        this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID,
                "The length of Witdhs array is invalid. Expected : \"" + expectedLength + "\" Current : \""
                        + wArr.size() + "\""));
        return false;
    }

    // ---- Check width consistency
    for (int i = 0; i < expectedLength; i++) {
        int cid = fc + i;
        COSBase arrContent = wArr.get(i);
        if (COSUtils.isNumeric(arrContent, cDoc)) {
            float width = COSUtils.getAsFloat(arrContent, cDoc);

            String charName = null;
            try {
                charName = this.type3Encoding.getName(cid);
            } catch (IOException e) {
                // shouldn't occur
                throw new ValidationException("Unable to check Widths consistency", e);
            }

            COSBase item = charProcsDictionary.getItem(COSName.getPDFName(charName));
            COSStream charStream = COSUtils.getAsStream(item, cDoc);
            if (charStream == null && width != 0) {
                GlyphException glyphEx = new GlyphException(ERROR_FONTS_METRICS, cid,
                        "The CharProcs \"" + charName + "\" doesn't exist but the width is " + width);
                GlyphDetail glyphDetail = new GlyphDetail(cid, glyphEx);
                this.fontContainer.addKnownCidElement(glyphDetail);
            } else {
                try {
                    // --- Parse the Glyph description to obtain the Width
                    PDFAType3StreamParser parser = new PDFAType3StreamParser(this.handler);
                    PDResources pRes = null;
                    if (this.resources != null) {
                        COSDictionary resAsDict = COSUtils.getAsDictionary(this.resources, cDoc);
                        if (resAsDict != null) {
                            pRes = new PDResources(resAsDict);
                        }
                    }
                    parser.resetEngine();
                    parser.processSubStream(null, pRes, charStream);

                    if (width != parser.getWidth()) {
                        GlyphException glyphEx = new GlyphException(ERROR_FONTS_METRICS, cid,
                                "The CharProcs \"" + charName + "\" should have a width equals to " + width);
                        GlyphDetail glyphDetail = new GlyphDetail(cid, glyphEx);
                        this.fontContainer.addKnownCidElement(glyphDetail);
                    } else {
                        // Glyph is OK, we keep the CID.
                        GlyphDetail glyphDetail = new GlyphDetail(cid);
                        this.fontContainer.addKnownCidElement(glyphDetail);
                    }
                } catch (ContentStreamException e) {
                    this.fontContainer.addError(new ValidationError(e.getValidationError()));
                    return false;
                } catch (IOException e) {
                    this.fontContainer.addError(new ValidationError(ERROR_FONTS_TYPE3_DAMAGED,
                            "The CharProcs references an element which can't be read"));
                    return false;
                }
            }

        } else {
            this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID,
                    "The Witdhs array is invalid. (some element aren't integer)"));
            return false;
        }
    }
    return true;
}

From source file:net.padaf.preflight.font.Type3FontValidator.java

License:Apache License

/**
 * If the Resources entry is present, this method check its content. Only
 * fonts and Images are checked because this resource describes glyphs. REMARK
 * : The font and the image aren't validated because they will be validated by
 * an other ValidationHelper./*from  w ww  . j  a  v a 2s  . com*/
 * 
 * @return
 */
private boolean checkResources() throws ValidationException {
    if (this.resources == null) {
        // ---- No resources dictionary.
        return true;
    }

    COSDocument cDoc = this.handler.getDocument().getDocument();
    COSDictionary dictionary = COSUtils.getAsDictionary(this.resources, cDoc);
    if (dictionary == null) {
        this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID,
                "The Resources element isn't a dictionary"));
        return false;
    }

    COSBase cbImg = dictionary.getItem(COSName.getPDFName(DICTIONARY_KEY_XOBJECT));
    COSBase cbFont = dictionary.getItem(COSName.getPDFName(DICTIONARY_KEY_FONT));

    if (cbImg == null && cbFont == null) {
        this.fontContainer.addError(new ValidationError(ERROR_FONTS_TYPE3_DAMAGED,
                "The Resources element doesn't have Glyph information"));
        return false;
    }

    if (cbImg != null) {
        // ---- the referenced objects must be present in the PDF file
        COSDictionary dicImgs = COSUtils.getAsDictionary(cbImg, cDoc);
        Set<COSName> keyList = dicImgs.keySet();
        for (Object key : keyList) {

            COSBase item = dictionary.getItem((COSName) key);
            COSDictionary xObjImg = COSUtils.getAsDictionary(item, cDoc);
            if (xObjImg == null) {
                this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID,
                        "The Resources dictionary of type 3 font is invalid"));
                return false;
            }

            if (!XOBJECT_DICTIONARY_VALUE_SUBTYPE_IMG
                    .equals(xObjImg.getString(COSName.getPDFName(DICTIONARY_KEY_SUBTYPE)))) {
                this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID,
                        "The Resources dictionary of type 3 font is invalid"));
                return false;
            }
        }
    }

    if (cbFont != null) {
        // ---- the referenced object must be present in the PDF file
        COSDictionary dicFonts = COSUtils.getAsDictionary(cbFont, cDoc);
        Set<COSName> keyList = dicFonts.keySet();
        for (Object key : keyList) {

            COSBase item = dictionary.getItem((COSName) key);
            COSDictionary xObjFont = COSUtils.getAsDictionary(item, cDoc);
            if (xObjFont == null) {
                this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID,
                        "The Resources dictionary of type 3 font is invalid"));
                return false;
            }

            if (!FONT_DICTIONARY_VALUE_FONT
                    .equals(xObjFont.getString(COSName.getPDFName(DICTIONARY_KEY_TYPE)))) {
                this.fontContainer.addError(new ValidationError(ERROR_FONTS_DICTIONARY_INVALID,
                        "The Resources dictionary of type 3 font is invalid"));
                return false;
            }

            try {
                PDFont aFont = PDFontFactory.createFont(xObjFont);
                // FontContainer aContainer = this.handler.retrieveFontContainer(aFont);
                AbstractFontContainer aContainer = this.handler.getFont(aFont.getCOSObject());
                // ---- another font is used in the Type3, check if the font is valid.
                if (aContainer.isValid() != State.VALID) {
                    this.fontContainer.addError(new ValidationError(ERROR_FONTS_TYPE3_DAMAGED,
                            "The Resources dictionary of type 3 font contains invalid font"));
                    return false;
                }
            } catch (IOException e) {
                throw new ValidationException("Unable to valid the Type3 : " + e.getMessage());
            }
        }
    }

    List<ValidationError> errors = new ArrayList<ValidationError>();
    ExtGStateContainer extGStates = new ExtGStateContainer(dictionary, cDoc);
    boolean res = extGStates.validateTransparencyRules(errors);
    for (ValidationError err : errors) {
        this.fontContainer.addError(err);
    }

    return res && validateShadingPattern(dictionary, errors);
}

From source file:net.padaf.preflight.graphics.ExtGStateContainer.java

License:Apache License

/**
 * Create an instance of ExtGStateContainer using a Resource dictionary and a
 * COSDocument. This constructor initializes the listOfExtGState attribute
 * using the given Resource dictionary and the COSDocument.
 * /*from w w w  . ja  v a2 s . co  m*/
 * @param resources
 *          a resource COSDictionary
 * @param cDoc
 *          the COSDocument which contains the Resource dictionary
 * @throws ValidationException
 *           thrown if a the Extended Graphic State isn't valid
 */
public ExtGStateContainer(COSDictionary resources, COSDocument cDoc) throws ValidationException {
    this.cDoc = cDoc;
    COSBase egsEntry = resources.getItem(COSName.getPDFName(TRANPARENCY_DICTIONARY_KEY_EXTGSTATE));
    COSDictionary extGStates = COSUtils.getAsDictionary(egsEntry, cDoc);

    if (extGStates != null) {
        for (Object object : extGStates.keySet()) {
            COSName key = (COSName) object;
            if (key.getName().matches(TRANPARENCY_DICTIONARY_KEY_EXTGSTATE_ENTRY_REGEX)) {
                COSBase gsBase = extGStates.getItem(key);
                COSDictionary gsDict = COSUtils.getAsDictionary(gsBase, cDoc);
                if (gsDict == null) {
                    throw new ValidationException("The Extended Graphics State dictionary is invalid");
                }
                this.listOfExtGState.add(gsDict);
            }
        }
    }
    //else  if there are no ExtGState, the list will be empty.

}

From source file:net.padaf.preflight.graphics.ExtGStateContainer.java

License:Apache License

/**
 * This method checks the SMask value of the ExtGState dictionary. The Soft
 * Mask is optional but must be "None" if it is present.
 * /*from  w w w  .  ja  v  a 2  s  .c o m*/
 * @param egs
 *          the Graphic state to check
 * @param error
 *          the list of error to update if the validation fails.
 * @return true if SMask is missing or equals to None
 */
private boolean checkSoftMask(COSDictionary egs, List<ValidationError> error) {
    COSBase smVal = egs.getItem(COSName.getPDFName(TRANSPARENCY_DICTIONARY_KEY_SOFT_MASK));
    if (smVal != null) {
        // ---- Soft Mask is valid only if it is a COSName equals to None
        if (!(smVal instanceof COSName
                && TRANSPARENCY_DICTIONARY_VALUE_SOFT_MASK_NONE.equals(((COSName) smVal).getName()))) {
            error.add(
                    new ValidationError(ERROR_TRANSPARENCY_EXT_GS_SOFT_MASK, "SoftMask must be null or None"));
            return false;
        }
    }
    return true;
}

From source file:net.padaf.preflight.graphics.ExtGStateContainer.java

License:Apache License

/**
 * This method checks the BM value of the ExtGState dictionary. The Blend Mode
 * is optional but must be "Normal" or "Compatible" if it is present.
 * //w w  w.j  a v a 2  s .  c  o  m
 * @param egs
 *          the graphic state to check
 * @param error
 *          the list of error to update if the validation fails.
 * @return true if BM is missing or equals to "Normal" or "Compatible"
 */
private boolean checkBlendMode(COSDictionary egs, List<ValidationError> error) {
    COSBase bmVal = egs.getItem(COSName.getPDFName(TRANSPARENCY_DICTIONARY_KEY_BLEND_MODE));
    if (bmVal != null) {
        // ---- Blend Mode is valid only if it is equals to Normal or Compatible
        if (!(bmVal instanceof COSName
                && (TRANSPARENCY_DICTIONARY_VALUE_BM_NORMAL.equals(((COSName) bmVal).getName())
                        || TRANSPARENCY_DICTIONARY_VALUE_BM_COMPATIBLE.equals(((COSName) bmVal).getName())))) {
            error.add(new ValidationError(ERROR_TRANSPARENCY_EXT_GS_BLEND_MODE,
                    "BlendMode value isn't valid (only Normal and Compatible are authorized)"));
            return false;
        }
    }
    return true;
}

From source file:net.padaf.preflight.graphics.ExtGStateContainer.java

License:Apache License

/**
 * This method checks the "CA" and "ca" values of the ExtGState dictionary.
 * They are optional but must be 1.0 if they are present.
 * /*  www  .ja  v a  2  s  .  c  o  m*/
 * @param egs
 *          the graphic state to check
 * @param error
 *          the list of error to update if the validation fails.
 * @return true if CA/ca is missing or equals to 1.0
 */
private boolean checkCA(COSDictionary egs, List<ValidationError> error) {
    COSBase uCA = egs.getItem(COSName.getPDFName(TRANSPARENCY_DICTIONARY_KEY_UPPER_CA));
    COSBase lCA = egs.getItem(COSName.getPDFName(TRANSPARENCY_DICTIONARY_KEY_LOWER_CA));
    if (uCA != null) {
        // ---- If CA is present only the value 1.0 is authorized
        Float fca = COSUtils.getAsFloat(uCA, cDoc);
        Integer ica = COSUtils.getAsInteger(uCA, cDoc);
        if (!(fca != null && fca == 1.0f) && !(ica != null && ica == 1)) {
            error.add(new ValidationError(ERROR_TRANSPARENCY_EXT_GS_CA, "CA entry in a ExtGState is invalid"));
            return false;
        }
    }

    if (lCA != null) {
        // ---- If ca is present only the value 1.0 is authorized
        Float fca = COSUtils.getAsFloat(lCA, cDoc);
        Integer ica = COSUtils.getAsInteger(lCA, cDoc);
        if (!(fca != null && fca == 1.0f) && !(ica != null && ica == 1)) {
            error.add(
                    new ValidationError(ERROR_TRANSPARENCY_EXT_GS_CA, "ca entry in a ExtGState  is invalid."));
            return false;
        }
    }
    return true;
}

From source file:net.padaf.preflight.graphics.ExtGStateContainer.java

License:Apache License

/**
 * Check the TR entry. A valid ExtGState hasn't TR entry.
 * //from w ww .jav a 2 s .c om
 * @param egs
 *          the graphic state to check
 * @param error
 *          the list of error to update if the validation fails.
 * @return true if TR entry is missing, false otherwise.
 */
protected boolean checkTRKey(COSDictionary egs, List<ValidationError> error) {
    if (egs.getItem(COSName.getPDFName("TR")) != null) {
        error.add(new ValidationError(ValidationConstants.ERROR_GRAPHIC_UNEXPECTED_KEY,
                "No TR key expected in Extended graphics state"));
        return false;
    }
    return true;
}

From source file:net.padaf.preflight.graphics.ExtGStateContainer.java

License:Apache License

/**
 * Check the TR2 entry. A valid ExtGState hasn't TR2 entry or a TR2 entry
 * equals to "default".//from  w ww.  j ava2  s.co  m
 * 
 * @param egs
 *          the graphic state to check
 * @param error
 *          the list of error to update if the validation fails.
 * @return true if TR2 entry is missing or equals to "default", false
 *         otherwise.
 */
protected boolean checkTR2Key(COSDictionary egs, List<ValidationError> error) {
    if (egs.getItem(COSName.getPDFName("TR2")) != null) {
        String s = egs.getNameAsString(COSName.getPDFName("TR2"));
        if (!"default".equals(s)) {
            error.add(new ValidationError(ValidationConstants.ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY,
                    "TR2 key only expect 'default' value, not '" + s + "'"));
            return false;
        }
    }
    return true;
}

From source file:net.padaf.preflight.graphics.ShadingPattern.java

License:Apache License

/**
 * Checks if the given shading pattern contains the ShadingType entry and if
 * the ColorSapce entry is consistent which rules of the PDF Reference and the
 * ISO 190005-1:2005 Specification.//from w  ww  . j  a va 2  s  .  co m
 * 
 * This method is called by the validate method.
 * 
 * @param shadingDict
 *          the Shading pattern dictionary to check
 * @param errors
 *          the list of error to update if the validation fails
 * @return true if the Shading pattern is valid, false otherwise.
 * @throws ValidationException
 */
protected boolean checkShadingDictionary(COSDictionary shadingDict, List<ValidationError> errors)
        throws ValidationException {
    if (shadingDict.getItem(COSName.getPDFName(PATTERN_KEY_SHADING_TYPE)) == null) {
        errors.add(new ValidationError(ERROR_GRAPHIC_INVALID_PATTERN_DEFINITION));
        return false;
    }

    COSBase csImg = shadingDict.getItem(COSName.getPDFName(XOBJECT_DICTIONARY_KEY_COLOR_SPACE));
    ColorSpaceHelper csh = ColorSpaceHelperFactory.getColorSpaceHelper(csImg, documentHandler,
            ColorSpaceRestriction.NO_PATTERN);
    return csh.validate(errors);
}