Java源码示例:org.apache.pdfbox.cos.COSDictionary

示例1
/**
 * Returns this field's children. These may be either terminal or non-terminal fields.
 *
 * @return the list of child fields. Be aware that this list is <i>not</i> backed by the
 * children of the field, so adding or deleting has no effect on the PDF document until you call
 * {@link #setChildren(java.util.List) setChildren()} with the modified list.
 */
public List<PDField> getChildren()
{
    List<PDField> children = new ArrayList<PDField>();
    COSArray kids = (COSArray)getCOSObject().getDictionaryObject(COSName.KIDS);
    for (int i = 0; i < kids.size(); i++)
    {
        COSBase kid = kids.getObject(i);
        if (kid instanceof COSDictionary)
        {
            if (kid.getCOSObject() == this.getCOSObject())
            {
                LOG.warn("Child field is same object as parent");
                continue;
            }
            PDField field = PDField.fromDictionary(getAcroForm(), (COSDictionary) kid, this);
            if (field != null)
            {
                children.add(field);
            }
        }
    }
    return children;
}
 
示例2
/**
 * Update the P reference to the new parent dictionary.
 *
 * @param kArray the kids array
 * @param newParent the new parent
 */
private void updateParentEntry(COSArray kArray, COSDictionary newParent)
{
    for (int i = 0; i < kArray.size(); i++)
    {
        COSBase subEntry = kArray.getObject(i);
        if (subEntry instanceof COSDictionary)
        {
            COSDictionary dictEntry = (COSDictionary) subEntry;
            if (dictEntry.getDictionaryObject(COSName.P) != null)
            {
                dictEntry.setItem(COSName.P, newParent);
            }
        }
    }
}
 
示例3
private void transferDict(COSDictionary orgDict, COSDictionary targetDict,
        Set<String> filter, boolean inclusive) throws IOException
{
    for (Map.Entry<COSName, COSBase> entry : orgDict.entrySet())
    {
        COSName key = entry.getKey();
        if (inclusive && !filter.contains(key.getName()))
        {
            continue;
        }
        else if (!inclusive && filter.contains(key.getName()))
        {
            continue;
        }
        targetDict.setItem(key,
                cloner.cloneForNewDocument(entry.getValue()));
    }
}
 
示例4
@Override
protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters)
        throws IOException
{
    COSName encryptionName = (COSName) parameters.getDictionaryObject(COSName.NAME);
    if(encryptionName == null || encryptionName.equals(COSName.IDENTITY))
    {
        // currently the only supported implementation is the Identity crypt filter
        Filter identityFilter = new IdentityFilter();
        identityFilter.encode(input, encoded, parameters);
    }
    else
    {
        throw new IOException("Unsupported crypt filter " + encryptionName.getName());
    }
}
 
示例5
/**
 * Parse the values of the trailer dictionary and return the root object.
 *
 * @param trailer The trailer dictionary.
 * @return The parsed root object.
 * @throws IOException If an IO error occurs or if the root object is missing in the trailer dictionary.
 */
protected COSBase parseTrailerValuesDynamically(COSDictionary trailer) throws IOException
{
    // PDFBOX-1557 - ensure that all COSObject are loaded in the trailer
    // PDFBOX-1606 - after securityHandler has been instantiated
    for (COSBase trailerEntry : trailer.getValues())
    {
        if (trailerEntry instanceof COSObject)
        {
            COSObject tmpObj = (COSObject) trailerEntry;
            parseObjectDynamically(tmpObj, false);
        }
    }
    // parse catalog or root object
    COSObject root = trailer.getCOSObject(COSName.ROOT);
    if (root == null)
    {
        throw new IOException("Missing root object specification in trailer.");
    }
    return root.getObject();
}
 
示例6
/**
 * A file specfication can either be a COSString or a COSDictionary.  This
 * will create the file specification either way.
 *
 * @param base The cos object that describes the fs.
 *
 * @return The file specification for the COSBase object.
 *
 * @throws IOException If there is an error creating the file spec.
 */
public static PDFileSpecification createFS( COSBase base ) throws IOException
{
    PDFileSpecification retval = null;
    if( base == null )
    {
        //then simply return null
    }
    else if( base instanceof COSString )
    {
        retval = new PDSimpleFileSpecification( (COSString)base );
    }
    else if( base instanceof COSDictionary )
    {
        retval = new PDComplexFileSpecification( (COSDictionary)base );
    }
    else
    {
        throw new IOException( "Error: Unknown file specification " + base );
    }
    return retval;
}
 
示例7
/**
 * Update the Pg and Obj references to the new (merged) page.
 */
private void updatePageReferences(PDFCloneUtility cloner,
        Map<Integer, COSObjectable> numberTreeAsMap,
        Map<COSDictionary, COSDictionary> objMapping) throws IOException
{
    for (COSObjectable obj : numberTreeAsMap.values())
    {
        if (obj == null)
        {
            continue;
        }
        PDParentTreeValue val = (PDParentTreeValue) obj;
        COSBase base = val.getCOSObject();
        if (base instanceof COSArray)
        {
            updatePageReferences(cloner, (COSArray) base, objMapping);
        }
        else
        {
            updatePageReferences(cloner, (COSDictionary) base, objMapping);
        }
    }
}
 
示例8
private static PDField createButtonSubType(PDAcroForm form, COSDictionary field,
                                           PDNonTerminalField parent)
{
    int flags = field.getInt(COSName.FF, 0);
    // BJL: I have found that the radio flag bit is not always set
    // and that sometimes there is just a kids dictionary.
    // so, if there is a kids dictionary then it must be a radio button group.
    if ((flags & PDButton.FLAG_RADIO) != 0)
    {
        return new PDRadioButton(form, field, parent);
    }
    else if ((flags & PDButton.FLAG_PUSHBUTTON) != 0)
    {
        return new PDPushButton(form, field, parent);
    }
    else
    {
        return new PDCheckBox(form, field, parent);
    }
}
 
示例9
/**
 * <a href="http://stackoverflow.com/questions/36964496/pdfbox-2-0-overcoming-dictionary-key-encoding">
 * PDFBox 2.0: Overcoming dictionary key encoding
 * </a>
 * <br/>
 * <a href="http://www.stockholm.se/PageFiles/85478/KYF%20211%20Best%C3%A4llning%202014.pdf">
 * KYF 211 Best&auml;llning 2014.pdf
 * </a>
 * 
 * <p>
 * Indeed, the special characters in the names are replaced by the Unicode replacement
 * character. PDFBox, when parsing a PDF name, immediately interprets its bytes as UTF-8
 * encoded which fails in the document at hand.
 * </p>
 */
@Test
public void testReadFormOptions() throws IOException
{
    try (   InputStream originalStream = getClass().getResourceAsStream("KYF 211 Best\u00e4llning 2014.pdf") )
    {
        PDDocument pdfDocument = Loader.loadPDF(originalStream);
        PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
        
        PDField field = acroForm.getField("Krematorier");
        List<PDAnnotationWidget> widgets = field.getWidgets();
        System.out.println("Field Name: " + field.getPartialName() + " (" + widgets.size() + ")");
        for (PDAnnotationWidget annot : widgets) {
          PDAppearanceDictionary ap = annot.getAppearance();
          Set<COSName> keys = ((COSDictionary)(ap.getCOSObject().getDictionaryObject("N"))).keySet();
          ArrayList<String> keyList = new ArrayList<>(keys.size());
          for (COSName cosKey : keys) {keyList.add(cosKey.getName());}
          System.out.println(String.join("|", keyList));
        }
    }
}
 
示例10
/**
 * Insert a page before another page within a page tree.
 *
 * @param newPage the page to be inserted.
 * @param nextPage the page that is to be after the new page.
 * @throws IllegalArgumentException if one attempts to insert a page that isn't part of a page
 * tree.
 */
public void insertBefore(PDPage newPage, PDPage nextPage)
{
    COSDictionary nextPageDict = nextPage.getCOSObject();
    COSDictionary parentDict = (COSDictionary) nextPageDict.getDictionaryObject(COSName.PARENT);
    COSArray kids = (COSArray) parentDict.getDictionaryObject(COSName.KIDS);
    boolean found = false;
    for (int i = 0; i < kids.size(); ++i)
    {
        COSDictionary pageDict = (COSDictionary) kids.getObject(i);
        if (pageDict.equals(nextPage.getCOSObject()))
        {
            kids.add(i, newPage.getCOSObject());
            newPage.getCOSObject().setItem(COSName.PARENT, parentDict);
            found = true;
            break;
        }
    }
    if (!found)
    {
        throw new IllegalArgumentException("attempted to insert before orphan page");
    }
    increaseParents(parentDict);
}
 
示例11
/**
 * Creates a new TrueType font embedder for the given TTF as a PDTrueTypeFont.
 *
 * @param document The parent document
 * @param dict Font dictionary
 * @param ttfStream TTF stream
 * @param encoding The PostScript encoding vector to be used for embedding.
 * @throws IOException if the TTF could not be read
 */
PDTrueTypeFontEmbedder(PDDocument document, COSDictionary dict, TrueTypeFont ttf,
                       Encoding encoding) throws IOException
{
    super(document, dict, ttf, false);
    dict.setItem(COSName.SUBTYPE, COSName.TRUE_TYPE);
    
    GlyphList glyphList = GlyphList.getAdobeGlyphList();
    this.fontEncoding = encoding;
    dict.setItem(COSName.ENCODING, encoding.getCOSObject());
    fontDescriptor.setSymbolic(false);
    fontDescriptor.setNonSymbolic(true);
    
    // add the font descriptor
    dict.setItem(COSName.FONT_DESC, fontDescriptor);

    // set the glyph widths
    setWidths(dict, glyphList);
}
 
示例12
/**
 * (Optional; PDF 1.7) A list of maps, where each map contains key value pairs, that specify the
 * Subject Distinguished Name (DN) that must be present within the certificate for it to be
 * acceptable for signing. The certificate must at a minimum contain all the attributes
 * specified in one of the maps entered.
 *
 * @param subjectDN list of maps that contains subject distinguished names
 */
public void setSubjectDN(List<Map<String, String>> subjectDN)
{
    List<COSDictionary> subjectDNDict = new LinkedList<COSDictionary>();
    for (Map<String, String> subjectDNItem : subjectDN)
    {
        COSDictionary dict = new COSDictionary();
        for (Map.Entry<String, String> entry : subjectDNItem.entrySet())
        {
            dict.setItem(entry.getKey(), new COSString(entry.getValue()));
        }
        subjectDNDict.add(dict);
    }
    this.dictionary.setItem(COSName.SUBJECT_DN,
            COSArrayList.converterToCOSArray(subjectDNDict));
}
 
示例13
/**
 * This will get the list of FDF Pages. This will return a list of FDFPage objects.
 *
 * @return A list of FDF pages.
 */
public List<FDFPage> getPages()
{
    List<FDFPage> retval = null;
    COSArray pageArray = (COSArray) fdf.getDictionaryObject(COSName.PAGES);
    if (pageArray != null)
    {
        List<FDFPage> pages = new ArrayList<FDFPage>();
        for (int i = 0; i < pageArray.size(); i++)
        {
            pages.add(new FDFPage((COSDictionary) pageArray.get(i)));
        }
        retval = new COSArrayList<FDFPage>(pages, pageArray);
    }
    return retval;
}
 
示例14
/**
 * Generates the list of "PARAMETER" entries in the WKT.
 * 
 * @param projectionDictionary the GeoPDF projection dictionary
 * 
 * @returns string of WKT parameters
 */
private static String generateWKTParameters(COSDictionary projectionDictionary) throws IOException {
    // Set up the projection parameters
    Properties parameters = new Properties();

    COSDictionaryMap<String, Object> dictionaryMap = COSDictionaryMap.convertBasicTypesToMap(projectionDictionary);

    if (projectionDictionary.containsKey("CentralMeridian")) {
        parameters.put("Central_Meridian", (String) dictionaryMap.get("CentralMeridian"));
    }
    if (projectionDictionary.containsKey("OriginLatitude")) {
        parameters.put("Latitude_Of_Origin", (String) dictionaryMap.get("OriginLatitude"));
    }
    if (projectionDictionary.containsKey("StandardParallelOne")) {
        parameters.put("Standard_Parallel_1", (String) dictionaryMap.get("StandardParallelOne"));
    }
    if (projectionDictionary.containsKey("StandardParallelTwo")) {
        parameters.put("Standard_Parallel_2", (String) dictionaryMap.get("StandardParallelTwo"));
    }
    if (projectionDictionary.containsKey("FalseEasting")) {
        parameters.put("False_Easting", (String) dictionaryMap.get("FalseEasting"));
    }
    if (projectionDictionary.containsKey("FalseNorthing")) {
        parameters.put("False_Northing", (String) dictionaryMap.get("FalseNorthing"));
    }
    if (projectionDictionary.containsKey("ScaleFactor")) {
        parameters.put("Scale_Factor", (String) dictionaryMap.get("ScaleFactor"));
    }

    return parameters.entrySet().stream()
            .map(entry -> "PARAMETER[\"" + entry.getKey() + "\", " + entry.getValue() + "]")
            .collect(Collectors.joining(","));
}
 
示例15
/**
 * Returns the optional resources of the type3 stream.
 *
 * @return the resources bound to be used when parsing the type3 stream
 */
public PDResources getResources()
{
    if (resources == null)
    {
        COSBase base = dict.getDictionaryObject(COSName.RESOURCES);
        if (base instanceof COSDictionary)
        {
            this.resources = new PDResources((COSDictionary) base, resourceCache);
        }
    }
    return resources;
}
 
示例16
/**
 * Returns the resource names of the given kind.
 * 
 * @return the names of all resources of the given kind.
 */
private Iterable<COSName> getNames(COSName kind)
{
    COSDictionary dict = (COSDictionary)resources.getDictionaryObject(kind);
    if (dict == null)
    {
        return Collections.emptySet();
    }
    return dict.keySet();
}
 
示例17
/**
 * This will get named page references..
 *
 * @return The named page references.
 */
public FDFNamedPageReference getAppearanceStreamReference()
{
    FDFNamedPageReference retval = null;
    COSDictionary ref = (COSDictionary) field.getDictionaryObject(COSName.AP_REF);
    if (ref != null)
    {
        retval = new FDFNamedPageReference(ref);
    }
    return retval;
}
 
示例18
/**
 * Helper method for {@link #findComplexObjects(PDDocument)} -
 * the method adds the given reference to its targets entry in
 * the mapping, also adding the target to the set if there was
 * no mapping before for the target (i.e. the target object has
 * not been analyzed yet and is newly found in this pass).
 * 
 * @see #testOptimizeDummy()
 */
void addTarget(Reference reference, Map<COSBase, Collection<Reference>> incomingReferences, Set<COSBase> thisPass) {
    COSBase object = reference.getTo();
    if (object instanceof COSArray || object instanceof COSDictionary) {
        Collection<Reference> incoming = incomingReferences.get(object);
        if (incoming == null) {
            incoming = new ArrayList<>();
            incomingReferences.put(object, incoming);
            thisPass.add(object);
        }
        incoming.add(reference);
    }
}
 
示例19
/**
 * Creates a new TrueType font embedder for the given TTF as a PDCIDFontType2.
 *
 * @param document parent document
 * @param dict font dictionary
 * @param ttf True Type Font
 * @param parent parent Type 0 font
 * @throws IOException if the TTF could not be read
 */
PDCIDFontType2Embedder(PDDocument document, COSDictionary dict, TrueTypeFont ttf,
        boolean embedSubset, PDType0Font parent, boolean vertical) throws IOException
{
    super(document, dict, ttf, embedSubset);
    this.document = document;
    this.dict = dict;
    this.parent = parent;
    this.vertical = vertical;

    // parent Type 0 font
    dict.setItem(COSName.SUBTYPE, COSName.TYPE0);
    dict.setName(COSName.BASE_FONT, fontDescriptor.getFontName());
    dict.setItem(COSName.ENCODING, vertical ? COSName.IDENTITY_V : COSName.IDENTITY_H); // CID = GID

    // descendant CIDFont
    cidFont = createCIDFont();
    COSArray descendantFonts = new COSArray();
    descendantFonts.add(cidFont);
    dict.setItem(COSName.DESCENDANT_FONTS, descendantFonts);

    if (!embedSubset)
    {
        // build GID -> Unicode map
        buildToUnicodeCMap(null);
    }
}
 
示例20
/**
 * Returns the first trailer if at least one exists.
 * 
 * @return the first trailer or null
 */
public final COSDictionary getFirstTrailer() 
{
    if (bytePosToXrefMap.isEmpty())
    {
        return null;
    }
    Set<Long> offsets = bytePosToXrefMap.keySet();
    SortedSet<Long> sortedOffset = new TreeSet<Long>(offsets);
    return bytePosToXrefMap.get(sortedOffset.first()).trailer;
}
 
示例21
private BoundingBox generateBoundingBox()
{
    PDRectangle rect = getFontBBox();
    if (rect.getLowerLeftX() == 0 && rect.getLowerLeftY() == 0
            && rect.getUpperRightX() == 0 && rect.getUpperRightY() == 0)
    {
        // Plan B: get the max bounding box of the glyphs
        COSDictionary cp = getCharProcs();
        for (COSName name : cp.keySet())
        {
            COSBase base = cp.getDictionaryObject(name);
            if (base instanceof COSStream)
            {
                PDType3CharProc charProc = new PDType3CharProc(this, (COSStream) base);
                try
                {
                    PDRectangle glyphBBox = charProc.getGlyphBBox();
                    if (glyphBBox == null)
                    {
                        continue;
                    }
                    rect.setLowerLeftX(Math.min(rect.getLowerLeftX(), glyphBBox.getLowerLeftX()));
                    rect.setLowerLeftY(Math.min(rect.getLowerLeftY(), glyphBBox.getLowerLeftY()));
                    rect.setUpperRightX(Math.max(rect.getUpperRightX(), glyphBBox.getUpperRightX()));
                    rect.setUpperRightY(Math.max(rect.getUpperRightY(), glyphBBox.getUpperRightY()));
                }
                catch (IOException ex)
                {
                    // ignore
                }
            }
        }
    }
    return new BoundingBox(rect.getLowerLeftX(), rect.getLowerLeftY(),
            rect.getUpperRightX(), rect.getUpperRightY());
}
 
示例22
/**
 * Creates a user property with a given dictionary.
 * 
 * @param dictionary the dictionary
 * @param userAttributeObject the user attribute object
 */
public PDUserProperty(COSDictionary dictionary,
    PDUserAttributeObject userAttributeObject)
{
    super(dictionary);
    this.userAttributeObject = userAttributeObject;
}
 
示例23
@Override
public PdfDict getAsDict(String name) {
	COSDictionary dict = (COSDictionary) wrapped.getDictionaryObject(name);
	if (dict == null) {
		return null;
	}
	return new PdfBoxDict(dict, document);
}
 
示例24
/**
 * This will parse a PDF dictionary.
 *
 * @return The parsed dictionary, never null.
 *
 * @throws IOException If there is an error reading the stream.
 */
protected COSDictionary parseCOSDictionary() throws IOException
{
    readExpectedChar('<');
    readExpectedChar('<');
    skipSpaces();
    COSDictionary obj = new COSDictionary();
    boolean done = false;
    while (!done)
    {
        skipSpaces();
        char c = (char) seqSource.peek();
        if (c == '>')
        {
            done = true;
        }
        else if (c == '/')
        {
            parseCOSDictionaryNameValuePair(obj);
        }
        else
        {
            // invalid dictionary, we were expecting a /Name, read until the end or until we can recover
            LOG.warn("Invalid dictionary, found: '" + c + "' but expected: '/' at offset " + seqSource.getPosition());
            if (readUntilEndOfCOSDictionary())
            {
                // we couldn't recover
                return obj;
            }
        }
    }
    readExpectedChar('>');
    readExpectedChar('>');
    return obj;
}
 
示例25
private void assignSignatureRectangle(PDSignatureField signatureField, COSDictionary annotDict)
{
    // Read and set the rectangle for visual signature
    COSArray rectArray = (COSArray) annotDict.getDictionaryObject(COSName.RECT);
    PDRectangle rect = new PDRectangle(rectArray);
    PDRectangle existingRectangle = signatureField.getWidgets().get(0).getRectangle();

    //in case of an existing field keep the original rect
    if (existingRectangle == null || existingRectangle.getCOSArray().size() != 4)
    {
        signatureField.getWidgets().get(0).setRectangle(rect);
    }
}
 
示例26
/**
 * Constructor for Standard 14.
 */
PDFont(String baseFont)
{
    dict = new COSDictionary();
    dict.setItem(COSName.TYPE, COSName.FONT);
    toUnicodeCMap = null;
    afmStandard14 = Standard14Fonts.getAFM(baseFont);
    if (afmStandard14 == null)
    {
        throw new IllegalArgumentException("No AFM for font " + baseFont);
    }
    fontDescriptor = PDType1FontEmbedder.buildFontDescriptor(afmStandard14);
    // standard 14 fonts may be accessed concurrently, as they are singletons
    codeToWidthMap = new ConcurrentHashMap<Integer, Float>();
}
 
示例27
/**
 * This will get a JavaScript action to be performed in order to recalculate
 * the value of this field when that of another field changes. The order in which
 * the document's fields are recalculated is defined by the CO entry in the
 * interactive form dictionary.
 * The name C stands for "calculate".
 *
 * @return The C entry of form field's additional actions dictionary.
 */
public PDAction getC()
{
    COSDictionary c = (COSDictionary) actions.getDictionaryObject(COSName.C);
    PDAction retval = null;
    if( c != null )
    {
        retval = PDActionFactory.createAction( c );
    }
    return retval;
}
 
示例28
/**
 * Default constructor.
 */
public PDSeedValue()
{
    dictionary = new COSDictionary();
    dictionary.setItem(COSName.TYPE, COSName.SV);
    dictionary.setDirect(true); // the specification claim to use direct objects
}
 
示例29
/**
 * Constructor.
 *
 * @param doc The document that this form is part of.
 */
public PDAcroForm(PDDocument doc)
{
    document = doc;
    dictionary = new COSDictionary();
    dictionary.setItem(COSName.FIELDS, new COSArray());
}
 
示例30
/**
 * Returns the page at the given index.
 *
 * @param index zero-based index
 * 
 * @return the page at the given index.
 */
public PDPage get(int index)
{
    COSDictionary dict = get(index + 1, root, 0);

    sanitizeType(dict);

    ResourceCache resourceCache = document != null ? document.getResourceCache() : null;
    return new PDPage(dict, resourceCache);
}