org.apache.pdfbox.cos.COSDictionary Java Examples

The following examples show how to use org.apache.pdfbox.cos.COSDictionary. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PDNonTerminalField.java    From gcs with Mozilla Public License 2.0 7 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: FDFDictionary.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: COSParser.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #4
Source File: CryptFilter.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
@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());
    }
}
 
Example #5
Source File: PDFileSpecification.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #6
Source File: LayerUtility.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
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()));
    }
}
 
Example #7
Source File: PDFMergerUtility.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #8
Source File: PDFieldFactory.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #9
Source File: PDSeedValueCertificate.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * (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));
}
 
Example #10
Source File: PDTrueTypeFontEmbedder.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #11
Source File: ReadForm.java    From testarea-pdfbox2 with Apache License 2.0 6 votes vote down vote up
/**
 * <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));
        }
    }
}
 
Example #12
Source File: PDPageTree.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #13
Source File: PDFMergerUtility.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * 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);
            }
        }
    }
}
 
Example #14
Source File: PDDocumentCatalog.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Constructor. Internal PDFBox use only! If you need to get the document catalog, call
 * {@link PDDocument#getDocumentCatalog()}.
 *
 * @param doc The document that this catalog is part of.
 */
public PDDocumentCatalog(PDDocument doc)
{
    document = doc;
    root = new COSDictionary();
    root.setItem(COSName.TYPE, COSName.CATALOG);
    document.getDocument().getTrailer().setItem(COSName.ROOT, root);
}
 
Example #15
Source File: PDResources.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #16
Source File: FDFField.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #17
Source File: PDFormFieldAdditionalActions.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will get a JavaScript action to be performed
 * when the field's value is changed. This allows the
 * new value to be checked for validity.
 * The name V stands for "validate".
 *
 * @return The V entry of form field's additional actions dictionary.
 */
public PDAction getV()
{
    COSDictionary v = (COSDictionary) actions.getDictionaryObject(COSName.V);
    PDAction retval = null;
    if( v != null )
    {
        retval = PDActionFactory.createAction( v );
    }
    return retval;
}
 
Example #18
Source File: PDCIEDictionaryBasedColorSpace.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a new CalRGB color space using the given COS array.
 *
 * @param rgb the cos array which represents this color space
 */
protected PDCIEDictionaryBasedColorSpace(COSArray rgb)
{
    array = rgb;
    dictionary = (COSDictionary) array.getObject(1);

    fillWhitepointCache(getWhitepoint());
}
 
Example #19
Source File: PDType3Font.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #20
Source File: NPEfix17_seventeen_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * 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());
}
 
Example #21
Source File: OptimizeAfterMerge.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example #22
Source File: XrefTrailerResolver.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #23
Source File: PDType3Font.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
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());
}
 
Example #24
Source File: PDUserProperty.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #25
Source File: PdfBoxDict.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public PdfDict getAsDict(String name) {
	COSDictionary dict = (COSDictionary) wrapped.getDictionaryObject(name);
	if (dict == null) {
		return null;
	}
	return new PdfBoxDict(dict, document);
}
 
Example #26
Source File: BaseParser.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #27
Source File: PDSeedValue.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Default constructor.
 */
public PDSeedValue()
{
    dictionary = new COSDictionary();
    dictionary.setItem(COSName.TYPE, COSName.SV);
    dictionary.setDirect(true); // the specification claim to use direct objects
}
 
Example #28
Source File: PDDocument.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #29
Source File: PDFormFieldAdditionalActions.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #30
Source File: PDFont.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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>();
}