Java Code Examples for org.apache.pdfbox.cos.COSArray#add()

The following examples show how to use org.apache.pdfbox.cos.COSArray#add() . 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: PDSeparation.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a new Separation color space.
 */
public PDSeparation()
{
    array = new COSArray();
    array.add(COSName.SEPARATION);
    array.add(COSName.getPDFName(""));
    // add some placeholder
    array.add(COSNull.NULL);
    array.add(COSNull.NULL);
}
 
Example 2
Source File: PDNumberTreeNode.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Set the numbers for this node. This method will set the appropriate upper and lower limits
 * based on the keys in the map.
 *
 * @param numbers The map of numbers to objects, or <code>null</code> for nothing.
 */
public void setNumbers( Map<Integer, ? extends COSObjectable> numbers )
{
    if( numbers == null )
    {
        node.setItem( COSName.NUMS, (COSObjectable)null );
        node.setItem( COSName.LIMITS, (COSObjectable)null);
    }
    else
    {
        List<Integer> keys = new ArrayList<Integer>( numbers.keySet() );
        Collections.sort( keys );
        COSArray array = new COSArray();
        for (Integer key : keys)
        {
            array.add( COSInteger.get( key ) );
            COSObjectable obj = numbers.get( key );
            array.add(obj == null ? COSNull.NULL : obj);
        }
        Integer lower = null;
        Integer upper = null;
        if (!keys.isEmpty())
        {
            lower = keys.get( 0 );
            upper = keys.get( keys.size()-1 );
        }
        setUpperLimit( upper );
        setLowerLimit( lower );
        node.setItem( COSName.NUMS, array );
    }
}
 
Example 3
Source File: PDPattern.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a new uncolored tiling pattern color space.
 * 
 * @param resources The current resources.
 * @param colorSpace The underlying color space.
 */
public PDPattern(PDResources resources, PDColorSpace colorSpace)
{
    this.resources = resources;
    this.underlyingColorSpace = colorSpace;
    array = new COSArray();
    array.add(COSName.PATTERN);
    array.add(colorSpace);
}
 
Example 4
Source File: PDUserAttributeObject.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Sets the user properties.
 * 
 * @param userProperties the user properties
 */
public void setUserProperties(List<PDUserProperty> userProperties)
{
    COSArray p = new COSArray();
    for (PDUserProperty userProperty : userProperties)
    {
        p.add(userProperty);
    }
    this.getCOSObject().setItem(COSName.P, p);
}
 
Example 5
Source File: FDFAnnotationInk.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Set the paths making up the freehand "scribble".
 * 
 * The ink annotation is made up of one ore more disjoint paths. Each array entry is an array representing a stroked
 * path, being a series of alternating horizontal and vertical coordinates in default user space.
 * 
 * @param inklist the List of arrays representing the paths.
 */
public final void setInkList(List<float[]> inklist)
{
    COSArray newInklist = new COSArray();
    for (float[] array : inklist)
    {
        COSArray newArray = new COSArray();
        newArray.setFloatArray(array);
        newInklist.add(newArray);
    }
    annot.setItem(COSName.INKLIST, newInklist);
}
 
Example 6
Source File: PDRectlinearMeasureDictionary.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will set the areas.
 * 
 * @param areas areas
 */
public void setAreas(PDNumberFormatDictionary[] areas)
{
    COSArray array = new COSArray();
    for (PDNumberFormatDictionary area : areas)
    {
        array.add(area);
    }
    this.getCOSObject().setItem(COSName.A, array);
}
 
Example 7
Source File: PDTristimulus.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Constructor. Defaults all values to 0, 0, 0.
 */
public PDTristimulus()
{
    values = new COSArray();
    values.add(new COSFloat(0.0f));
    values.add(new COSFloat(0.0f));
    values.add(new COSFloat(0.0f));
}
 
Example 8
Source File: PDICCBased.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a new ICC color space with an empty stream.
 * @param doc the document to store the ICC data
 */
public PDICCBased(PDDocument doc)
{
    array = new COSArray();
    array.add(COSName.ICCBASED);
    stream = new PDStream(doc);
    array.add(stream);
}
 
Example 9
Source File: PDOptionalContentMembershipDictionary.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Set optional content groups as a list.
 * 
 * @param ocgs list of optional content groups to set.
 */
public void setOCGs(List<PDPropertyList> ocgs)
{
    COSArray ar = new COSArray();
    for (PDPropertyList prop : ocgs)
    {
        ar.add(prop);
    }
    dict.setItem(COSName.OCGS, ar);
}
 
Example 10
Source File: LayerUtility.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Some applications may not wrap their page content in a save/restore (q/Q) pair which can
 * lead to problems with coordinate system transformations when content is appended. This
 * method lets you add a q/Q pair around the existing page's content.
 * @param page the page
 * @throws IOException if an I/O error occurs
 */
public void wrapInSaveRestore(PDPage page) throws IOException
{
    COSStream saveGraphicsStateStream = getDocument().getDocument().createCOSStream();
    OutputStream saveStream = saveGraphicsStateStream.createOutputStream();
    saveStream.write("q\n".getBytes("ISO-8859-1"));
    saveStream.close();

    COSStream restoreGraphicsStateStream = getDocument().getDocument().createCOSStream();
    OutputStream restoreStream = restoreGraphicsStateStream.createOutputStream();
    restoreStream.write("Q\n".getBytes("ISO-8859-1"));
    restoreStream.close();

    //Wrap the existing page's content in a save/restore pair (q/Q) to have a controlled
    //environment to add additional content.
    COSDictionary pageDictionary = page.getCOSObject();
    COSBase contents = pageDictionary.getDictionaryObject(COSName.CONTENTS);
    if (contents instanceof COSStream)
    {
        COSStream contentsStream = (COSStream)contents;

        COSArray array = new COSArray();
        array.add(saveGraphicsStateStream);
        array.add(contentsStream);
        array.add(restoreGraphicsStateStream);

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

        contentsArray.add(0, saveGraphicsStateStream);
        contentsArray.add(restoreGraphicsStateStream);
    }
    else
    {
        throw new IOException("Contents are unknown type: " + contents.getClass().getName());
    }
}
 
Example 11
Source File: PDPageLabels.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc} 
 */
@Override
public COSBase getCOSObject()
{
    COSDictionary dict = new COSDictionary();
    COSArray arr = new COSArray();
    for (Entry<Integer, PDPageLabelRange> i : labels.entrySet())
    {
        arr.add(COSInteger.get(i.getKey()));
        arr.add(i.getValue());
    }
    dict.setItem(COSName.NUMS, arr);
    return dict;
}
 
Example 12
Source File: PDCIDFontType2Embedder.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 13
Source File: Overlay.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private void processPages(PDDocument document) throws IOException
{
    int pageCounter = 0;
    for (PDPage page : document.getPages())
    {
        pageCounter++;
        COSDictionary pageDictionary = page.getCOSObject();
        COSBase originalContent = pageDictionary.getDictionaryObject(COSName.CONTENTS);
        COSArray newContentArray = new COSArray();
        LayoutPage layoutPage = getLayoutPage(pageCounter, document.getNumberOfPages());
        if (layoutPage == null)
        {
            continue;
        }
        switch (position)
        {
            case FOREGROUND:
                // save state
                newContentArray.add(createStream("q\n"));
                addOriginalContent(originalContent, newContentArray);
                // restore state
                newContentArray.add(createStream("Q\n"));
                // overlay content last
                overlayPage(page, layoutPage, newContentArray);
                break;
            case BACKGROUND:
                // overlay content first
                overlayPage(page, layoutPage, newContentArray);

                addOriginalContent(originalContent, newContentArray);
                break;
            default:
                throw new IOException("Unknown type of position:" + position);
        }
        pageDictionary.setItem(COSName.CONTENTS, newContentArray);
    }
}
 
Example 14
Source File: PDStandardAttributeObject.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Sets an array of strings.
 * 
 * @param name the attribute name
 * @param values the array of strings
 */
protected void setArrayOfString(String name, String[] values)
{
    COSBase oldBase = this.getCOSObject().getDictionaryObject(name);
    COSArray array = new COSArray();
    for (String value : values)
    {
        array.add(new COSString(value));
    }
    this.getCOSObject().setItem(name, array);
    COSBase newBase = this.getCOSObject().getDictionaryObject(name);
    this.potentiallyNotifyChanged(oldBase, newBase);
}
 
Example 15
Source File: PDShadingType1.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Sets the optional Matrix entry for the function based shading.
 *
 * @param transform the transformation matrix
 */
public void setMatrix(AffineTransform transform)
{
    COSArray matrix = new COSArray();
    double[] values = new double[6];
    transform.getMatrix(values);
    for (double v : values)
    {
        matrix.add(new COSFloat((float) v));
    }
    getCOSObject().setItem(COSName.MATRIX, matrix);
}
 
Example 16
Source File: PDPage.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Set the viewports.
 *
 * @param viewports A list of viewports, or null if the entry is to be deleted.
 */
public void setViewports(List<PDViewportDictionary> viewports)
{
    if (viewports == null)
    {
        page.removeItem(COSName.VP);
        return;
    }
    COSArray array = new COSArray();
    for (PDViewportDictionary viewport : viewports)
    {
        array.add(viewport);
    }
    page.setItem(COSName.VP, array);
}
 
Example 17
Source File: AddSpecialCharacterWithoutEmbedding.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
COSDictionary buildUnembeddedArialWithSpecialEncoding() {
    COSArray differences = new COSArray();
    differences.add(COSInteger.get(32));
    differences.add(COSName.getPDFName("uniAB55"));

    COSDictionary fontDescDict = new COSDictionary();
    fontDescDict.setName("Type", "FontDescriptor");
    fontDescDict.setName("FontName", "Arial");
    fontDescDict.setString("FontFamily", "Arial");
    fontDescDict.setInt("Flags", 32);
    fontDescDict.setItem("FontBBox", new PDRectangle(-665, -325, 2665, 1365));
    fontDescDict.setInt("ItalicAngle", 0);
    fontDescDict.setInt("Ascent", 1040);
    fontDescDict.setInt("Descent", -325);
    fontDescDict.setInt("CapHeight", 716);
    fontDescDict.setInt("StemV", 88);
    fontDescDict.setInt("XHeight", 519);

    COSDictionary encodingDict = new COSDictionary();
    encodingDict.setName("Type", "Encoding");
    encodingDict.setName("BaseEncoding", "WinAnsiEncoding");
    encodingDict.setItem("Differences", differences);

    COSArray widths = new COSArray();
    widths.add(COSInteger.get(500));

    COSDictionary fontDict = new COSDictionary();
    fontDict.setName("Type", "Font");
    fontDict.setName("Subtype", "TrueType");
    fontDict.setName("BaseFont", "Arial");
    fontDict.setInt("FirstChar", 32);
    fontDict.setInt("LastChar", 32);
    fontDict.setItem("Widths", widths);
    fontDict.setItem("FontDescriptor", fontDescDict);
    fontDict.setItem("Encoding", encodingDict);

    return fontDict;
}
 
Example 18
Source File: FDFAnnotationStamp.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
private COSArray parseArrayElement(Element arrayEl) throws IOException
{
    LOG.debug("Parse " + arrayEl.getAttribute("KEY") + " Array");
    COSArray array = new COSArray();

    NodeList nodeList = arrayEl.getChildNodes();
    String parentAttrKey = arrayEl.getAttribute("KEY");

    if ("BBox".equals(parentAttrKey))
    {
        if (nodeList.getLength() < 4)
        {
            throw new IOException("BBox does not have enough coordinates, only has: " +
                    nodeList.getLength());
        }
    }
    else if ("Matrix".equals(parentAttrKey))
    {
        if (nodeList.getLength() < 6)
        {
            throw new IOException("Matrix does not have enough coordinates, only has: " + 
                    nodeList.getLength());
        }
    }

    for (int i = 0; i < nodeList.getLength(); i++)
    {
        Node node = nodeList.item(i);
        if (node instanceof Element)
        {
            Element child = (Element) node;
            String childAttrKey = child.getAttribute("KEY");
            String childAttrVal = child.getAttribute("VAL");
            LOG.debug(parentAttrKey + " => reading child: " + child.getTagName() +
                       " with key: " + childAttrKey);
            if ("INT".equalsIgnoreCase(child.getTagName()))
            {
                LOG.debug(parentAttrKey + " value(" + i + "): " + child.getAttribute("VAL"));
                array.add(COSFloat.get(childAttrVal));
            }
            else if ("FIXED".equalsIgnoreCase(child.getTagName()))
            {
                LOG.debug(parentAttrKey + " value(" + i + "): " + child.getAttribute("VAL"));
                array.add(COSInteger.get(childAttrVal));
            }
            else if ("NAME".equalsIgnoreCase(child.getTagName()))
            {
                LOG.debug(parentAttrKey + " value(" + i + "): " + child.getAttribute("VAL"));
                array.add(COSName.getPDFName(childAttrVal));
            }
            else if ("BOOL".equalsIgnoreCase(child.getTagName()))
            {
                LOG.debug(parentAttrKey + " value(" + i + "): " + child.getAttribute("VAL"));
                array.add(COSBoolean.getBoolean(Boolean.parseBoolean(childAttrVal)));
            }
            else if ("DICT".equalsIgnoreCase(child.getTagName()))
            {
                LOG.debug(parentAttrKey + " value(" + i + "): " + child.getAttribute("VAL"));
                array.add(parseDictElement(child));
            }
            else if ("STREAM".equalsIgnoreCase(child.getTagName()))
            {
                LOG.debug(parentAttrKey + " value(" + i + "): " + child.getAttribute("VAL"));
                array.add(parseStreamElement(child));
            }
            else if ("ARRAY".equalsIgnoreCase(child.getTagName()))
            {
                LOG.debug(parentAttrKey + " value(" + i + "): " + child.getAttribute("VAL"));
                array.add(parseArrayElement(child));
            }
            else
            {
                LOG.warn(parentAttrKey + " => Not handling child element: " + child.getTagName());
            }
        }
    }

    return array;
}
 
Example 19
Source File: BaseParser.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * This will parse a PDF array object.
 *
 * @return The parsed PDF array.
 *
 * @throws IOException If there is an error parsing the stream.
 */
protected COSArray parseCOSArray() throws IOException
{
    long startPosition = seqSource.getPosition();
    readExpectedChar('[');
    COSArray po = new COSArray();
    COSBase pbo;
    skipSpaces();
    int i;
    while( ((i = seqSource.peek()) > 0) && ((char)i != ']') )
    {
        pbo = parseDirObject();
        if( pbo instanceof COSObject )
        {
            // We have to check if the expected values are there or not PDFBOX-385
            if (po.size() > 0 && po.get(po.size() - 1) instanceof COSInteger)
            {
                COSInteger genNumber = (COSInteger)po.remove( po.size() -1 );
                if (po.size() > 0 && po.get(po.size() - 1) instanceof COSInteger)
                {
                    COSInteger number = (COSInteger)po.remove( po.size() -1 );
                    COSObjectKey key = new COSObjectKey(number.longValue(), genNumber.intValue());
                    pbo = getObjectFromPool(key);
                }
                else
                {
                    // the object reference is somehow wrong
                    pbo = null;
                }
            }
            else
            {
                pbo = null;
            }
        }
        if( pbo != null )
        {
            po.add( pbo );
        }
        else
        {
            //it could be a bad object in the array which is just skipped
            LOG.warn("Corrupt object reference at offset " +
                    seqSource.getPosition() + ", start offset: " + startPosition);

            // This could also be an "endobj" or "endstream" which means we can assume that
            // the array has ended.
            String isThisTheEnd = readString();
            seqSource.unread(isThisTheEnd.getBytes(ISO_8859_1));
            if(ENDOBJ_STRING.equals(isThisTheEnd) || ENDSTREAM_STRING.equals(isThisTheEnd))
            {
                return po;
            }
        }
        skipSpaces();
    }
    // read ']'
    seqSource.read(); 
    skipSpaces();
    return po;
}
 
Example 20
Source File: PDAnnotationMarkup.java    From gcs with Mozilla Public License 2.0 3 votes vote down vote up
/**
 * This will set the difference between the annotations "outer" rectangle defined by
 * /Rect and the border.
 * 
 * @param differenceLeft left difference from the annotations /Rect entry
 * @param differenceTop top difference from the annotations /Rect entry
 * @param differenceRight right difference from  the annotations /Rect entry
 * @param differenceBottom bottom difference from the annotations /Rect entry
 * 
 */
public void setRectDifferences(float differenceLeft, float differenceTop, float differenceRight, float differenceBottom)
{
    COSArray margins = new COSArray();
    margins.add(new COSFloat(differenceLeft));
    margins.add(new COSFloat(differenceTop));
    margins.add(new COSFloat(differenceRight));
    margins.add(new COSFloat(differenceBottom));
    getCOSObject().setItem(COSName.RD, margins);    
}