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:com.aaasec.sigserv.csspsupport.pdfbox.modifications.CsCOSWriter.java

License:Apache License

/**
 * This will write a COS object.//ww w . j  ava 2 s .  c o  m
 *
 * @param obj The object to write.
 *
 * @throws COSVisitorException If there is an error visiting objects.
 */
public void doWriteObject(COSBase obj) throws COSVisitorException {
    try {
        writtenObjects.add(obj);
        if (obj instanceof COSDictionary) {
            COSDictionary dict = (COSDictionary) obj;
            COSName item = (COSName) dict.getItem(COSName.TYPE);
            if (COSName.SIG.equals(item) || COSName.DOC_TIME_STAMP.equals(item)) {
                reachedSignature = true;
            }
        }

        // find the physical reference
        currentObjectKey = getObjectKey(obj);
        // add a x ref entry
        addXRefEntry(new COSWriterXRefEntry(getStandardOutput().getPos(), obj, currentObjectKey));
        // write the object
        getStandardOutput().write(String.valueOf(currentObjectKey.getNumber()).getBytes("ISO-8859-1"));
        getStandardOutput().write(SPACE);
        getStandardOutput().write(String.valueOf(currentObjectKey.getGeneration()).getBytes("ISO-8859-1"));
        getStandardOutput().write(SPACE);
        getStandardOutput().write(OBJ);
        getStandardOutput().writeEOL();
        obj.accept(this);
        getStandardOutput().writeEOL();
        getStandardOutput().write(ENDOBJ);
        getStandardOutput().writeEOL();
    } catch (IOException e) {
        throw new COSVisitorException(e);
    }
}

From source file:com.aaasec.sigserv.csspsupport.pdfbox.modifications.CsCOSWriter.java

License:Apache License

/**
 * visitFromDictionary method comment.//from   ww w. j ava2s  . com
 *
 * @param obj The object that is being visited.
 *
 * @throws COSVisitorException If there is an exception while visiting this
 * object.
 *
 * @return null
 */
public Object visitFromDictionary(COSDictionary obj) throws COSVisitorException {
    try {
        getStandardOutput().write(DICT_OPEN);
        getStandardOutput().writeEOL();
        for (Map.Entry<COSName, COSBase> entry : obj.entrySet()) {
            COSBase value = entry.getValue();
            if (value != null) {
                entry.getKey().accept(this);
                getStandardOutput().write(SPACE);
                if (value instanceof COSDictionary) {
                    COSDictionary dict = (COSDictionary) value;

                    // write all XObjects as direct objects, this will save some size
                    COSBase item = dict.getItem(COSName.XOBJECT);
                    if (item != null) {
                        item.setDirect(true);
                    }
                    item = dict.getItem(COSName.RESOURCES);
                    if (item != null) {
                        item.setDirect(true);
                    }

                    if (dict.isDirect()) {
                        // If the object should be written direct, we need
                        // to pass the dictionary to the visitor again.
                        visitFromDictionary(dict);
                    } else {
                        addObjectToWrite(dict);
                        writeReference(dict);
                    }
                } else if (value instanceof COSObject) {
                    COSBase subValue = ((COSObject) value).getObject();
                    if (subValue instanceof COSDictionary || subValue == null) {
                        addObjectToWrite(value);
                        writeReference(value);
                    } else {
                        subValue.accept(this);
                    }
                } else {
                    // If we reach the pdf signature, we need to determinate the position of the
                    // content and byterange
                    if (reachedSignature && COSName.CONTENTS.equals(entry.getKey())) {
                        signaturePosition = new int[2];
                        signaturePosition[0] = (int) getStandardOutput().getPos();
                        value.accept(this);
                        signaturePosition[1] = (int) getStandardOutput().getPos();
                    } else if (reachedSignature && COSName.BYTERANGE.equals(entry.getKey())) {
                        byterangePosition = new int[2];
                        byterangePosition[0] = (int) getStandardOutput().getPos() + 1;
                        value.accept(this);
                        byterangePosition[1] = (int) getStandardOutput().getPos() - 1;
                        reachedSignature = false;
                    } else {
                        value.accept(this);
                    }
                }
                getStandardOutput().writeEOL();

            } else {
                //then we won't write anything, there are a couple cases
                //were the value of an entry in the COSDictionary will
                //be a dangling reference that points to nothing
                //so we will just not write out the entry if that is the case
            }
        }
        getStandardOutput().write(DICT_CLOSE);
        getStandardOutput().writeEOL();
        return null;
    } catch (IOException e) {
        throw new COSVisitorException(e);
    }
}

From source file:com.esri.geoportal.commons.pdf.PdfUtils.java

License:Apache License

/**
 * Reads metadata values from a PDF file.
 * /*w ww.j a  v  a  2s. c o m*/
 * @param rawBytes the PDF to read
 * @param defaultTitle title to be used if the PDF metadata doesn't have one
 * @param geometryServiceUrl url of a <a href="https://developers.arcgis.com/rest/services-reference/geometry-service.htm">geometry service</a> for reprojecting coordinates. 
 * 
 * @return metadata properties or null if the PDF cannot be read.
 * 
 * @throws IOException on parsing error
 */
public static Properties readMetadata(byte[] rawBytes, String defaultTitle, String geometryServiceUrl)
        throws IOException {
    Properties ret = new Properties();

    // Attempt to read in the PDF file
    try (PDDocument document = PDDocument.load(rawBytes)) {

        // See if we can read the PDF
        if (!document.isEncrypted()) {
            // Get document metadata
            PDDocumentInformation info = document.getDocumentInformation();

            if (info != null) {

                if (info.getTitle() != null) {
                    ret.put(PROP_TITLE, info.getTitle());
                } else {
                    ret.put(PROP_TITLE, defaultTitle);
                }

                if (info.getSubject() != null) {
                    ret.put(PROP_SUBJECT, info.getSubject());
                } else {

                    StringBuilder psudoSubject = new StringBuilder("");
                    psudoSubject.append("\nAuthor: " + info.getAuthor());
                    psudoSubject.append("\nCreator: " + info.getCreator());
                    psudoSubject.append("\nProducer: " + info.getProducer());

                    ret.put(PROP_SUBJECT, psudoSubject.toString());
                }

                if (info.getModificationDate() != null) {
                    ret.put(PROP_MODIFICATION_DATE, info.getModificationDate().getTime());
                } else {
                    ret.put(PROP_MODIFICATION_DATE, info.getCreationDate().getTime());
                }
            } else {
                LOG.warn("Got null metadata for PDF file");
                return null;
            }

            // Attempt to read in geospatial PDF data
            COSObject measure = document.getDocument().getObjectByType(COSName.getPDFName("Measure"));
            String bBox = null;
            if (measure != null) {
                // This is a Geospatial PDF (i.e. Adobe's standard)
                COSDictionary dictionary = (COSDictionary) measure.getObject();

                float[] coords = ((COSArray) dictionary.getItem("GPTS")).toFloatArray();

                bBox = generateBbox(coords);
            } else {
                PDPage page = document.getPage(0);
                if (page.getCOSObject().containsKey(COSName.getPDFName("LGIDict"))) {
                    // This is a GeoPDF (i.e. TerraGo's standard)
                    bBox = extractGeoPDFProps(page, geometryServiceUrl);
                }
            }

            if (bBox != null) {
                ret.put(PROP_BBOX, bBox);
            }

        } else {
            LOG.warn("Cannot read encrypted PDF file");
            return null;
        }

    } catch (IOException ex) {
        LOG.error("Exception reading PDF", ex);
        throw ex;
    }

    return ret;
}

From source file:com.esri.geoportal.commons.pdf.PdfUtils.java

License:Apache License

/**
 * Extracts the geospatial metadata from a GeoPDF
 * //from w  w w .  j  av a 2  s  .  com
 * @param page the PDF page to read geospatial metadata from
 * @param geometryServiceUrl url of a <a href="https://developers.arcgis.com/rest/services-reference/geometry-service.htm">geometry service</a> for reprojecting coordinates. 
 * 
 * @see <a href="https://www.loc.gov/preservation/digital/formats/fdd/fdd000312.shtml">Library of Congress information on GeoPDF</a>
 * @see <a href="https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf">The PDF specification</a>, section 8, for instructions for translating coordinates.
 * 
 * @returns the bounding box of the GeoPDF as "yMin xMin, yMax xMax"
 */
private static String extractGeoPDFProps(PDPage page, String geometryServiceUrl) {

    // The LGI dictionary is an array, we'll loop through all entries and pull the first one for a bounding box
    COSArray lgi = (COSArray) page.getCOSObject().getDictionaryObject("LGIDict");

    List<String> bBoxes = new ArrayList<>();

    lgi.iterator().forEachRemaining(item -> {

        String currentBbox = null;

        // Set up the Coordinate Transformation Matrix (used to translate PDF coords to geo coords)
        Double[][] ctmValues = null;

        COSDictionary dictionary = (COSDictionary) item;
        if (dictionary.containsKey("CTM")) {
            ctmValues = new Double[3][3];

            // The last column in the matrix is always constant
            ctmValues[0][2] = 0.0;
            ctmValues[1][2] = 0.0;
            ctmValues[2][2] = 1.0;

            COSArray ctm = (COSArray) dictionary.getDictionaryObject("CTM");
            for (int i = 0; i < ctm.toList().size(); i += 2) {
                int ctmRow = i / 2;
                ctmValues[ctmRow][0] = Double.parseDouble(((COSString) ctm.get(i)).getString());
                ctmValues[ctmRow][1] = Double.parseDouble(((COSString) ctm.get(i + 1)).getString());
            }
        }

        // Get the neatline (i.e. the bounding box in *PDF* coordinates)
        Double[][] neatLineValues = null;
        int neatLineLength = 0;
        if (dictionary.containsKey("Neatline")) {

            COSArray neatline = (COSArray) dictionary.getDictionaryObject("Neatline");
            neatLineLength = neatline.toList().size();
            neatLineValues = new Double[neatLineLength / 2][3];

            for (int i = 0; i < neatline.toList().size(); i += 2) {
                int neatLineRow = i / 2;
                neatLineValues[neatLineRow][0] = Double.parseDouble(((COSString) neatline.get(i)).getString());
                neatLineValues[neatLineRow][1] = Double
                        .parseDouble(((COSString) neatline.get(i + 1)).getString());
                neatLineValues[neatLineRow][2] = 1.0;
            }
        }

        // Translate the PDF coordinates to Geospatial coordintates by multiplying the two matricies
        MultiPoint mp = new MultiPoint();
        if (ctmValues != null && neatLineValues != null) {
            Double[][] resultCoords = new Double[neatLineLength / 2][3];
            for (int z = 0; z < neatLineLength / 2; z++) {
                for (int i = 0; i < 3; i++) {
                    resultCoords[z][i] = neatLineValues[z][0] * ctmValues[0][i]
                            + neatLineValues[z][1] * ctmValues[1][i] + neatLineValues[z][2] * ctmValues[2][i];
                }
                mp.add(resultCoords[z][0], resultCoords[z][1]);
            }
        }

        // Project the geospatial coordinates to WGS84 for the Dublin-Core metadata
        if (dictionary.containsKey("Projection")) {
            COSDictionary projectionDictionary = (COSDictionary) dictionary.getDictionaryObject("Projection");
            String projectionType = projectionDictionary.getString("ProjectionType");

            try (GeometryService svc = new GeometryService(HttpClients.custom().useSystemProperties().build(),
                    new URL(geometryServiceUrl));) {

                // UTM projections require slightly different processing
                if ("UT".equals(projectionType)) {
                    String zone = Integer.toString(projectionDictionary.getInt("Zone"));
                    String hemisphere = projectionDictionary.getString("Hemisphere");

                    // Get the wkt for the geospatial coordinate system
                    String wkt = datumTranslation(projectionDictionary.getItem("Datum"));

                    if (zone != null && hemisphere != null && wkt != null) {
                        // Generate a list of UTM strings
                        List<String> utmCoords = new ArrayList<>();
                        for (Point2D pt : mp.getCoordinates2D()) {
                            String coord = String.format("%s%s %s %s", zone, hemisphere, Math.round(pt.x),
                                    Math.round(pt.y));
                            utmCoords.add(coord);
                        }

                        MultiPoint reproj = svc.fromGeoCoordinateString(utmCoords, WGS84_WKID);

                        currentBbox = generateBbox(reproj);

                    } else {
                        LOG.warn("Missing UTM argument: zone: {}, hemisphere: {}, datum: {}", zone, hemisphere,
                                wkt);
                        LOG.debug("Projection dictionary {}", projectionDictionary);
                    }
                } else {
                    // Generate Well Known Text for projection and re-projects the points to WGS 84
                    String wkt = getProjectionWKT(projectionDictionary, projectionType);

                    if (wkt != null) {
                        MultiPoint reproj = svc.project(mp, wkt, WGS84_WKID);

                        currentBbox = generateBbox(reproj);

                    } else if (LOG.isDebugEnabled()) {
                        // Print out translated coordinates for debugging purposes
                        LOG.debug("Translated Coordinates");
                        for (Point2D pt : mp.getCoordinates2D()) {
                            LOG.debug(String.format("\t%s, %s", pt.x, pt.y));
                        }
                    }
                }
            } catch (Exception e) {
                // If something goes wrong, just try the next set of coordinates
                LOG.error("Exception reprojecting geometry, skipping this geopdf dictionary instance...", e);
            }
        }

        if (currentBbox != null) {
            bBoxes.add(currentBbox);
        }

    });

    return bBoxes.get(0);
}

From source file:ddf.catalog.transformer.input.pdf.GeoPdfParserImpl.java

License:Open Source License

/**
 * Generates a WKT compliant String from a PDF Document if it contains GeoPDF information.
 * Currently, only WGS84 Projections are supported (GEOGRAPHIC GeoPDF ProjectionType).
 *
 * @param pdfDocument - The PDF document
 * @return the WKT String/*from  www  .  j  a v  a 2s  .  c o  m*/
 * @throws IOException
 */
@Override
public String apply(PDDocument pdfDocument) throws IOException {
    ToDoubleVisitor toDoubleVisitor = new ToDoubleVisitor();
    LinkedList<String> polygons = new LinkedList<>();

    for (PDPage pdPage : pdfDocument.getPages()) {
        COSDictionary cosObject = pdPage.getCOSObject();

        COSBase lgiDictObject = cosObject.getObjectFromPath(LGIDICT);

        // Handle Multiple Map Frames
        if (lgiDictObject instanceof COSArray) {
            for (int i = 0; i < ((COSArray) lgiDictObject).size(); i++) {
                COSDictionary lgidict = (COSDictionary) cosObject.getObjectFromPath(LGIDICT + "/[" + i + "]");

                COSDictionary projectionArray = (COSDictionary) lgidict.getDictionaryObject(PROJECTION);
                if (projectionArray != null) {
                    String projectionType = ((COSString) projectionArray.getItem(PROJECTION_TYPE)).getString();
                    if (GEOGRAPHIC.equals(projectionType)) {
                        COSArray neatlineArray = (COSArray) cosObject
                                .getObjectFromPath(LGIDICT + "/[" + i + "]/" + NEATLINE);
                        String wktString = getWktFromNeatLine(lgidict, neatlineArray, toDoubleVisitor);
                        polygons.add(wktString);
                    } else {
                        LOGGER.debug("Unsupported projection type {}.  Map Frame will be skipped.",
                                projectionType);
                    }
                } else {
                    LOGGER.debug("No projection array found on the map frame.  Map Frame will be skipped.");
                }
            }
            // Handle One Map Frame
        } else if (lgiDictObject instanceof COSDictionary) {
            COSDictionary lgidict = (COSDictionary) lgiDictObject;
            COSDictionary projectionArray = (COSDictionary) lgidict.getDictionaryObject(PROJECTION);
            if (projectionArray != null) {
                String projectionType = ((COSString) projectionArray.getItem(PROJECTION_TYPE)).getString();
                if (GEOGRAPHIC.equals(projectionType)) {
                    COSArray neatlineArray = (COSArray) cosObject.getObjectFromPath(LGIDICT + "/" + NEATLINE);
                    if (neatlineArray == null) {
                        neatlineArray = generateNeatLineFromPDFDimensions(pdPage);

                    }
                    polygons.add(getWktFromNeatLine(lgidict, neatlineArray, toDoubleVisitor));

                } else {
                    LOGGER.debug("Unsupported projection type {}.  Map Frame will be skipped.", projectionType);
                }
            } else {
                LOGGER.debug("No projection array found on the map frame.  Map Frame will be skipped.");
            }
        }
    }

    if (polygons.size() == 0) {
        LOGGER.debug(
                "No GeoPDF information found on PDF during transformation.  Metacard location will not be set.");
        return null;
    }

    if (polygons.size() == 1) {
        return POLYGON + polygons.get(0) + "))";
    } else {
        return polygons.stream().map(polygon -> "((" + polygon + "))")
                .collect(Collectors.joining(",", MULTIPOLYGON, ")"));
    }
}

From source file:modules.PDFFontDependencyExtractorModule.java

License:Apache License

public PDFFontResults extractFontList(File f) throws IOException, InvalidParameterException {
    PDDocument document;/*  www .  j  a v a  2s .c o m*/
    try {
        document = PDDocument.load(f);
    } catch (IOException x) {
        throw new InvalidParameterException("Not a PDF file");
    }
    SortedSet<FontInformation> ret = new TreeSet<FontInformation>(new Comparator<FontInformation>() {

        @Override
        public int compare(FontInformation o1, FontInformation o2) {
            int a = o1.fontName.compareTo(o2.fontName);
            if (a != 0)
                return a;
            else
                return o1.fontType.compareTo(o2.fontType);
        }

    });

    document.getDocumentCatalog().getAllPages();
    // The code down here is easier as it gets all the fonts used in the
    // document. Still, this would inlcude unused fonts, so we get the fonts
    // page by page and add them to a Hash table.
    for (COSObject c : document.getDocument().getObjectsByType(COSName.FONT)) {
        if (c == null || !(c.getObject() instanceof COSDictionary)) {
            continue;
            // System.out.println(c.getObject());
        }

        COSDictionary fontDictionary = (COSDictionary) c.getObject();
        // System.out.println(dic.getNameAsString(COSName.BASE_FONT));
        // }
        // }
        // int pagen = document.getNumberOfPages();
        // i=0;
        // for (int p=0;p<pagen;p++){
        // PDPage page = (PDPage)pages.get(p);
        // PDResources res = page.findResources();
        // //for each page resources
        // if (res==null) continue;
        // // get the font dictionary
        // COSDictionary fonts = (COSDictionary)
        // res.getCOSDictionary().getDictionaryObject( COSName.FONT );
        // for( COSName fontName : fonts.keySet() ) {
        // COSObject font = (COSObject) fonts.getItem( fontName );
        // // if the font has already been visited we ingore it
        // long objectId = font.getObjectNumber().longValue();
        // if (ret.get(objectId)!=null)
        // continue;
        // if( font==null || ! (font.getObject() instanceof COSDictionary) )
        // continue;
        // COSDictionary fontDictionary = (COSDictionary)font.getObject();

        // Type MUSt be font
        if (!fontDictionary.getNameAsString(COSName.TYPE).equals("Font")) {
            continue;
        }
        // get the variables
        FontInformation fi = new FontInformation();
        fi.fontType = fontDictionary.getNameAsString(COSName.SUBTYPE);

        String baseFont = fontDictionary.getNameAsString(COSName.BASE_FONT);
        if (baseFont == null) {
            continue;
        }
        if (Arrays.binarySearch(standard14, baseFont) >= 0) {
            continue;
        }
        COSDictionary fontDescriptor = (COSDictionary) fontDictionary.getDictionaryObject(COSName.FONT_DESC);
        COSBase enc = fontDictionary.getItem(COSName.ENCODING);
        COSBase uni = fontDictionary.getItem(COSName.TO_UNICODE);
        fontDictionary.getInt(COSName.FIRST_CHAR);
        fontDictionary.getInt(COSName.LAST_CHAR);
        String encoding;
        boolean toUnicode = uni != null;
        if (enc == null) {
            encoding = "standard14";
        }
        if (enc instanceof COSString) {
            encoding = ((COSString) enc).getString();
        } else {
            encoding = "table";
        }
        fi.isSubset = false;
        boolean t = true;
        // Type one and TT can have subsets defineing the basename see 5.5.3
        // pdfref 1.6
        // if (fi.fontType.lastIndexOf(COSName.TYPE1.getName())!=-1 ||
        // fi.fontType.equals(COSName.TRUE_TYPE.getName()) )
        if (baseFont != null) {
            if (baseFont.length() > 6) {
                for (int k = 0; k < 6; k++)
                    if (!Character.isUpperCase(baseFont.charAt(k))) {
                        t = false;
                    }
                if (baseFont.charAt(6) != '+') {
                    t = false;
                }
            } else {
                t = false;
            }
            fi.isSubset = t;
            if (fi.isSubset) {
                fi.baseName = baseFont.substring(0, 6);
                baseFont = baseFont.substring(7);
            }
        }
        fi.fontFlags = 0;
        if (fi.fontType.equals(COSName.TYPE0.getName()) || fi.fontType.equals(COSName.TYPE3.getName())) {
            fi.isEmbedded = true;
        }

        if (fontDescriptor != null) {
            // in Type1 charset indicates font is subsetted
            if (fontDescriptor.getItem(COSName.CHAR_SET) != null) {
                fi.isSubset = true;
            }
            if (fontDescriptor.getItem(COSName.FONT_FILE) != null
                    || fontDescriptor.getItem(COSName.FONT_FILE3) != null
                    || fontDescriptor.getItem(COSName.FONT_FILE2) != null) {
                fi.isEmbedded = true;
            }
            fi.fontFlags = fontDescriptor.getInt(COSName.getPDFName("Flags"));
            fi.fontFamily = fontDescriptor.getString(COSName.FONT_FAMILY);
            fi.fontStretch = fontDescriptor.getString(COSName.FONT_STRETCH);

        }
        fi.charset = encoding;
        fi.fontName = baseFont;
        fi.isToUnicode = toUnicode;
        fi.encoding = fontDictionary.getNameAsString(COSName.CID_TO_GID_MAP);

        ret.add(fi);

    } // for all fonts

    HashMultimap<String, FontInformation> m = HashMultimap.create();

    for (FontInformation ff : ret) {
        m.put(ff.fontName, ff);
    }
    LinkedList<FontInformation> missing = new LinkedList<FontInformation>();
    Set<String> k = m.keySet();
    for (String kk : k) {
        Set<FontInformation> s = m.get(kk);
        if (s.size() < 1) {
            continue;
        }
        if (s.size() > 1) {
            boolean found = false;
            FontInformation ff = null;
            for (FontInformation fonti : s) {
                if (!fonti.isEmbedded) {
                    ff = fonti;
                } else {
                    found = true;
                }
            }
            if (!found) {
                missing.add(ff);
            }
        } else {
            FontInformation ff = s.iterator().next();
            if (!ff.isEmbedded) {
                missing.add(ff);
            }
        }

    }

    // } // for all pages
    // Iterator<FontInformation> it = ret.iterator();
    // FontInformation prev = null;
    // LinkedList<FontInformation> toDelete = new
    // LinkedList<FontInformation>();
    // while (it.hasNext()) {
    // FontInformation current = it.next();
    //
    // if (prev!= null && prev.fontName.equals(current.fontName) &&
    // (prev.fontType.startsWith("CIDFontType") ||
    // current.fontType.startsWith("CIDFontType")))
    // toDelete.add(current);
    // prev = current;
    // }
    //
    // //ret.removeAll(toDelete);
    // FontInformation[] retArray =toDelete.toArray(new FontInformation[0]);
    //

    if (missing.size() == 0) {
        missing = null;
    } else {
        System.out.println("Found missing fonts: " + f);
        System.out.println(missing);
    }
    return new PDFFontResults(new LinkedList<FontInformation>(ret), missing);
}

From source file:net.padaf.preflight.actions.ActionManagerFactory.java

License:Apache License

/**
 * This method extract actions from the given dictionary. An action is
 * identified by the following entries :
 * <UL>//  w ww  . j  a va2s.c  o m
 * <li>A (Action) : Available in Annotations, Outline items
 * <li>OpenAction (OpenAction) : Available in the Catalog dictionary
 * <li>AA (Additional Action) : Available in the Catalog dictionary,
 * Annotations, Pages
 * </UL>
 * 
 * If there are no action, an empty list is returned.
 * 
 * @param dictionary
 * @param cDoc
 * @return
 * @throws ValidationException
 */
public final List<AbstractActionManager> getActions(COSDictionary dictionary, COSDocument cDoc)
        throws ValidationException {

    List<AbstractActionManager> result = new ArrayList<AbstractActionManager>(0);
    Map<COSObjectKey, Boolean> alreadyCreated = new HashMap<COSObjectKey, Boolean>();

    COSBase aDict = dictionary.getDictionaryObject(DICTIONARY_KEY_ACTION);
    if (aDict != null) {
        callCreateAction(aDict, cDoc, result, alreadyCreated);
    }

    COSBase oaDict = dictionary.getDictionaryObject(DICTIONARY_KEY_OPEN_ACTION);
    if (oaDict != null) {
        if (!COSUtils.isArray(oaDict, cDoc)) {
            callCreateAction(oaDict, cDoc, result, alreadyCreated);
        }
        // else Nothing to do because of an array contains a Destination not an
        // action.
    }

    COSBase aa = dictionary.getDictionaryObject(DICTIONARY_KEY_ADDITIONAL_ACTION);
    if (aa != null) {
        COSDictionary aaDict = COSUtils.getAsDictionary(aa, cDoc);
        if (aaDict != null) {
            for (Object key : aaDict.keySet()) {
                COSName name = (COSName) key;
                callCreateAction(aaDict.getItem(name), cDoc, result, name.getName(), alreadyCreated);
            }
        }
    }
    return result;
}

From source file:net.padaf.preflight.annotation.AnnotationValidator.java

License:Apache License

/**
 * This method checks the AP entry of the Annotation Dictionary. If the AP key
 * is missing, this method returns true. If the AP key exists, only the N
 * entry is authorized and must be a Stream which define the appearance of the
 * annotation. (Currently, only the type of the N entry is checked because of
 * the Appearance stream is a Form XObject, so it will be checked by the
 * Graphics Helper)//w ww  . j av a  2s .c  o  m
 * 
 * If the AP content isn't valid, this method return false and updates the
 * errors list.
 * 
 * @param errors
 *          list of errors which is updated if validation fails
 * @return
 */
protected boolean checkAP(List<ValidationError> errors) {
    PDAppearanceDictionary ap = this.pdAnnot.getAppearance();
    if (ap != null) {
        COSDictionary apDict = ap.getDictionary();
        // ---- Only N entry is authorized
        if (apDict.getItem(COSName.getPDFName(ANNOT_DICTIONARY_KEY_D)) != null
                || apDict.getItem(COSName.getPDFName(ANNOT_DICTIONARY_KEY_R)) != null) {
            errors.add(new ValidationResult.ValidationError(ValidationConstants.ERROR_ANNOT_INVALID_AP_CONTENT,
                    "Only the N Appearance is authorized"));
            return false;
        } else if (apDict.getItem(COSName.getPDFName(ANNOT_DICTIONARY_KEY_N)) == null) {
            // ---- N entry is required
            errors.add(new ValidationResult.ValidationError(
                    ValidationConstants.ERROR_ANNOT_MISSING_AP_N_CONTENT, "The N Appearance must be present"));
            return false;
        } else {
            // ---- the N entry must be a Stream (Dictionaries are forbidden)
            COSBase apn = apDict.getItem(COSName.getPDFName(ANNOT_DICTIONARY_KEY_N));
            if (!COSUtils.isStream(apn, this.cosDoc)) {
                errors.add(
                        new ValidationResult.ValidationError(ValidationConstants.ERROR_ANNOT_INVALID_AP_CONTENT,
                                "The N Appearance must be a Stream"));
                return false;
            }
        }
    } //else  ok, nothing to check,this field is optional
    return true;
}

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

License:Apache License

/**
 * Check the content of the CIDSystemInfo dictionary. A CIDSystemInfo
 * dictionary must contain ://from w  w  w .ja va2s.c  om
 * <UL>
 * <li>a Name - Registry
 * <li>a Name - Ordering
 * <li>a Integer - Supplement
 * </UL>
 * 
 * @param sysinfo
 * @param cDoc
 * @return
 */
private boolean checkCIDSystemInfo(COSBase sysinfo, COSDocument cDoc) {
    COSDictionary cidSysInfo = COSUtils.getAsDictionary(sysinfo, cDoc);
    if (cidSysInfo == null) {
        this.fontContainer.addError(new ValidationError(ERROR_FONTS_CIDKEYED_SYSINFO));
        return false;
    }

    COSBase reg = cidSysInfo.getItem(COSName.getPDFName(FONT_DICTIONARY_KEY_SYSINFO_REGISTRY));
    COSBase ord = cidSysInfo.getItem(COSName.getPDFName(FONT_DICTIONARY_KEY_SYSINFO_ORDERING));
    COSBase sup = cidSysInfo.getItem(COSName.getPDFName(FONT_DICTIONARY_KEY_SYSINFO_SUPPLEMENT));

    if (!(COSUtils.isString(reg, cDoc) && COSUtils.isString(ord, cDoc) && COSUtils.isInteger(sup, cDoc))) {
        this.fontContainer.addError(new ValidationError(ERROR_FONTS_CIDKEYED_SYSINFO));
        return false;
    }

    return true;
}

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

License:Apache License

/**
 * The CIDSystemInfo must have the same Registry and Ordering for CMap and
 * CIDFont. This control is useless if CMap is Identity-H or Identity-V so
 * this method is called by the checkCMap method.
 * /*from w  w w .  j av  a2 s  .  c o m*/
 * @param errors
 * @return
 */
private boolean compareCIDSystemInfo() {
    COSDocument cDoc = handler.getDocument().getDocument();
    if (!isIdentityCMap) {
        COSDictionary cmsi = COSUtils
                .getAsDictionary(this.cmap.getItem(COSName.getPDFName(FONT_DICTIONARY_KEY_CID_SYSINFO)), cDoc);
        COSDictionary cfsi = COSUtils.getAsDictionary(
                this.cidFont.getItem(COSName.getPDFName(FONT_DICTIONARY_KEY_CID_SYSINFO)), cDoc);

        String regCM = COSUtils
                .getAsString(cmsi.getItem(COSName.getPDFName(FONT_DICTIONARY_KEY_SYSINFO_REGISTRY)), cDoc);
        String ordCM = COSUtils
                .getAsString(cmsi.getItem(COSName.getPDFName(FONT_DICTIONARY_KEY_SYSINFO_ORDERING)), cDoc);

        String regCF = COSUtils
                .getAsString(cfsi.getItem(COSName.getPDFName(FONT_DICTIONARY_KEY_SYSINFO_REGISTRY)), cDoc);
        String ordCF = COSUtils
                .getAsString(cfsi.getItem(COSName.getPDFName(FONT_DICTIONARY_KEY_SYSINFO_ORDERING)), cDoc);

        if (!regCF.equals(regCM) || !ordCF.equals(ordCM)) {
            this.fontContainer.addError(
                    new ValidationError(ERROR_FONTS_CIDKEYED_SYSINFO, "The CIDSystemInfo is inconsistent"));
            return false;
        }
    } // else cmap is null because it is a Identity-H/V
    return true;
}