List of usage examples for org.apache.pdfbox.cos COSDictionary getDictionaryObject
public COSBase getDictionaryObject(COSName key)
From source file:com.itdhq.poc.ocrsign.ShowSignature.java
License:Apache License
private void showSignature(String[] args) throws IOException, CertificateException { if (args.length != 2) { usage();//from www .ja va2 s . c o m } else { String password = args[0]; String infile = args[1]; PDDocument document = null; try { document = PDDocument.load(new File(infile)); if (!document.isEncrypted()) { System.err.println("Warning: Document is not encrypted."); } COSDictionary trailer = document.getDocument().getTrailer(); COSDictionary root = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT); COSDictionary acroForm = (COSDictionary) root.getDictionaryObject(COSName.ACRO_FORM); COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS); for (int i = 0; i < fields.size(); i++) { COSDictionary field = (COSDictionary) fields.getObject(i); // FIXME /* COSName type = field.getCOSName( COSName.FT ); if( COSName.SIG.equals( type ) ) { COSDictionary cert = (COSDictionary)field.getDictionaryObject( COSName.V ); if( cert != null ) { System.out.println( "Certificate found" ); System.out.println( "Name=" + cert.getDictionaryObject( COSName.NAME ) ); System.out.println( "Modified=" + cert.getDictionaryObject( COSName.M ) ); COSName subFilter = (COSName)cert.getDictionaryObject( COSName.SUB_FILTER ); if( subFilter != null ) { if( subFilter.getName().equals( "adbe.x509.rsa_sha1" ) ) { COSString certString = (COSString)cert.getDictionaryObject( COSName.getPDFName( "Cert" ) ); byte[] certData = certString.getBytes(); CertificateFactory factory = CertificateFactory.getInstance( "X.509" ); ByteArrayInputStream certStream = new ByteArrayInputStream( certData ); Collection<? extends Certificate> certs = factory.generateCertificates( certStream ); System.out.println( "certs=" + certs ); } else if( subFilter.getName().equals( "adbe.pkcs7.sha1" ) ) { COSString certString = (COSString)cert.getDictionaryObject( COSName.CONTENTS ); byte[] certData = certString.getBytes(); CertificateFactory factory = CertificateFactory.getInstance( "X.509" ); ByteArrayInputStream certStream = new ByteArrayInputStream( certData ); Collection<? extends Certificate> certs = factory.generateCertificates( certStream ); System.out.println( "certs=" + certs ); } else { System.err.println( "Unknown certificate type:" + subFilter ); } } else { throw new IOException( "Missing subfilter for cert dictionary" ); } } else { System.out.println( "Signature found, but no certificate" ); } } */ } } finally { if (document != null) { document.close(); } } } }
From source file:com.modemo.javase.signature.SigUtils.java
License:Apache License
/** * Get the access permissions granted for this document in the DocMDP transform parameters * dictionary. Details are described in the table "Entries in the DocMDP transform parameters * dictionary" in the PDF specification. * * @param doc document.// w w w. j a va 2s. c om * @return the permission value. 0 means no DocMDP transform parameters dictionary exists. Other * return values are 1, 2 or 3. 2 is also returned if the DocMDP transform parameters dictionary * is found but did not contain a /P entry, or if the value is outside the valid range. */ public static int getMDPPermission(PDDocument doc) { COSBase base = doc.getDocumentCatalog().getCOSObject().getDictionaryObject(COSName.PERMS); if (base instanceof COSDictionary) { COSDictionary permsDict = (COSDictionary) base; base = permsDict.getDictionaryObject(COSName.DOCMDP); if (base instanceof COSDictionary) { COSDictionary signatureDict = (COSDictionary) base; base = signatureDict.getDictionaryObject("Reference"); if (base instanceof COSArray) { COSArray refArray = (COSArray) base; for (int i = 0; i < refArray.size(); ++i) { base = refArray.getObject(i); if (base instanceof COSDictionary) { COSDictionary sigRefDict = (COSDictionary) base; if (COSName.DOCMDP.equals(sigRefDict.getDictionaryObject("TransformMethod"))) { base = sigRefDict.getDictionaryObject("TransformParams"); if (base instanceof COSDictionary) { COSDictionary transformDict = (COSDictionary) base; int accessPermissions = transformDict.getInt(COSName.P, 2); if (accessPermissions < 1 || accessPermissions > 3) { accessPermissions = 2; } return accessPermissions; } } } } } } } return 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 w ww . jav 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:fixture.pdfboxeg.CreateSignatureBase.java
License:Apache License
/** * Get the access permissions granted for this document in the DocMDP transform parameters * dictionary. Details are described in the table "Entries in the DocMDP transform parameters * dictionary" in the PDF specification. * * @param doc document./*from ww w .j a va 2s . c om*/ * @return the permission value. 0 means no DocMDP transform parameters dictionary exists. Other * return values are 1, 2 or 3. 2 is also returned if the DocMDP transform parameters dictionary * is found but did not contain a /P entry, or if the value is outside the valid range. */ public int getMDPPermission(PDDocument doc) { COSBase base = doc.getDocumentCatalog().getCOSObject().getDictionaryObject(COSName.PERMS); if (base instanceof COSDictionary) { COSDictionary permsDict = (COSDictionary) base; base = permsDict.getDictionaryObject(COSName.DOCMDP); if (base instanceof COSDictionary) { COSDictionary signatureDict = (COSDictionary) base; base = signatureDict.getDictionaryObject("Reference"); if (base instanceof COSArray) { COSArray refArray = (COSArray) base; for (int i = 0; i < refArray.size(); ++i) { base = refArray.getObject(i); if (base instanceof COSDictionary) { COSDictionary sigRefDict = (COSDictionary) base; if (COSName.DOCMDP.equals(sigRefDict.getDictionaryObject("TransformMethod"))) { base = sigRefDict.getDictionaryObject("TransformParams"); if (base instanceof COSDictionary) { COSDictionary transformDict = (COSDictionary) base; int accessPermissions = transformDict.getInt(COSName.P, 2); if (accessPermissions < 1 || accessPermissions > 3) { accessPermissions = 2; } return accessPermissions; } } } } } } } return 0; }
From source file:modules.PDFFontDependencyExtractorModule.java
License:Apache License
public PDFFontResults extractFontList(File f) throws IOException, InvalidParameterException { PDDocument document;//from www . ja v a 2 s .com 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>/*from ww w .java 2 s . co 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.actions.ActionManagerFactory.java
License:Apache License
/** * Returns all actions contained by the Next entry. If the action dictionary * doesn't have Next action, the result is an empty list. * /* w w w .ja va 2s .c om*/ * @param actionDictionary * the action dictionary which contains Next entry * @param cDoc * the COSDocument which contains actions. * @return * @throws ValidationException */ public final List<AbstractActionManager> getNextActions(COSDictionary actionDictionary, COSDocument cDoc) throws ValidationException { List<AbstractActionManager> result = new ArrayList<AbstractActionManager>(0); Map<COSObjectKey, Boolean> alreadyCreated = new HashMap<COSObjectKey, Boolean>(); COSBase nextDict = actionDictionary.getDictionaryObject(ACTION_DICTIONARY_KEY_NEXT); if (nextDict != null) { if (COSUtils.isArray(nextDict, cDoc)) { COSArray array = COSUtils.getAsArray(nextDict, cDoc); // ---- Next may contains an array of Action dictionary for (int i = 0; i < array.size(); ++i) { callCreateAction(array.get(i), cDoc, result, alreadyCreated); } } else { // ---- Next field contains a Dictionary or a reference to a Dictionary callCreateAction(nextDict, cDoc, result, alreadyCreated); } } return result; }
From source file:net.padaf.preflight.font.Type3FontValidator.java
License:Apache License
/** * This method check the Shading entry of the resource dictionary if exists. * // w w w .j a v a2s. c o m * @param result * @return * @throws ValidationException */ protected boolean validateShadingPattern(COSDictionary dictionary, List<ValidationError> result) throws ValidationException { boolean res = true; if (dictionary != null) { COSDictionary shadings = (COSDictionary) dictionary.getDictionaryObject(PATTERN_KEY_SHADING); if (shadings != null) { for (COSName key : shadings.keySet()) { COSDictionary aShading = (COSDictionary) shadings.getDictionaryObject(key); ShadingPattern sp = new ShadingPattern(handler, aShading); List<ValidationError> lErrors = sp.validate(); if (lErrors != null && !lErrors.isEmpty()) { result.addAll(lErrors); res = false; } } } } return res; }
From source file:net.padaf.preflight.graphics.XObjFormValidator.java
License:Apache License
/** * This method check the Shading entry of the resource dictionary if exists. * To process this validation, an instance of ShadinPattern is used. * // w w w . ja va 2 s. c om * @param result * the list of error to update if the validation fails * @return true if the validation succeed, false otherwise. * @throws ValidationException */ protected boolean validateShadingPattern(List<ValidationError> result) throws ValidationException { PDResources resources = this.pdXObj.getResources(); boolean res = true; if (resources != null) { COSDictionary shadings = (COSDictionary) resources.getCOSDictionary() .getDictionaryObject(PATTERN_KEY_SHADING); if (shadings != null) { for (Object key : shadings.keySet()) { COSDictionary aShading = (COSDictionary) shadings.getDictionaryObject((COSName) key); ShadingPattern sp = new ShadingPattern(handler, aShading); List<ValidationError> lErrors = sp.validate(); if (lErrors != null && !lErrors.isEmpty()) { result.addAll(lErrors); res = false; } } } } return res; }
From source file:net.padaf.preflight.helpers.PagesValidationHelper.java
License:Apache License
/** * This method check the Shading entry of the resource dictionary if exists. * //from www . j a v a2s. co m * @param page * @param handler * @param result * @return * @throws ValidationException */ protected boolean validateShadingPattern(PDPage page, DocumentHandler handler, List<ValidationError> result) throws ValidationException { PDResources resources = page.getResources(); COSDictionary shadings = (COSDictionary) resources.getCOSDictionary() .getDictionaryObject(PATTERN_KEY_SHADING); boolean res = true; if (shadings != null) { for (Object key : shadings.keySet()) { COSDictionary aShading = (COSDictionary) shadings.getDictionaryObject((COSName) key); ShadingPattern sp = new ShadingPattern(handler, aShading); List<ValidationError> lErrors = sp.validate(); if (lErrors != null && !lErrors.isEmpty()) { result.addAll(lErrors); res = false; } } } return res; }