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.helpers.BookmarkValidationHelper.java

License:Apache License

/**
 * Return true if the Count entry is present in the given dictionary.
 * /*  w  ww .  j ava 2s.c om*/
 * @param outline
 * @return
 */
private boolean isCountEntryPresent(COSDictionary outline) {
    return outline.getItem(COSName.getPDFName("Count")) != null;
}

From source file:net.padaf.preflight.helpers.BookmarkValidationHelper.java

License:Apache License

/**
 * This method checks the inputItem dictionary and call the
 * exploreOutlineLevel method on the first child if it is not null.
 * /*from   w w  w .  ja  va 2 s .  co  m*/
 * @param inputItem
 *          outline item to validate
 * @param handler
 *          The document handler which provides useful data for the level
 *          exploration (ex : access to the PDDocument)
 * @param result
 * @return
 * @throws ValidationException
 */
protected boolean validateItem(PDOutlineItem inputItem, DocumentHandler handler, List<ValidationError> result)
        throws ValidationException {
    boolean isValid = true;
    // ---- Dest entry isn't permitted if the A entry is present
    // A entry isn't permitted if the Dest entry is present
    // If the A enntry is present, the referenced actions is validated
    COSDictionary dictionary = inputItem.getCOSDictionary();
    COSBase dest = dictionary.getItem(COSName.getPDFName(DICTIONARY_KEY_DESTINATION));
    COSBase action = dictionary.getItem(COSName.getPDFName(DICTIONARY_KEY_ACTION));

    if (action != null && dest != null) {
        result.add(new ValidationError(ERROR_SYNTAX_TRAILER_OUTLINES_INVALID,
                "Dest entry isn't permitted if the A entry is present"));
        return false;
    } else if (action != null) {
        List<AbstractActionManager> actions = this.actionFact.getActions(dictionary,
                handler.getDocument().getDocument());
        for (AbstractActionManager act : actions) {
            isValid = isValid && act.valid(result);
        }
    } // else no specific validation

    // ---- check children
    PDOutlineItem fChild = inputItem.getFirstChild();
    if (fChild != null) {
        if (!isCountEntryPresent(inputItem.getCOSDictionary())) {
            result.add(new ValidationError(ERROR_SYNTAX_TRAILER_OUTLINES_INVALID,
                    "Outline item doesn't have Count entry but has at least one descendant."));
            isValid = false;
        } else {
            // ---- there are some descendants, so dictionary must have a Count
            // entry
            isValid = isValid && exploreOutlineLevel(fChild, handler, result);
        }
    }

    return isValid;
}

From source file:net.padaf.preflight.helpers.CatalogValidationHelper.java

License:Apache License

/**
 * This method checks the content of each OutputIntent. The S entry must
 * contain GTS_PDFA1. The DestOuputProfile must contain a valid ICC Profile
 * Stream.//  ww w  .j  a v a  2s .c  om
 * 
 * If there are more than one OutputIntent, they have to use the same ICC
 * Profile.
 * 
 * This method returns a list of ValidationError. It is empty if no errors
 * have been found.
 * 
 * @param handler
 * @return
 * @throws ValidationException
 */
public List<ValidationError> validateOutputIntent(DocumentHandler handler) throws ValidationException {
    List<ValidationError> result = new ArrayList<ValidationError>(0);
    PDDocument pdDocument = handler.getDocument();
    PDDocumentCatalog catalog = pdDocument.getDocumentCatalog();
    COSDocument cDoc = pdDocument.getDocument();

    COSBase cBase = catalog.getCOSDictionary()
            .getItem(COSName.getPDFName(DOCUMENT_DICTIONARY_KEY_OUTPUT_INTENTS));
    COSArray outputIntents = COSUtils.getAsArray(cBase, cDoc);

    Map<COSObjectKey, Boolean> tmpDestOutputProfile = new HashMap<COSObjectKey, Boolean>();

    for (int i = 0; outputIntents != null && i < outputIntents.size(); ++i) {
        COSDictionary dictionary = COSUtils.getAsDictionary(outputIntents.get(i), cDoc);

        if (dictionary == null) {

            result.add(new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY,
                    "OutputIntent object is null or isn't a dictionary"));

        } else {
            // ---- S entry is mandatory and must be equals to GTS_PDFA1
            String sValue = dictionary.getNameAsString(COSName.getPDFName(OUTPUT_INTENT_DICTIONARY_KEY_S));
            if (!OUTPUT_INTENT_DICTIONARY_VALUE_GTS_PDFA1.equals(sValue)) {
                result.add(new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_S_VALUE_INVALID,
                        "The S entry of the OutputIntent isn't GTS_PDFA1"));
                continue;
            }

            // ---- OutputConditionIdentifier is a mandatory field
            String outputConditionIdentifier = dictionary
                    .getString(COSName.getPDFName(OUTPUT_INTENT_DICTIONARY_KEY_OUTPUT_CONDITION_IDENTIFIER));
            if (outputConditionIdentifier == null || "".equals(outputConditionIdentifier)) {
                result.add(new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY,
                        "The OutputIntentCondition is missing"));
                continue;
            }

            // ---- If OutputConditionIdentifier is "Custom" :
            // ---- DestOutputProfile and Info are mandatory
            // ---- DestOutputProfile must be a ICC Profile

            // ---- Because of PDF/A conforming file needs to specify the color
            // characteristics, the DestOutputProfile
            // is checked even if the OutputConditionIdentifier isn't "Custom"
            COSBase dop = dictionary
                    .getItem(COSName.getPDFName(OUTPUT_INTENT_DICTIONARY_KEY_DEST_OUTPUT_PROFILE));
            ValidationError valer = validateICCProfile(dop, cDoc, tmpDestOutputProfile, handler);
            if (valer != null) {
                result.add(valer);
                continue;
            }

            if (OUTPUT_INTENT_DICTIONARY_VALUE_OUTPUT_CONDITION_IDENTIFIER_CUSTOM
                    .equals(outputConditionIdentifier)) {
                String info = dictionary.getString(COSName.getPDFName(OUTPUT_INTENT_DICTIONARY_KEY_INFO));
                if (info == null || "".equals(info)) {
                    result.add(new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY,
                            "The Info entry of a OutputIntent dictionary is missing"));
                    continue;
                }
            }
        }
    }
    return result;
}

From source file:net.padaf.preflight.helpers.FileSpecificationValidationHelper.java

License:Apache License

/**
 * Validate a FileSpec dictionary, a FileSpec dictionary mustn't have the EF
 * (EmbeddedFile) entry./*from   w ww.  j  a va  2s.  c om*/
 * 
 * @param handler
 *          The document handler
 * @param cObj
 *          the FileSpec Dictionary
 * @return
 */
public List<ValidationError> validateFileSpecification(DocumentHandler handler, COSObject cObj) {
    List<ValidationError> result = new ArrayList<ValidationError>(0);
    COSDictionary fileSpec = (COSDictionary) cObj.getObject();

    // ---- Check dictionary entries
    // ---- Only the EF entry is forbidden
    if (fileSpec.getItem(COSName.getPDFName(FILE_SPECIFICATION_KEY_EMBEDDED_FILE)) != null) {
        result.add(new ValidationError(ERROR_SYNTAX_EMBEDDED_FILES,
                "EmbeddedFile entry is present in a FileSpecification dictionary"));
    }

    return result;
}

From source file:net.padaf.preflight.helpers.MetadataValidationHelper.java

License:Apache License

/**
 * Return the xpacket from the dictionary's stream
 *///from   ww  w. j ava2  s. c o m
public static byte[] getXpacket(COSDocument cdocument) throws IOException, XpacketParsingException {
    COSObject catalog = cdocument.getCatalog();
    COSBase cb = catalog.getDictionaryObject(COSName.METADATA);
    if (cb == null) {
        // missing Metadata Key in catalog
        ValidationError error = new ValidationError(ValidationConstants.ERROR_METADATA_FORMAT,
                "Missing Metadata Key in catalog");
        throw new XpacketParsingException("Failed while retrieving xpacket", error);
    }
    // no filter key
    COSDictionary metadataDictionnary = COSUtils.getAsDictionary(cb, cdocument);
    if (metadataDictionnary.getItem(COSName.FILTER) != null) {
        // should not be defined
        ValidationError error = new ValidationError(ValidationConstants.ERROR_SYNTAX_STREAM_INVALID_FILTER,
                "Filter specified in metadata dictionnary");
        throw new XpacketParsingException("Failed while retrieving xpacket", error);
    }

    PDStream stream = PDStream.createFromCOS(metadataDictionnary);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    InputStream is = stream.createInputStream();
    IOUtils.copy(is, bos);
    is.close();
    bos.close();
    return bos.toByteArray();
}

From source file:net.padaf.preflight.helpers.TrailerValidationHelper.java

License:Apache License

/**
 * Return true if the ID of the first dictionary is the same as the id of the
 * last dictionary Return false otherwise.
 * /*from w  w w.  j  av  a2s .  c  om*/
 * @param first
 * @param last
 * @return
 */
protected boolean compareIds(COSDictionary first, COSDictionary last, COSDocument doc) {
    COSBase idFirst = first.getItem(COSName.getPDFName(TRAILER_DICTIONARY_KEY_ID));
    COSBase idLast = last.getItem(COSName.getPDFName(TRAILER_DICTIONARY_KEY_ID));

    if (idFirst == null || idLast == null) {
        return false;
    }

    // ---- cast two COSBase to COSArray.
    COSArray af = COSUtils.getAsArray(idFirst, doc);
    COSArray al = COSUtils.getAsArray(idLast, doc);

    // ---- if one COSArray is null, the PDF/A isn't valid
    if ((af == null) || (al == null)) {
        return false;
    }

    // ---- compare both arrays
    boolean isEqual = true;
    for (Object of : af.toList()) {
        boolean oneIsEquals = false;
        for (Object ol : al.toList()) {
            // ---- according to PDF Reference 1-4, ID is an array containing two
            // strings
            if (!oneIsEquals)
                oneIsEquals = ((COSString) ol).getString().equals(((COSString) of).getString());
        }
        isEqual = isEqual && oneIsEquals;
    }
    return isEqual;
}

From source file:net.padaf.preflight.helpers.TrailerValidationHelper.java

License:Apache License

/**
 * check if all keys are authorized in a trailer dictionary and if the type is
 * valid./*from  w  ww .  j av  a 2 s .co  m*/
 * 
 * @param trailer
 * @param lErrors
 */
protected void checkMainTrailer(COSDocument doc, COSDictionary trailer, List<ValidationError> lErrors) {
    boolean id = false;
    boolean root = false;
    boolean size = false;
    boolean prev = false;
    boolean info = false;
    boolean encrypt = false;

    for (Object key : trailer.keySet()) {
        if (!(key instanceof COSName)) {
            lErrors.add(new ValidationResult.ValidationError(
                    ValidationConstants.ERROR_SYNTAX_DICTIONARY_KEY_INVALID,
                    "Invalid key in The trailer dictionary"));
            return;
        }

        String cosName = ((COSName) key).getName();
        if (cosName.equals(TRAILER_DICTIONARY_KEY_ENCRYPT)) {
            encrypt = true;
        }
        if (cosName.equals(TRAILER_DICTIONARY_KEY_SIZE)) {
            size = true;
        }
        if (cosName.equals(TRAILER_DICTIONARY_KEY_PREV)) {
            prev = true;
        }
        if (cosName.equals(TRAILER_DICTIONARY_KEY_ROOT)) {
            root = true;
        }
        if (cosName.equals(TRAILER_DICTIONARY_KEY_INFO)) {
            info = true;
        }
        if (cosName.equals(TRAILER_DICTIONARY_KEY_ID)) {
            id = true;
        }
    }

    // ---- PDF/A Trailer dictionary must contain the ID key
    if (!id) {
        lErrors.add(new ValidationResult.ValidationError(ValidationConstants.ERROR_SYNTAX_TRAILER_MISSING_ID,
                "The trailer dictionary doesn't contain ID"));
    } else {
        COSBase trailerId = trailer.getItem(COSName.getPDFName(TRAILER_DICTIONARY_KEY_ID));
        if (!COSUtils.isArray(trailerId, doc)) {
            lErrors.add(
                    new ValidationResult.ValidationError(ValidationConstants.ERROR_SYNTAX_TRAILER_TYPE_INVALID,
                            "The trailer dictionary contains an id but it isn't an array"));
        }
    }
    // ---- PDF/A Trailer dictionary mustn't contain the Encrypt key
    if (encrypt) {
        lErrors.add(new ValidationResult.ValidationError(ValidationConstants.ERROR_SYNTAX_TRAILER_ENCRYPT,
                "The trailer dictionary contains Encrypt"));
    }
    // ---- PDF Trailer dictionary must contain the Size key
    if (!size) {
        lErrors.add(new ValidationResult.ValidationError(ValidationConstants.ERROR_SYNTAX_TRAILER_MISSING_SIZE,
                "The trailer dictionary doesn't contain Size"));
    } else {
        COSBase trailerSize = trailer.getItem(COSName.getPDFName(TRAILER_DICTIONARY_KEY_SIZE));
        if (!COSUtils.isInteger(trailerSize, doc)) {
            lErrors.add(
                    new ValidationResult.ValidationError(ValidationConstants.ERROR_SYNTAX_TRAILER_TYPE_INVALID,
                            "The trailer dictionary contains a size but it isn't an integer"));
        }
    }

    // ---- PDF Trailer dictionary must contain the Root key
    if (!root) {
        lErrors.add(new ValidationResult.ValidationError(ValidationConstants.ERROR_SYNTAX_TRAILER_MISSING_ROOT,
                "The trailer dictionary doesn't contain Root"));
    } else {
        COSBase trailerRoot = trailer.getItem(COSName.getPDFName(TRAILER_DICTIONARY_KEY_ROOT));
        if (!COSUtils.isDictionary(trailerRoot, doc)) {
            lErrors.add(
                    new ValidationResult.ValidationError(ValidationConstants.ERROR_SYNTAX_TRAILER_TYPE_INVALID,
                            "The trailer dictionary contains a root but it isn't a dictionary"));
        }
    }
    // ---- PDF Trailer dictionary may contain the Prev key
    if (prev) {
        COSBase trailerPrev = trailer.getItem(COSName.getPDFName(TRAILER_DICTIONARY_KEY_PREV));
        if (!COSUtils.isInteger(trailerPrev, doc)) {
            lErrors.add(
                    new ValidationResult.ValidationError(ValidationConstants.ERROR_SYNTAX_TRAILER_TYPE_INVALID,
                            "The trailer dictionary contains a prev but it isn't an integer"));
        }
    }
    // ---- PDF Trailer dictionary may contain the Info key
    if (info) {
        COSBase trailerInfo = trailer.getItem(COSName.getPDFName(TRAILER_DICTIONARY_KEY_INFO));
        if (!COSUtils.isDictionary(trailerInfo, doc)) {
            lErrors.add(
                    new ValidationResult.ValidationError(ValidationConstants.ERROR_SYNTAX_TRAILER_TYPE_INVALID,
                            "The trailer dictionary contains an info but it isn't a dictionary"));
        }
    }
}

From source file:net.padaf.preflight.utils.ContentStreamEngine.java

License:Apache License

/**
 * This method validates if the ColorSpace used by the InlinedImage is
 * consistent with the color space defined in OutputIntent dictionaries.
 * /*from   w  ww. j  a  v a 2  s  . c  o  m*/
 * @param operator
 *          the InlinedImage object (BI to EI)
 * @throws ContentStreamException
 */
protected void validImageColorSpace(PDFOperator operator) throws ContentStreamException, IOException {
    COSDictionary dict = operator.getImageParameters().getDictionary();

    COSDocument doc = this.documentHandler.getDocument().getDocument();
    COSBase csInlinedBase = dict.getItem(COSName.getPDFName(STREAM_DICTIONARY_KEY_COLOR_SPACE));

    ColorSpaceHelper csHelper = null;
    if (csInlinedBase != null) {

        if (COSUtils.isString(csInlinedBase, doc)) {
            // ---- In InlinedImage only DeviceGray/RGB/CMYK and restricted Indexed
            // color spaces
            // are allowed.
            String colorSpace = COSUtils.getAsString(csInlinedBase, doc);
            ColorSpaces cs = null;

            try {
                cs = ColorSpaces.valueOf(colorSpace);
            } catch (IllegalArgumentException e) {
                // ---- The color space is unknown.
                // ---- Try to access the resources dictionary, the color space can be
                // a reference.
                PDColorSpace pdCS = (PDColorSpace) this.getColorSpaces().get(colorSpace);
                if (pdCS != null) {
                    cs = ColorSpaces.valueOf(pdCS.getName());
                    csHelper = ColorSpaceHelperFactory.getColorSpaceHelper(pdCS, documentHandler,
                            ColorSpaceRestriction.ONLY_DEVICE);
                }
            }

            if (cs == null) {
                throwContentStreamException("The ColorSpace is unknown",
                        ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY);
            }
        }

        if (csHelper == null) {
            csHelper = ColorSpaceHelperFactory.getColorSpaceHelper(csInlinedBase, documentHandler,
                    ColorSpaceRestriction.ONLY_DEVICE);
        }
        List<ValidationError> errors = new ArrayList<ValidationError>();
        try {
            if (!csHelper.validate(errors)) {
                ValidationError ve = errors.get(0);
                throwContentStreamException(ve.getDetails(), ve.getErrorCode());
            }
        } catch (ValidationException e) {
            throw new IOException(e.getMessage());
        }
    }
}

From source file:org.apache.fop.render.pdf.pdfbox.FOPPDFSingleByteFont.java

License:Apache License

public FOPPDFSingleByteFont(COSDictionary fontData, String name) throws IOException {
    super(null, EmbeddingMode.FULL);
    if (fontData.getItem(COSName.SUBTYPE) == COSName.TRUE_TYPE) {
        setFontType(FontType.TRUETYPE);/*from w  w w .  j  av a  2  s .  co  m*/
    }
    width = new int[0];
    font = getFont(fontData);
    setFirstChar(font.getFirstChar());
    setLastChar(font.getLastChar());
    shortFontName = MergeFontsPDFWriter.getName(font.font.getName());
    loadFontFile(font);
    float[] bBoxF = font.getBoundingBox();
    int[] bBox = new int[bBoxF.length];
    for (int i = 0; i < bBox.length; i++) {
        bBox[i] = (int) bBoxF[i];
    }
    setFontBBox(bBox);

    setFontName(name);
    Object cmap = getCmap(font);
    for (int i = font.getFirstChar(); i <= font.getLastChar(); i++) {
        String mappedChar = getChar(cmap, i);
        if (mappedChar != null && !charMapGlobal.containsKey(mappedChar)) {
            charMapGlobal.put(mappedChar, i);
        }
    }
    //mark font as used
    notifyMapOperation();
    FOPPDFMultiByteFont.setProperties(this, font.font);
    if (font.getWidths() != null) {
        //if width contains 0 we cant rely on codeToNameMap
        boolean usesZero = font.getWidths().contains(0);
        Set<Integer> codeToName = getCodeToName(font.getEncoding()).keySet();
        for (int i = getFirstChar(); i <= Math.min(getLastChar(),
                getFirstChar() + font.getWidths().size()); i++) {
            if (usesZero || codeToName.contains(i)) {
                int w = font.getWidths().get(i - getFirstChar());
                newWidth.put(i, w);
            } else {
                newWidth.put(i, 0);
            }
        }
    }
    mapping = new FOPPDFEncoding();
    encodingSkip = font.getLastChar() + 1;
    addEncoding(font);
}

From source file:org.apache.fop.render.pdf.pdfbox.MergeFontsPDFWriter.java

License:Apache License

private String getNewFont(COSDictionary fontData, FontInfo fontinfo, Collection<String> usedFonts)
        throws IOException {
    String base = getUniqueFontName(fontData);
    if (base == null || usedFonts.contains(base) || (parentFonts != null && parentFonts.contains(base))) {
        return null;
    }//from   ww  w .  ja  v a  2  s  . c o  m
    try {
        for (Typeface t : fontinfo.getUsedFonts().values()) {
            if (t instanceof FOPPDFFont && base.equals(t.getFontName())) {
                return ((FOPPDFFont) t).addFont(fontData);
            }
        }
        if (base.endsWith("cid") || fontData.getItem(COSName.SUBTYPE) != COSName.TYPE1
                && fontData.getItem(COSName.SUBTYPE) != COSName.TRUE_TYPE) {
            fontinfo.addMetrics(base, new FOPPDFMultiByteFont(fontData, base));
        } else {
            fontinfo.addMetrics(base, new FOPPDFSingleByteFont(fontData, base));
        }
    } catch (IOException e) {
        log.warn(e.getMessage());
        return null;
    }
    fontinfo.useFont(base);
    return base;
}