Java Code Examples for org.apache.pdfbox.cos.COSDictionary#setItem()

The following examples show how to use org.apache.pdfbox.cos.COSDictionary#setItem() . 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: 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 2
Source File: PdfBoxSignatureService.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public DSSDocument addDssDictionary(DSSDocument document, List<DSSDictionaryCallback> callbacks, String pwd) {
	try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
			InputStream is = document.openStream();
			PDDocument pdDocument = PDDocument.load(is, pwd)) {

		if (Utils.isCollectionNotEmpty(callbacks)) {
			final COSDictionary cosDictionary = pdDocument.getDocumentCatalog().getCOSObject();
			cosDictionary.setItem(PAdESConstants.DSS_DICTIONARY_NAME, buildDSSDictionary(pdDocument, callbacks));
			cosDictionary.setNeedToBeUpdated(true);
		}
		
		// encryption is not required (no signature/timestamp is added on the step)
		saveDocumentIncrementally(pdDocument, baos);

		DSSDocument inMemoryDocument = new InMemoryDocument(baos.toByteArray());
		inMemoryDocument.setMimeType(MimeType.PDF);
		return inMemoryDocument;

	} catch (Exception e) {
		throw new DSSException(e);
	}
}
 
Example 3
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 4
Source File: COSDictionaryMap.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will take a map&lt;java.lang.String,org.apache.pdfbox.pdmodel.COSObjectable&gt;
 * and convert it into a COSDictionary.
 *
 * @param someMap A map containing COSObjectables
 *
 * @return A proper COSDictionary
 */
public static COSDictionary convert(Map<String, ?> someMap)
{
    COSDictionary dic = new COSDictionary();
    for (Entry<String, ?> entry : someMap.entrySet())
    {
        String name = entry.getKey();
        COSObjectable object = (COSObjectable) entry.getValue();
        dic.setItem( COSName.getPDFName( name ), object.getCOSObject() );
    }
    return dic;
}
 
Example 5
Source File: PDAppearanceDictionary.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Constructor for embedding.
 */
public PDAppearanceDictionary()
{
    dictionary = new COSDictionary();
    // the N entry is required.
    dictionary.setItem(COSName.N, new COSDictionary());
}
 
Example 6
Source File: PDFont.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Constructor for embedding.
 */
PDFont()
{
    dict = new COSDictionary();
    dict.setItem(COSName.TYPE, COSName.FONT);
    toUnicodeCMap = null;
    fontDescriptor = null;
    afmStandard14 = null;
    codeToWidthMap = new HashMap<Integer, Float>();
}
 
Example 7
Source File: PDFontFactory.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Create a default font.
 * 
 * @return a default font
 * @throws IOException if something goes wrong
 */
public static PDFont createDefaultFont() throws IOException
{
    COSDictionary dict = new COSDictionary();
    dict.setItem(COSName.TYPE, COSName.FONT);
    dict.setItem(COSName.SUBTYPE, COSName.TRUE_TYPE);
    dict.setString(COSName.BASE_FONT, "Arial");
    return createFont(dict);
}
 
Example 8
Source File: CreateSignature.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * A minimal signing frame work merely requiring a {@link SignatureInterface}
 * instance signing an existing field.
 * </p>
 * @see #testSignWithLocking()
 */
void signExistingFieldWithLock(PDDocument document, OutputStream output, SignatureInterface signatureInterface) throws IOException
{
    PDSignatureField signatureField = document.getSignatureFields().get(0);
    PDSignature signature = new PDSignature();
    signatureField.setValue(signature);

    COSBase lock = signatureField.getCOSObject().getDictionaryObject(COS_NAME_LOCK);
    if (lock instanceof COSDictionary)
    {
        COSDictionary lockDict = (COSDictionary) lock;
        COSDictionary transformParams = new COSDictionary(lockDict);
        transformParams.setItem(COSName.TYPE, COSName.getPDFName("TransformParams"));
        transformParams.setItem(COSName.V, COSName.getPDFName("1.2"));
        transformParams.setDirect(true);
        COSDictionary sigRef = new COSDictionary();
        sigRef.setItem(COSName.TYPE, COSName.getPDFName("SigRef"));
        sigRef.setItem(COSName.getPDFName("TransformParams"), transformParams);
        sigRef.setItem(COSName.getPDFName("TransformMethod"), COSName.getPDFName("FieldMDP"));
        sigRef.setItem(COSName.getPDFName("Data"), document.getDocumentCatalog());
        sigRef.setDirect(true);
        COSArray referenceArray = new COSArray();
        referenceArray.add(sigRef);
        signature.getCOSObject().setItem(COSName.getPDFName("Reference"), referenceArray);
    }

    signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
    signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
    signature.setName("blablabla");
    signature.setLocation("blablabla");
    signature.setReason("blablabla");
    signature.setSignDate(Calendar.getInstance());
    document.addSignature(signature);
    ExternalSigningSupport externalSigning =
            document.saveIncrementalForExternalSigning(output);
    // invoke external signature service
    byte[] cmsSignature = signatureInterface.sign(externalSigning.getContent());
    // set signature bytes received from the service
    externalSigning.setSignature(cmsSignature);
}
 
Example 9
Source File: PdfBoxSignatureService.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Set 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               The document.
 * @param signature         The signature object.
 * @param accessPermissions The permission value (1, 2 or 3).
 */
public void setMDPPermission(PDDocument doc, PDSignature signature, int accessPermissions) {
	COSDictionary sigDict = signature.getCOSObject();

	// DocMDP specific stuff
	COSDictionary transformParameters = new COSDictionary();
	transformParameters.setItem(COSName.TYPE, COSName.getPDFName("TransformParams"));
	transformParameters.setInt(COSName.P, accessPermissions);
	transformParameters.setName(COSName.V, "1.2");
	transformParameters.setNeedToBeUpdated(true);

	COSDictionary referenceDict = new COSDictionary();
	referenceDict.setItem(COSName.TYPE, COSName.getPDFName("SigRef"));
	referenceDict.setItem("TransformMethod", COSName.DOCMDP);
	referenceDict.setItem("TransformParams", transformParameters);
	referenceDict.setNeedToBeUpdated(true);

	COSArray referenceArray = new COSArray();
	referenceArray.add(referenceDict);
	sigDict.setItem("Reference", referenceArray);
	referenceArray.setNeedToBeUpdated(true);

	// Document Catalog
	COSDictionary catalogDict = doc.getDocumentCatalog().getCOSObject();
	COSDictionary permsDict = new COSDictionary();
	catalogDict.setItem(COSName.PERMS, permsDict);
	permsDict.setItem(COSName.DOCMDP, signature);
	catalogDict.setNeedToBeUpdated(true);
	permsDict.setNeedToBeUpdated(true);
}
 
Example 10
Source File: NPEfix17_seventeen_t.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 11
Source File: PDAcroForm.java    From gcs with Mozilla Public License 2.0 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 12
Source File: PDFMergerUtility.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private void mergeRoleMap(PDStructureTreeRoot srcStructTree, PDStructureTreeRoot destStructTree)
{
    COSDictionary srcDict = srcStructTree.getCOSObject().getCOSDictionary(COSName.ROLE_MAP);
    COSDictionary destDict = destStructTree.getCOSObject().getCOSDictionary(COSName.ROLE_MAP);
    if (srcDict == null)
    {
        return;
    }
    if (destDict == null)
    {
        destStructTree.getCOSObject().setItem(COSName.ROLE_MAP, srcDict); // clone not needed
        return;
    }
    for (Map.Entry<COSName, COSBase> entry : srcDict.entrySet())
    {
        COSBase destValue = destDict.getDictionaryObject(entry.getKey());
        if (destValue != null && destValue.equals(entry.getValue()))
        {
            // already exists, but identical
            continue;
        }
        if (destDict.containsKey(entry.getKey()))
        {
            LOG.warn("key " + entry.getKey() + " already exists in destination RoleMap");
        }
        else
        {
            destDict.setItem(entry.getKey(), entry.getValue());
        }
    }
}
 
Example 13
Source File: NPEfix18_eigthteen_t.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 14
Source File: PDCIDFontType2Embedder.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private COSDictionary createCIDFont() throws IOException
{
    COSDictionary cidFont = new COSDictionary();

    // Type, Subtype
    cidFont.setItem(COSName.TYPE, COSName.FONT);
    cidFont.setItem(COSName.SUBTYPE, COSName.CID_FONT_TYPE2);

    // BaseFont
    cidFont.setName(COSName.BASE_FONT, fontDescriptor.getFontName());

    // CIDSystemInfo
    COSDictionary info = toCIDSystemInfo("Adobe", "Identity", 0);
    cidFont.setItem(COSName.CIDSYSTEMINFO, info);

    // FontDescriptor
    cidFont.setItem(COSName.FONT_DESC, fontDescriptor.getCOSObject());

    // W - widths
    buildWidths(cidFont);

    // Vertical metrics
    if (vertical)
    {
        buildVerticalMetrics(cidFont);
    }

    // CIDToGIDMap
    cidFont.setItem(COSName.CID_TO_GID_MAP, COSName.IDENTITY);

    return cidFont;
}
 
Example 15
Source File: PDAnnotation.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Constructor.
 */
public PDAnnotation()
{
    dictionary = new COSDictionary();
    dictionary.setItem(COSName.TYPE, COSName.ANNOT);
}
 
Example 16
Source File: FDFAnnotationStamp.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * This will create an Appearance dictionary from an appearance XML document.
 *
 * @param fdfXML The XML document that contains the appearance data.
 */
private COSDictionary parseStampAnnotationAppearanceXML(Element appearanceXML) throws IOException
{
    COSDictionary dictionary = new COSDictionary();
    // the N entry is required.
    dictionary.setItem(COSName.N, new COSStream());
    LOG.debug("Build dictionary for Appearance based on the appearanceXML");

    NodeList nodeList = appearanceXML.getChildNodes();
    String parentAttrKey = appearanceXML.getAttribute("KEY");
    LOG.debug("Appearance Root - tag: " + appearanceXML.getTagName() + ", name: " + 
            appearanceXML.getNodeName() + ", key: " + parentAttrKey + ", children: " + 
            nodeList.getLength());

    // Currently only handles Appearance dictionary (AP key on the root)
    if (!"AP".equals(appearanceXML.getAttribute("KEY")))
    {
        LOG.warn(parentAttrKey + " => Not handling element: " + appearanceXML.getTagName() + 
                                 " with key: " + appearanceXML.getAttribute("KEY"));
        return dictionary;
    }
    for (int i = 0; i < nodeList.getLength(); i++)
    {
        Node node = nodeList.item(i);
        if (node instanceof Element)
        {
            Element child = (Element) node;
            if ("STREAM".equalsIgnoreCase(child.getTagName()))
            {
                LOG.debug(parentAttrKey +
                        " => Process " + child.getAttribute("KEY") + 
                        " item in the dictionary after processing the " + 
                        child.getTagName());
                dictionary.setItem(child.getAttribute("KEY"), parseStreamElement(child));
                LOG.debug(parentAttrKey + " => Set " + child.getAttribute("KEY"));
            }
            else
            {
                LOG.warn(parentAttrKey + " => Not handling element: " + child.getTagName());
            }
        }
    }
    return dictionary;
}
 
Example 17
Source File: PDOptionalContentProperties.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Sets the base state for optional content groups.
 * @param state the base state
 */
public void setBaseState(BaseState state)
{
    COSDictionary d = getD();
    d.setItem(COSName.BASE_STATE, state.getName());
}
 
Example 18
Source File: PDExtendedGraphicsState.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Default constructor, creates blank graphics state.
 */
public PDExtendedGraphicsState()
{
    dict = new COSDictionary();
    dict.setItem(COSName.TYPE, COSName.EXT_G_STATE);
}
 
Example 19
Source File: CreateSignature.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * A minimal signing frame work merely requiring a {@link SignatureInterface}
 * instance signing an existing field and actually locking fields the transform
 * requires to be locked.
 * </p>
 * @see #signExistingFieldWithLock(PDDocument, OutputStream, SignatureInterface)
 */
void signAndLockExistingFieldWithLock(PDDocument document, OutputStream output, SignatureInterface signatureInterface) throws IOException
{
    PDSignatureField signatureField = document.getSignatureFields().get(0);
    PDSignature signature = new PDSignature();
    signatureField.setValue(signature);

    COSBase lock = signatureField.getCOSObject().getDictionaryObject(COS_NAME_LOCK);
    if (lock instanceof COSDictionary)
    {
        COSDictionary lockDict = (COSDictionary) lock;
        COSDictionary transformParams = new COSDictionary(lockDict);
        transformParams.setItem(COSName.TYPE, COSName.getPDFName("TransformParams"));
        transformParams.setItem(COSName.V, COSName.getPDFName("1.2"));
        transformParams.setDirect(true);
        COSDictionary sigRef = new COSDictionary();
        sigRef.setItem(COSName.TYPE, COSName.getPDFName("SigRef"));
        sigRef.setItem(COSName.getPDFName("TransformParams"), transformParams);
        sigRef.setItem(COSName.getPDFName("TransformMethod"), COSName.getPDFName("FieldMDP"));
        sigRef.setItem(COSName.getPDFName("Data"), document.getDocumentCatalog());
        sigRef.setDirect(true);
        COSArray referenceArray = new COSArray();
        referenceArray.add(sigRef);
        signature.getCOSObject().setItem(COSName.getPDFName("Reference"), referenceArray);

        final Predicate<PDField> shallBeLocked;
        final COSArray fields = lockDict.getCOSArray(COSName.FIELDS);
        final List<String> fieldNames = fields == null ? Collections.emptyList() :
            fields.toList().stream().filter(c -> (c instanceof COSString)).map(s -> ((COSString)s).getString()).collect(Collectors.toList());
        final COSName action = lockDict.getCOSName(COSName.getPDFName("Action"));
        if (action.equals(COSName.getPDFName("Include"))) {
            shallBeLocked = f -> fieldNames.contains(f.getFullyQualifiedName());
        } else if (action.equals(COSName.getPDFName("Exclude"))) {
            shallBeLocked = f -> !fieldNames.contains(f.getFullyQualifiedName());
        } else if (action.equals(COSName.getPDFName("All"))) {
            shallBeLocked = f -> true;
        } else { // unknown action, lock nothing
            shallBeLocked = f -> false;
        }
        lockFields(document.getDocumentCatalog().getAcroForm().getFields(), shallBeLocked);
    }

    signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
    signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
    signature.setName("blablabla");
    signature.setLocation("blablabla");
    signature.setReason("blablabla");
    signature.setSignDate(Calendar.getInstance());
    document.addSignature(signature);
    ExternalSigningSupport externalSigning =
            document.saveIncrementalForExternalSigning(output);
    // invoke external signature service
    byte[] cmsSignature = signatureInterface.sign(externalSigning.getContent());
    // set signature bytes received from the service
    externalSigning.setSignature(cmsSignature);
}
 
Example 20
Source File: PDFontDescriptor.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Package-private constructor, for embedding.
 */
PDFontDescriptor()
{
    dic = new COSDictionary();
    dic.setItem( COSName.TYPE, COSName.FONT_DESC );
}