org.apache.pdfbox.cos.COSStream Java Examples

The following examples show how to use org.apache.pdfbox.cos.COSStream. 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: FDFAnnotation.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Get a text or text stream.
 *
 * Some dictionary entries allow either a text or a text stream.
 *
 * @param base the potential text or text stream
 * @return the text stream
 */
protected final String getStringOrStream(COSBase base)
{
    if (base == null)
    {
        return "";
    }
    else if (base instanceof COSString)
    {
        return ((COSString) base).getString();
    }
    else if (base instanceof COSStream)
    {
        return ((COSStream) base).toTextString();
    }
    else
    {
        return "";
    }
}
 
Example #2
Source File: PDImageXObject.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Creates a COS stream from raw (encoded) data.
 */
private static COSStream createRawStream(PDDocument document, InputStream rawInput)
        throws IOException
{
    COSStream stream = document.getDocument().createCOSStream();
    OutputStream output = null;
    try
    {
        output = stream.createRawOutputStream();
        IOUtils.copy(rawInput, output);
    }
    finally
    {
        if (output != null)
        {
            output.close();
        }
    }
    return stream;
}
 
Example #3
Source File: PDStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Get the metadata that is part of the document catalog. This will return
 * null if there is no meta data for this object.
 * 
 * @return The metadata for this object.
 * @throws IllegalStateException if the value of the metadata entry is different from a stream
 *                               or null
 */
public PDMetadata getMetadata()
{
    PDMetadata retval = null;
    COSBase mdStream = stream.getDictionaryObject(COSName.METADATA);
    if (mdStream != null)
    {
        if (mdStream instanceof COSStream)
        {
            retval = new PDMetadata((COSStream) mdStream);
        } 
        else if (mdStream instanceof COSNull)
        {
            // null is authorized
        } 
        else
        {
            throw new IllegalStateException(
                    "Expected a COSStream but was a "
                            + mdStream.getClass().getSimpleName());
        }
    }
    return retval;
}
 
Example #4
Source File: PDImageXObject.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Returns the Mask Image XObject associated with this image, or null if there is none.
 * @return Mask Image XObject
 * @throws java.io.IOException
 */
public PDImageXObject getMask() throws IOException
{
    COSBase mask = getCOSObject().getDictionaryObject(COSName.MASK);
    if (mask instanceof COSArray)
    {
        // color key mask, no explicit mask to return
        return null;
    }
    else
    {
        COSStream cosStream = getCOSObject().getCOSStream(COSName.MASK);
        if (cosStream != null)
        {
            // always DeviceGray
            return new PDImageXObject(new PDStream(cosStream), null);
        }
        return null;
    }
}
 
Example #5
Source File: PDResources.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Tells whether the XObject resource with the given name is an image.
 *
 * @param name Name of the XObject resource.
 * @return true if it is an image XObject, false if not.
 */
public boolean isImageXObject(COSName name)
{
    // get the instance
    COSBase value = get(COSName.XOBJECT, name);
    if (value == null)
    {
        return false;
    }
    else if (value instanceof COSObject)
    {
        value = ((COSObject) value).getObject();
    }
    if (!(value instanceof COSStream))
    {
        return false;
    }
    COSStream stream = (COSStream) value;
    return COSName.IMAGE.equals(stream.getCOSName(COSName.SUBTYPE));
}
 
Example #6
Source File: PDAppearanceEntry.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Returns the entry as an appearance subdictionary.
 *
 * @throws IllegalStateException if this entry is not an appearance subdictionary
 */
public Map<COSName, PDAppearanceStream> getSubDictionary()
{
    if (!isSubDictionary())
    {
        throw new IllegalStateException("This entry is not an appearance subdictionary");
    }

    COSDictionary dict = (COSDictionary) entry;
    Map<COSName, PDAppearanceStream> map = new HashMap<COSName, PDAppearanceStream>();

    for (COSName name : dict.keySet())
    {
        COSBase value = dict.getDictionaryObject(name);

        // the file from PDFBOX-1599 contains /null as its entry, so we skip non-stream entries
        if (value instanceof COSStream)
        {
            map.put(name, new PDAppearanceStream((COSStream) value));
        }
    }

    return new COSDictionaryMap<COSName, PDAppearanceStream>(map, dict);
}
 
Example #7
Source File: FDFJavaScript.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * This will get the javascript that is executed before the import.
 *
 * @return Some javascript code.
 */
public String getBefore()
{
    COSBase base = dictionary.getDictionaryObject(COSName.BEFORE);
    if (base instanceof COSString)
    {
        return ((COSString) base).getString();
    }
    else if (base instanceof COSStream)
    {
        return ((COSStream) base).toTextString();
    }
    else
    {
        return null;
    }
}
 
Example #8
Source File: PDPage.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Returns the content streams which make up this page.
 * 
 * @return content stream iterator
 */
public Iterator<PDStream> getContentStreams()
{
    List<PDStream> streams = new ArrayList<PDStream>();
    COSBase base = page.getDictionaryObject(COSName.CONTENTS);
    if (base instanceof COSStream)
    {
        streams.add(new PDStream((COSStream) base));
    }
    else if (base instanceof COSArray && ((COSArray) base).size() > 0)
    {
        COSArray array = (COSArray)base;
        for (int i = 0; i < array.size(); i++)
        {
            COSStream stream = (COSStream) array.getObject(i);
            streams.add(new PDStream(stream));
        }
    }
    return streams.iterator();
}
 
Example #9
Source File: Overlay.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private void addOriginalContent(COSBase contents, COSArray contentArray) throws IOException
{
    if (contents == null)
    {
        return;
    }

    if (contents instanceof COSStream)
    {
        contentArray.add(contents);
    }
    else if (contents instanceof COSArray)
    {
        contentArray.addAll((COSArray) contents);
    }
    else
    {
        throw new IOException("Unknown content type: " + contents.getClass().getName());
    }
}
 
Example #10
Source File: PDActionJavaScript.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * @return The Javascript Code.
 */
public String getAction()
{
    COSBase base = action.getDictionaryObject( COSName.JS );
    if (base instanceof COSString)
    {
        return ((COSString)base).getString();
    }
    else if (base instanceof COSStream)
    {
        return ((COSStream)base).toTextString();
    }
    else
    {
        return null;
    }
}
 
Example #11
Source File: PDVariableText.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Get a text as text stream.
 *
 * Some dictionary entries allow either a text or a text stream.
 *
 * @param base the potential text or text stream
 * @return the text stream
 */
protected final String getStringOrStream(COSBase base)
{
    if (base == null)
    {
        return "";
    }
    else if (base instanceof COSString)
    {
        return ((COSString)base).getString();
    }
    else if (base instanceof COSStream)
    {
        return ((COSStream)base).toTextString();
    }
    else
    {
        return "";
    }
}
 
Example #12
Source File: FDFField.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Returns the COS value of this field.
 * 
 * @return The COS value of the field.
 * @throws IOException If there is an error getting the value.
 */
public COSBase getCOSValue() throws IOException
{
    COSBase value = field.getDictionaryObject(COSName.V);
    
    if (value instanceof COSName)
    {
        return value;
    }
    else if (value instanceof COSArray)
    {
        return value;
    }
    else if (value instanceof COSString || value instanceof COSStream)
    {
        return value;
    }
    else if (value != null)
    {
        throw new IOException("Error:Unknown type for field import" + value);
    }
    else
    {
        return null;
    }
}
 
Example #13
Source File: COSParser.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Parses an xref object stream starting with indirect object id.
 * 
 * @return value of PREV item in dictionary or <code>-1</code> if no such item exists
 */
private long parseXrefObjStream(long objByteOffset, boolean isStandalone) throws IOException
{
    // ---- parse indirect object head
    long objectNumber = readObjectNumber();

    // remember the highest XRef object number to avoid it being reused in incremental saving
    long currentHighestXRefObjectNumber = document.getHighestXRefObjectNumber();
    document.setHighestXRefObjectNumber(Math.max(currentHighestXRefObjectNumber, objectNumber));

    readGenerationNumber();
    readExpectedString(OBJ_MARKER, true);

    COSDictionary dict = parseCOSDictionary();
    COSStream xrefStream = parseCOSStream(dict);
    parseXrefStream(xrefStream, objByteOffset, isStandalone);
    xrefStream.close();

    return dict.getLong(COSName.PREV);
}
 
Example #14
Source File: PDImageXObject.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Returns the Soft Mask Image XObject associated with this image, or null if there is none.
 * @return the SMask Image XObject, or null.
 * @throws java.io.IOException
 */
public PDImageXObject getSoftMask() throws IOException
{
    COSStream cosStream = getCOSObject().getCOSStream(COSName.SMASK);
    if (cosStream != null)
    {
        // always DeviceGray
        return new PDImageXObject(new PDStream(cosStream), null);
    }
    return null;
}
 
Example #15
Source File: PDPage.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Get the metadata that is part of the document catalog. This will return null if there is
 * no meta data for this object.
 * 
 * @return The metadata for this object.
 */
public PDMetadata getMetadata()
{
    PDMetadata retval = null;
    COSBase base = page.getDictionaryObject(COSName.METADATA);
    if (base instanceof COSStream)
    {
        retval = new PDMetadata((COSStream) base);
    }
    return retval;
}
 
Example #16
Source File: PDPage.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Returns true if this page has one or more content streams.
 */
public boolean hasContents()
{
    COSBase contents = page.getDictionaryObject(COSName.CONTENTS);
    if (contents instanceof COSStream)
    {
        return ((COSStream) contents).size() > 0;
    }
    else if (contents instanceof COSArray)
    {
        return ((COSArray) contents).size() > 0;
    }
    return false;
}
 
Example #17
Source File: PDComplexFileSpecification.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Get the embedded Unix file.
 *
 * @return The embedded file for this file spec.
 */
public PDEmbeddedFile getEmbeddedFileUnix()
{
    PDEmbeddedFile file = null;
    COSStream stream = (COSStream)getObjectFromEFDictionary( COSName.UNIX );
    if( stream != null )
    {
        file = new PDEmbeddedFile( stream );
    }
    return file;
}
 
Example #18
Source File: PdfBoxSignatureService.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private COSArray buildArray(PDDocument pdDocument, Map<String, COSStream> streams,
		Collection<? extends Token> tokens, Map<String, Long> knownObjects) throws IOException {
	COSArray array = new COSArray();
	// avoid duplicate CRLs
	List<String> currentObjIds = new ArrayList<>();
	for (Token token : tokens) {
		String digest = getTokenDigest(token);
		if (!currentObjIds.contains(digest)) {
			Long objectNumber = knownObjects.get(digest);
			if (objectNumber == null) {
				COSStream stream = streams.get(digest);
				if (stream == null) {
					stream = pdDocument.getDocument().createCOSStream();
					try (OutputStream unfilteredStream = stream.createOutputStream()) {
						unfilteredStream.write(token.getEncoded());
						unfilteredStream.flush();
					}
					streams.put(digest, stream);
				}
				array.add(stream);
			} else {
				COSObject foundCosObject = getByObjectNumber(pdDocument, objectNumber);
				array.add(foundCosObject);
			}
			currentObjIds.add(digest);
		}
	}
	return array;
}
 
Example #19
Source File: PDAppearanceEntry.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Returns the entry as an appearance stream.
 *
 * @throws IllegalStateException if this entry is not an appearance stream
 */
public PDAppearanceStream getAppearanceStream()
{
    if (!isStream())
    {
        throw new IllegalStateException("This entry is not an appearance stream");
    }
    return new PDAppearanceStream((COSStream) entry);
}
 
Example #20
Source File: PDImageXObject.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a thumbnail Image XObject from the given COSBase and name.
 * @param cosStream the COS stream
 * @return an XObject
 * @throws IOException if there is an error creating the XObject.
 */
public static PDImageXObject createThumbnail(COSStream cosStream) throws IOException
{
    // thumbnails are special, any non-null subtype is treated as being "Image"
    PDStream pdStream = new PDStream(cosStream);
    return new PDImageXObject(pdStream, null);
}
 
Example #21
Source File: PDObjectStream.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will create a new PDObjectStream object.
 *
 * @param document The document that the stream will be part of.
 * @return A new stream object.
 */
public static PDObjectStream createStream( PDDocument document )
{
    COSStream cosStream = document.getDocument().createCOSStream();
    PDObjectStream strm = new PDObjectStream( cosStream );
    strm.getCOSObject().setItem( COSName.TYPE, COSName.OBJ_STM );
    return strm;
}
 
Example #22
Source File: PDImageXObject.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Returns the metadata associated with this XObject, or null if there is none.
 * @return the metadata associated with this object.
 */
public PDMetadata getMetadata()
{
    COSStream cosStream = getCOSObject().getCOSStream(COSName.METADATA);
    if (cosStream != null)
    {
        return new PDMetadata(cosStream);
    }
    return null;
}
 
Example #23
Source File: PDObjectReference.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Gets a higher-level object for the referenced object.
 * Currently this method may return a {@link PDAnnotation},
 * a {@link PDXObject} or <code>null</code>.
 * 
 * @return a higher-level object for the referenced object
 */
public COSObjectable getReferencedObject()
{
    COSBase obj = this.getCOSObject().getDictionaryObject(COSName.OBJ);
    if (!(obj instanceof COSDictionary))
    {
        return null;
    }
    try
    {
        if (obj instanceof COSStream)
        {
            PDXObject xobject = PDXObject.createXObject(obj, null); // <-- TODO: valid?
            if (xobject != null)
            {
                return xobject;
            }
        }
        COSDictionary objDictionary  = (COSDictionary)obj;
        PDAnnotation annotation = PDAnnotation.createAnnotation(obj);
        /*
         * COSName.TYPE is optional, so if annotation is of type unknown and
         * COSName.TYPE is not COSName.ANNOT it still may be an annotation.
         * TODO shall we return the annotation object instead of null?
         * what else can be the target of the object reference?
         */
        if (!(annotation instanceof PDAnnotationUnknown) 
                || COSName.ANNOT.equals(objDictionary.getDictionaryObject(COSName.TYPE))) 
        {
            return annotation;
        }
    }
    catch (IOException exception)
    {
        // this can only happen if the target is an XObject.
    }
    return null;
}
 
Example #24
Source File: PDFont.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Reads a CMap given a COS Stream or Name. May return null if a predefined CMap does not exist.
 *
 * @param base COSName or COSStream
 */
protected final CMap readCMap(COSBase base) throws IOException
{
    if (base instanceof COSName)
    {
        // predefined CMap
        String name = ((COSName)base).getName();
        return CMapManager.getPredefinedCMap(name);
    }
    else if (base instanceof COSStream)
    {
        // embedded CMap
        InputStream input = null;
        try
        {
            input = ((COSStream)base).createInputStream();
            return CMapManager.parseCMap(input);
        }
        finally
        {
            IOUtils.closeQuietly(input);
        }
    }
    else
    {
        throw new IOException("Expected Name or Stream");
    }
}
 
Example #25
Source File: PDDocumentCatalog.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Get the metadata that is part of the document catalog. This will return null if there is no
 * meta data for this object.
 *
 * @return The metadata for this object.
 */
public PDMetadata getMetadata()
{
    COSBase metaObj = root.getDictionaryObject(COSName.METADATA);
    if (metaObj instanceof COSStream)
    {
        return new PDMetadata((COSStream) metaObj);
    }
    return null;
}
 
Example #26
Source File: SecurityHandler.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will dispatch to the correct method.
 *
 * @param obj The object to decrypt.
 * @param objNum The object number.
 * @param genNum The object generation Number.
 *
 * @throws IOException If there is an error getting the stream data.
 */
public void decrypt(COSBase obj, long objNum, long genNum) throws IOException
{
    if (!(obj instanceof COSString || obj instanceof COSDictionary || obj instanceof COSArray))
    {
        return;
    }
    // PDFBOX-4477: only cache strings and streams, this improves speed and memory footprint
    if (obj instanceof COSString)
    {
        if (objects.contains(obj))
        {
            return;
        }
        objects.add(obj);
        decryptString((COSString) obj, objNum, genNum);
    }
    else if (obj instanceof COSStream)
    {
        if (objects.contains(obj))
        {
            return;
        }
        objects.add(obj);
        decryptStream((COSStream) obj, objNum, genNum);
    }
    else if (obj instanceof COSDictionary)
    {
        decryptDictionary((COSDictionary) obj, objNum, genNum);
    }
    else if (obj instanceof COSArray)
    {
        decryptArray((COSArray) obj, objNum, genNum);
    }
}
 
Example #27
Source File: SecurityHandler.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will encrypt a stream, but not the dictionary as the dictionary is
 * encrypted by visitFromString() in COSWriter and we don't want to encrypt
 * it twice.
 *
 * @param stream The stream to decrypt.
 * @param objNum The object number.
 * @param genNum The object generation number.
 *
 * @throws IOException If there is an error getting the stream data.
 */
public void encryptStream(COSStream stream, long objNum, int genNum) throws IOException
{
    byte[] rawData = IOUtils.toByteArray(stream.createRawInputStream());
    ByteArrayInputStream encryptedStream = new ByteArrayInputStream(rawData);
    OutputStream output = stream.createRawOutputStream();
    try
    {
        encryptData(objNum, genNum, encryptedStream, output, false /* encrypt */);
    }
    finally
    {
        output.close();
    }
}
 
Example #28
Source File: PDFontDescriptor.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Get the CIDSet stream.
 *
 * @return A stream containing a CIDSet.
 */
public PDStream getCIDSet()
{
    COSObjectable cidSet = dic.getDictionaryObject(COSName.CID_SET);
    if (cidSet instanceof COSStream)
    {
        return new PDStream((COSStream) cidSet);
    }
    return null;
}
 
Example #29
Source File: COSWriter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Object visitFromStream(COSStream obj) throws IOException
{
    if (willEncrypt)
    {
        pdDocument.getEncryption().getSecurityHandler()
            .encryptStream(obj, currentObjectKey.getNumber(), currentObjectKey.getGeneration());
    }

    InputStream input = null;
    try
    {
        // write the stream content
        visitFromDictionary(obj);
        getStandardOutput().write(STREAM);
        getStandardOutput().writeCRLF();

        input = obj.createRawInputStream();
        IOUtils.copy(input, getStandardOutput());
     
        getStandardOutput().writeCRLF();
        getStandardOutput().write(ENDSTREAM);
        getStandardOutput().writeEOL();
        return null;
    }
    finally
    {
        if (input != null)
        {
            input.close();
        }
    }
}
 
Example #30
Source File: FDFField.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will get the value for the field. This will return type will either be <br>
 * String : Checkboxes, Radio Button, Textfields <br>
 * java.util.List of strings: Choice Field
 *
 * @return The value of the field.
 * @throws IOException If there is an error getting the value.
 */
public Object getValue() throws IOException
{
    COSBase value = field.getDictionaryObject(COSName.V);
    if (value instanceof COSName)
    {
        return ((COSName) value).getName();
    }
    else if (value instanceof COSArray)
    {
        return COSArrayList.convertCOSStringCOSArrayToList((COSArray) value);
    }
    else if (value instanceof COSString)
    {
        return ((COSString) value).getString();
    }
    else if (value instanceof COSStream)
    {
        return ((COSStream) value).toTextString();
    }
    else if (value != null)
    {
        throw new IOException("Error:Unknown type for field import" + value);
    }
    else
    {
        return null;
    }
}