Example usage for org.apache.pdfbox.cos COSDictionary setItem

List of usage examples for org.apache.pdfbox.cos COSDictionary setItem

Introduction

In this page you can find the example usage for org.apache.pdfbox.cos COSDictionary setItem.

Prototype

public void setItem(String key, COSBase value) 

Source Link

Document

This will set an item in the dictionary.

Usage

From source file:org.apache.fop.render.pdf.DocumentRootModifierTestCase.java

License:Apache License

@Test
public void testStructTreeRootEntriesToCopy() throws IOException {
    Rectangle2D r = new Rectangle2D.Double();
    PDFDocument pdfDoc = new PDFDocument("");
    PDFPage page = new PDFPage(new PDFResources(pdfDoc), 0, r, r, r, r);
    page.setObjectNumber(1);//from ww w .  ja v  a2 s . c o m
    page.setDocument(pdfDoc);
    pdfDoc.makeStructTreeRoot(null);
    PDFStructTreeRoot structTreeRoot = pdfDoc.getRoot().getStructTreeRoot();
    PDFDictionary rootBaseRoleMap = new PDFDictionary();
    PDFBoxAdapter adapter = new PDFBoxAdapter(page, new HashMap(), new HashMap<Integer, PDFArray>());
    DocumentRootModifier modifier = new DocumentRootModifier(adapter, pdfDoc);
    COSDictionary root = new COSDictionary();
    COSDictionary mapRole = new COSDictionary();
    mapRole.setName("Icon", "Figure");
    root.setItem(COSName.ROLE_MAP, mapRole);
    modifier.structTreeRootEntriesToCopy(root);
    structTreeRoot = pdfDoc.getRoot().getStructTreeRoot();
    PDFDictionary baseRoot = (PDFDictionary) structTreeRoot.get("RoleMap");
    String test = baseRoot.get("Icon").toString();
    String expected = "/Figure";
    Assert.assertEquals(test, expected);

    PDFName para = new PDFName("P");
    rootBaseRoleMap.put("MyPara", para);
    structTreeRoot.put("RoleMap", rootBaseRoleMap);
    modifier.structTreeRootEntriesToCopy(root);
    structTreeRoot = pdfDoc.getRoot().getStructTreeRoot();
    PDFDictionary baseRoot2 = (PDFDictionary) structTreeRoot.get("RoleMap");
    PDFName nameIcon = (PDFName) baseRoot2.get("Icon");
    PDFName myPara = (PDFName) baseRoot2.get("MyPara");
    test = nameIcon.getName();
    expected = "Figure";
    Assert.assertEquals(test, expected);
    test = myPara.getName();
    expected = "P";
    Assert.assertEquals(test, expected);

    PDDocument doc = PDDocument.load(new File(getClass().getResource(CLASSMAP).getFile()));
    COSDictionary temp = (COSDictionary) doc.getDocumentCatalog().getStructureTreeRoot().getCOSObject();
    PDFDictionary classMap = new PDFDictionary();
    PDFDictionary inner = new PDFDictionary();
    inner.put("StartIndent", 0);
    classMap.put("Normal2", inner);
    structTreeRoot.put("ClassMap", classMap);
    modifier.structTreeRootEntriesToCopy(temp);
    structTreeRoot = pdfDoc.getRoot().getStructTreeRoot();
    PDFDictionary testDict = (PDFDictionary) structTreeRoot.get("ClassMap");
    Assert.assertNotNull(testDict.get("Normal2"));
}

From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java

License:Apache License

private void mergeXObj(COSDictionary sourcePageResources, FontInfo fontinfo, UniqueName uniqueName)
        throws IOException {
    COSDictionary xobj = (COSDictionary) sourcePageResources.getDictionaryObject(COSName.XOBJECT);
    if (xobj != null && pdfDoc.isMergeFontsEnabled()) {
        for (Map.Entry<COSName, COSBase> i : xobj.entrySet()) {
            COSObject v = (COSObject) i.getValue();
            COSStream stream = (COSStream) v.getObject();
            COSDictionary res = (COSDictionary) stream.getDictionaryObject(COSName.RESOURCES);
            if (res != null) {
                COSDictionary src = (COSDictionary) res.getDictionaryObject(COSName.FONT);
                if (src != null) {
                    COSDictionary target = (COSDictionary) sourcePageResources
                            .getDictionaryObject(COSName.FONT);
                    if (target == null) {
                        sourcePageResources.setItem(COSName.FONT, src);
                    } else {
                        for (Map.Entry<COSName, COSBase> entry : src.entrySet()) {
                            if (!target.keySet().contains(entry.getKey())) {
                                target.setItem(uniqueName.getName(entry.getKey()), entry.getValue());
                            }/*from w  ww.j a v  a2 s .c  o  m*/
                        }
                    }
                    PDFWriter writer = new MergeFontsPDFWriter(src, fontinfo, uniqueName, parentFonts, 0);
                    String c = writer.writeText(new PDStream(stream));
                    if (c != null) {
                        stream.removeItem(COSName.FILTER);
                        newXObj.put(i.getKey(), c);
                        for (Object e : src.keySet().toArray()) {
                            COSName name = (COSName) e;
                            src.setItem(uniqueName.getName(name), src.getItem(name));
                            src.removeItem(name);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.apache.fop.render.pdf.StructureTreeMergerTestCase.java

License:Apache License

@Test
public void testCheckNullCOSObject() throws IOException {
    setUp();//w ww . j av  a 2 s .  com
    PDDocument doc = PDDocument.load(new File(getClass().getResource(BrokenLink).getFile()));
    PDPage srcPage = doc.getPage(0);
    PageParentTreeFinder finder = new PageParentTreeFinder(srcPage);
    COSArray markedContentParents = finder.getPageParentTreeArray(doc);
    COSObject nullObj = new COSObject(null);
    nullObj.setObjectNumber(100);
    nullObj.setGenerationNumber(0);
    PDFStructElem elem = new PDFStructElem();
    elem.setObjectNumber(2);
    COSObject parent = (COSObject) markedContentParents.get(1);
    COSArray kids = (COSArray) parent.getDictionaryObject(COSName.K);
    COSDictionary kid = (COSDictionary) kids.get(1);
    kid.setItem(COSName.OBJ, nullObj);
    adapter = new PDFBoxAdapter(pdfPage, new HashMap(), new HashMap<Integer, PDFArray>());
    PDFLogicalStructureHandler handler = setUpPDFLogicalStructureHandler();
    StructureTreeMerger merger = new StructureTreeMerger(elem, handler, adapter, srcPage);
    merger.copyStructure(markedContentParents);
    PDFArray array = handler.getPageParentTree();
    PDFStructElem parentElem = (PDFStructElem) array.get(1);
    PDFDictionary objrDict = (PDFDictionary) parentElem.getKids().get(1);
    Assert.assertNull(objrDict.get("Obj"));
}

From source file:org.apache.fop.render.pdf.StructureTreeMergerTestCase.java

License:Apache License

@Test
public void testDirectDescedants() throws IOException {
    PDFStructElem elem = new PDFStructElem();
    elem.setObjectNumber(100);//from  w w w .  j ava2s . com
    setUp();
    adapter = new PDFBoxAdapter(pdfPage, new HashMap(), new HashMap<Integer, PDFArray>());
    PDFLogicalStructureHandler handler = setUpPDFLogicalStructureHandler();
    PDPage srcPage = new PDPage();
    StructureTreeMerger merger = new StructureTreeMerger(elem, handler, adapter, srcPage);
    COSArray array = new COSArray();
    COSDictionary dict = new COSDictionary();
    dict.setItem(COSName.S, COSName.P);
    COSObject obj = new COSObject(dict);
    obj.setObjectNumber(200);
    obj.setGenerationNumber(0);
    array.add(0, obj);
    merger.createDirectDescendants(array, elem);
    List<PDFObject> list = elem.getKids();
    PDFStructElem kid = (PDFStructElem) list.get(0);
    PDFName name = (PDFName) kid.get("S");
    String test = name.getName();
    Assert.assertEquals(test, "P");
}

From source file:org.apache.fop.render.pdf.StructureTreeMergerUtilTestCase.java

License:Apache License

@Test
public void testFindRoleMapKeyByValue() {

    COSDictionary rolemap = new COSDictionary();
    COSName key1 = COSName.getPDFName("Para");
    COSName value1 = COSName.getPDFName("P");
    COSName key2 = COSName.getPDFName("Icon");
    COSName value2 = COSName.getPDFName("Image");
    rolemap.setItem(key1, value1);
    rolemap.setItem(key2, value2);//from  w w  w  .  j a  v a2s.  c  o  m
    String type = "Image";
    List<String> result = StructureTreeMergerUtil.findRoleMapKeyByValue(type, rolemap);
    String test = result.get(0);
    String expected = "Icon";
    Assert.assertEquals(test, expected);
}

From source file:org.lockss.pdf.pdfbox.PdfBoxTokens.java

License:Open Source License

/**
 * <p>//w w  w .  j a va 2s  . c om
 * Converts from a map from strings to PDF tokens to a 
 * {@link COSDictionary}.
 * </p>
 * @param mapping A map from strings (PDF names) to PDF tokens.
 * @return A {@link COSDictionary} instance.
 * @since 1.56
 */
protected static COSDictionary asCOSDictionary(Map<String, PdfToken> mapping) {
    COSDictionary cosDictionary = new COSDictionary();
    for (Map.Entry<String, PdfToken> entry : mapping.entrySet()) {
        cosDictionary.setItem(asCOSName(entry.getKey()), asCOSBase(entry.getValue()));
    }
    return cosDictionary;
}

From source file:org.mustangproject.ZUGFeRD.ZUGFeRDExporter.java

License:Open Source License

/**
 * Embeds an external file (generic - any type allowed) in the PDF.
 *
 * @param doc          PDDocument to attach the file to.
 * @param filename     name of the file that will become attachment name in the PDF
 * @param relationship how the file relates to the content, e.g. "Alternative"
 * @param description  Human-readable description of the file content
 * @param subType      type of the data e.g. could be "text/xml" - mime like
 * @param data         the binary data of the file/attachment
 * @throws java.io.IOException//from   www  .  j a va 2 s . c  om
 */
public void PDFAttachGenericFile(PDDocument doc, String filename, String relationship, String description,
        String subType, byte[] data) throws IOException {
    fileAttached = true;

    PDComplexFileSpecification fs = new PDComplexFileSpecification();
    fs.setFile(filename);

    COSDictionary dict = fs.getCOSObject();
    dict.setName("AFRelationship", relationship);
    dict.setString("UF", filename);
    dict.setString("Desc", description);

    ByteArrayInputStream fakeFile = new ByteArrayInputStream(data);
    PDEmbeddedFile ef = new PDEmbeddedFile(doc, fakeFile);
    ef.setSubtype(subType);
    ef.setSize(data.length);
    ef.setCreationDate(new GregorianCalendar());

    ef.setModDate(GregorianCalendar.getInstance());

    fs.setEmbeddedFile(ef);

    // In addition make sure the embedded file is set under /UF
    dict = fs.getCOSObject();
    COSDictionary efDict = (COSDictionary) dict.getDictionaryObject(COSName.EF);
    COSBase lowerLevelFile = efDict.getItem(COSName.F);
    efDict.setItem(COSName.UF, lowerLevelFile);

    // now add the entry to the embedded file tree and set in the document.
    PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
    PDEmbeddedFilesNameTreeNode efTree = names.getEmbeddedFiles();
    if (efTree == null) {
        efTree = new PDEmbeddedFilesNameTreeNode();
    }

    Map<String, PDComplexFileSpecification> namesMap = new HashMap<>();

    Map<String, PDComplexFileSpecification> oldNamesMap = efTree.getNames();
    if (oldNamesMap != null) {
        for (String key : oldNamesMap.keySet()) {
            namesMap.put(key, oldNamesMap.get(key));
        }
    }
    namesMap.put(filename, fs);
    efTree.setNames(namesMap);

    names.setEmbeddedFiles(efTree);
    doc.getDocumentCatalog().setNames(names);

    // AF entry (Array) in catalog with the FileSpec
    COSArray cosArray = (COSArray) doc.getDocumentCatalog().getCOSObject().getItem("AF");
    if (cosArray == null) {
        cosArray = new COSArray();
    }
    cosArray.add(fs);
    COSDictionary dict2 = doc.getDocumentCatalog().getCOSObject();
    COSArray array = new COSArray();
    array.add(fs.getCOSObject()); // see below
    dict2.setItem("AF", array);
    doc.getDocumentCatalog().getCOSObject().setItem("AF", cosArray);
}

From source file:pdfpicmangler.PDPng.java

License:Open Source License

/**
 * Construct from a stream.//from  ww w.j a  va2s.  co  m
 * 
 * @param doc The document to create the image as part of.
 * @param is The stream that contains the png data.
 * @throws IOException If there is an error reading the png data.
 */
public PDPng(PDDocument doc, InputStream is) throws IOException {
    super(doc, "png");

    System.out.println("reading in png");

    COSDictionary dic = getCOSStream();

    dic.setItem(COSName.SUBTYPE, COSName.IMAGE);
    //dic.setItem(COSName.TYPE, COSName.XOBJECT);

    data = getCOSStream().createFilteredStream();

    readPng(is);

    setWidth(imageWidth);
    setHeight(imageHeight);
    dic.setInt(COSName.BITS_PER_COMPONENT, bitDepth);

    if ((colorType & PNG_TYPE_PALETTE) != 0) {
        getCOSStream().setItem(COSName.COLORSPACE, paldata);
    } else if ((colorType & PNG_TYPE_COLOR) != 0) {
        setColorSpace(PDDeviceRGB.INSTANCE);
    } else {
        setColorSpace(new PDDeviceGray());
    }

    COSDictionary filterParams = new COSDictionary();
    filterParams.setInt(COSName.PREDICTOR, 15); // png adaptive predictor
    filterParams.setInt(COSName.COLORS,
            ((colorType & PNG_TYPE_COLOR) == 0 || (colorType & PNG_TYPE_PALETTE) != 0) ? 1 : 3);
    filterParams.setInt(COSName.BITS_PER_COMPONENT, bitDepth);
    filterParams.setInt(COSName.COLUMNS, imageWidth);
    filterParams.setDirect(true);

    dic.setItem(COSName.DECODE_PARMS, filterParams);
    dic.setItem(COSName.FILTER, COSName.FLATE_DECODE);

    dic.setInt(COSName.LENGTH, dataLen);
    dic.getDictionaryObject(COSName.LENGTH).setDirect(true);
}

From source file:se.streamsource.streamflow.web.application.pdf.Underlay.java

License:Apache License

private void processPages(List pages) throws IOException {
    Iterator pageIter = pages.iterator();
    while (pageIter.hasNext()) {
        PDPage page = (PDPage) pageIter.next();
        COSDictionary pageDictionary = page.getCOSDictionary();
        COSBase contents = pageDictionary.getDictionaryObject(COSName.CONTENTS);
        if (contents instanceof COSStreamArray) {
            COSStreamArray cosStreamArray = (COSStreamArray) contents;
            COSArray array = new COSArray();
            for (int i = 0; i < cosStreamArray.getStreamCount(); i++) {
                array.add(cosStreamArray.get(i));
            }/*  w w  w . j  a v a2  s . c  o m*/
            mergePage(array, page);
            pageDictionary.setItem(COSName.CONTENTS, array);
        } else if (contents instanceof COSStream) {
            COSStream contentsStream = (COSStream) contents;

            COSArray array = new COSArray();

            array.add(contentsStream);

            mergePage(array, page);

            pageDictionary.setItem(COSName.CONTENTS, array);
        } else if (contents instanceof COSArray) {
            COSArray contentsArray = (COSArray) contents;

            mergePage(contentsArray, page);
        } else {
            throw new IOException("Contents are unknown type:" + contents.getClass().getName());
        }
        pageCount++;
    }
}

From source file:se.streamsource.streamflow.web.application.pdf.Underlay.java

License:Apache License

/**
 * merges two dictionaries./*from  w w w.  ja va  2 s  . com*/
 *
 * @param dest
 * @param source
 */
private void mergeDictionary(COSName name, COSDictionary dest, COSDictionary source, Map objectNameMap) {
    COSDictionary destDict = (COSDictionary) dest.getDictionaryObject(name);
    COSDictionary sourceDict = (COSDictionary) source.getDictionaryObject(name);

    if (destDict == null) {
        destDict = new COSDictionary();
        dest.setItem(name, destDict);
    }
    if (sourceDict != null) {

        for (Map.Entry<COSName, COSBase> entry : sourceDict.entrySet()) {
            COSName mappedKey = (COSName) objectNameMap.get(entry.getKey().getName());
            if (mappedKey != null) {
                destDict.setItem(mappedKey, entry.getValue());
            }
        }
    }
}