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

The following examples show how to use org.apache.pdfbox.cos.COSDictionary#getDictionaryObject() . 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: PDOptionalContentGroup.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * @param destination to be rendered
 * @return state or null if undefined
 */
public RenderState getRenderState(RenderDestination destination)
{
    COSName state = null;
    COSDictionary usage = (COSDictionary) dict.getDictionaryObject("Usage");
    if (usage != null)
    {
        if (RenderDestination.PRINT.equals(destination))
        {
            COSDictionary print = (COSDictionary) usage.getDictionaryObject("Print");
            state = print == null ? null : (COSName) print.getDictionaryObject("PrintState");
        }
        else if (RenderDestination.VIEW.equals(destination))
        {
            COSDictionary view = (COSDictionary) usage.getDictionaryObject("View");
            state = view == null ? null : (COSName) view.getDictionaryObject("ViewState");
        }
        // Fallback to export
        if (state == null)
        {
            COSDictionary export = (COSDictionary) usage.getDictionaryObject("Export");
            state = export == null ? null : (COSName) export.getDictionaryObject("ExportState");
        }
    }
    return state == null ? null : RenderState.valueOf(state);
}
 
Example 2
Source File: PDPageTree.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Insert a page after another page within a page tree.
 *
 * @param newPage the page to be inserted.
 * @param prevPage the page that is to be before the new page.
 * @throws IllegalArgumentException if one attempts to insert a page that isn't part of a page
 * tree.
 */
public void insertAfter(PDPage newPage, PDPage prevPage)
{
    COSDictionary prevPageDict = prevPage.getCOSObject();
    COSDictionary parentDict = (COSDictionary) prevPageDict.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(prevPage.getCOSObject()))
        {
            kids.add(i + 1, 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 3
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 4
Source File: PDPageTree.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Returns the given attribute, inheriting from parent tree nodes if necessary.
 *
 * @param node page object
 * @param key the key to look up
 * @return COS value for the given key
 */
public static COSBase getInheritableAttribute(COSDictionary node, COSName key)
{
    COSBase value = node.getDictionaryObject(key);
    if (value != null)
    {
        return value;
    }

    COSBase base = node.getDictionaryObject(COSName.PARENT, COSName.P);
    if (base instanceof COSDictionary)
    {
        COSDictionary parent = (COSDictionary) base;
        if (COSName.PAGES.equals(parent.getDictionaryObject(COSName.TYPE)))
        {
            return getInheritableAttribute(parent, key);
        }
    }

    return null;
}
 
Example 5
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 6
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 7
Source File: CryptFilter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public DecodeResult decode(InputStream encoded, OutputStream decoded,
                                     COSDictionary parameters, int index) 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.decode(encoded, decoded, parameters, index);
        return new DecodeResult(parameters);
    }
    throw new IOException("Unsupported crypt filter " + encryptionName.getName());
}
 
Example 8
Source File: PDFieldFactory.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private static String findFieldType(COSDictionary dic)
{
    String retval = dic.getNameAsString(COSName.FT);
    if (retval == null)
    {
        COSBase base = dic.getDictionaryObject(COSName.PARENT, COSName.P);
        if (base instanceof COSDictionary)
        {
            retval = findFieldType((COSDictionary) base);
        }
    }
    return retval;
}
 
Example 9
Source File: PDComplexFileSpecification.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
private COSBase getObjectFromEFDictionary(COSName key)
{
    COSDictionary ef = getEFDictionary();
    if (ef != null)
    {
        return ef.getDictionaryObject(key);
    }
    return null;
}
 
Example 10
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 11
Source File: OptimizeAfterMerge.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
/**
 * <a href="https://stackoverflow.com/questions/53420344/ho-to-reduce-the-size-of-merged-pdf-a1-b-files-with-pdfbox-or-other-java-library">
 * Ho to reduce the size of merged PDF A1/b Files with pdfbox or other java library
 * </a>
 * <br/>
 * <a href="https://datentransfer.sparkassenverlag.de/my/transfers/5q8eskgne52npemx8kid7728zk1hq3f993dfat8his">
 * dummy.pdf
 * </a>
 * <p>
 * This is the code the OP himself posted as his solution. This only works if
 * (a) all font programs embedded for the same name indeed are identical, and
 * if (b) all fonts to consider are in the immediate page resources, not the
 * resources of some referred to xobject or pattern. If those conditions are
 * fulfilled, though, it very likely is much faster than the approach in
 * {@link #optimize(PDDocument)}. For the example file provided by the OP,
 * its result is nearly as small.
 * </p>
 */
@Test
public void testOptimizeLikeSchowaveDummy() throws IOException {
    try (   InputStream resource = getClass().getResourceAsStream("dummy.pdf")  ) {
        PDDocument doc = Loader.loadPDF(resource);

        Map<String, COSBase> fontFileCache = new HashMap<>();
        for (int pageNumber = 0; pageNumber < doc.getNumberOfPages(); pageNumber++) {
            final PDPage page = doc.getPage(pageNumber);
            COSDictionary pageDictionary = (COSDictionary) page.getResources().getCOSObject().getDictionaryObject(COSName.FONT);
            for (COSName currentFont : pageDictionary.keySet()) {
                COSDictionary fontDictionary = (COSDictionary) pageDictionary.getDictionaryObject(currentFont);
                for (COSName actualFont : fontDictionary.keySet()) {
                    COSBase actualFontDictionaryObject = fontDictionary.getDictionaryObject(actualFont);
                    if (actualFontDictionaryObject instanceof COSDictionary) {
                        COSDictionary fontFile = (COSDictionary) actualFontDictionaryObject;
                        if (fontFile.getItem(COSName.FONT_NAME) instanceof COSName) {
                            COSName fontName = (COSName) fontFile.getItem(COSName.FONT_NAME);
                            fontFileCache.computeIfAbsent(fontName.getName(), key -> fontFile.getItem(COSName.FONT_FILE2));
                            fontFile.setItem(COSName.FONT_FILE2, fontFileCache.get(fontName.getName()));
                        }
                    }
                }
            }
        }

        doc.save(new File(RESULT_FOLDER, "dummy-optimized-like-schowave.pdf"));
    }
}
 
Example 12
Source File: PDFParser.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * The initial parse will first parse only the trailer, the xrefstart and all xref tables to have a pointer (offset)
 * to all the pdf's objects. It can handle linearized pdfs, which will have an xref at the end pointing to an xref
 * at the beginning of the file. Last the root object is parsed.
 * 
 * @throws InvalidPasswordException If the password is incorrect.
 * @throws IOException If something went wrong.
 */
protected void initialParse() throws IOException
{
    COSDictionary trailer = retrieveTrailer();

    COSBase base = parseTrailerValuesDynamically(trailer);
    if (!(base instanceof COSDictionary))
    {
        throw new IOException("Expected root dictionary, but got this: " + base);
    }
    COSDictionary root = (COSDictionary) base;
    // in some pdfs the type value "Catalog" is missing in the root object
    if (isLenient() && !root.containsKey(COSName.TYPE))
    {
        root.setItem(COSName.TYPE, COSName.CATALOG);
    }
    // parse all objects, starting at the root dictionary
    parseDictObjects(root, (COSName[]) null);
    // parse all objects of the info dictionary
    COSBase infoBase = trailer.getDictionaryObject(COSName.INFO);
    if (infoBase instanceof COSDictionary)
    {
        parseDictObjects((COSDictionary) infoBase, (COSName[]) null);
    }
    // check pages dictionaries
    checkPages(root);
    if (!(root.getDictionaryObject(COSName.PAGES) instanceof COSDictionary))
    {
        throw new IOException("Page tree root must be a dictionary");
    }
    document.setDecrypted();
    initialParseDone = true;
}
 
Example 13
Source File: NPEfix17_seventeen_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * This will get a field by name, possibly using the cache if setCache is true.
 *
 * @param fullyQualifiedName The name of the field to get.
 * @return The field with that name of null if one was not found.
 * @throws IOException If there is an error getting the field type.
 */
public PDField getField(String fullyQualifiedName)
{
    PDField retval = null;
    if (fieldCache != null)
    {
        retval = fieldCache.get(fullyQualifiedName);
    }
    else
    {
        String[] nameSubSection = fullyQualifiedName.split("\\.");
        COSArray fields = (COSArray) dictionary.getDictionaryObject(COSName.FIELDS);

        if (fields != null)
        {
            for (int i = 0; i < fields.size() && retval == null; i++)
            {
                COSDictionary element = (COSDictionary) fields.getObject(i);
                if (element != null)
                {
                    COSString fieldName = (COSString)element.getDictionaryObject(COSName.T);
                    if (fieldName.getString().equals(fullyQualifiedName) || fieldName.getString().equals(nameSubSection[0]))
                    {
                        PDField root = PDField.fromDictionary(this, element, null);
                        if (root != null)
                        {
                            if (nameSubSection.length > 1)
                            {
                                PDField kid = root.findKid(nameSubSection, 1);
                                if (kid != null) {
                                retval = kid;
                                }
                                else
                                {
                                retval = root;
                                }
                            }
                            else
                            {
                                retval = root;
                            }
                        }
                        else
                        {
                            retval = root;
                        }
                    }
                    else
                     {
                     retval = root;
                     }

                }
            }
        }
    }
    return retval;
}
 
Example 14
Source File: RenderType3Character.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/42032729/render-type3-font-character-as-image-using-pdfbox">
 * Render Type3 font character as image using PDFBox
 * </a>
 * <br/>
 * <a href="https://drive.google.com/file/d/0B0f6X4SAMh2KRDJTbm4tb3E1a1U/view">
 * 4700198773.pdf
 * </a>
 * from
 * <a href="http://stackoverflow.com/questions/37754112/extract-text-with-custom-font-result-non-readble">
 * extract text with custom font result non readble
 * </a>
 * <p>
 * This test shows how one can render individual Type 3 font glyphs as bitmaps.
 * Unfortunately PDFBox out-of-the-box does not provide a class to render contents
 * of arbitrary XObjects, merely for rendering pages; thus, we simply create a page
 * with the glyph in question and render that page.   
 * </p>
 * <p>
 * As the OP did not provide a sample PDF, we simply use one from another
 * stackoverflow question. There obviously might remain issues with the
 * OP's files.
 * </p>
 */
@Test
public void testRenderSdnList() throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException
{
    Method PDPageContentStreamWrite = PDPageContentStream.class.getSuperclass().getDeclaredMethod("write", String.class);
    PDPageContentStreamWrite.setAccessible(true);

    try (   InputStream resource = getClass().getResourceAsStream("sdnlist.pdf"))
    {
        PDDocument document = Loader.loadPDF(resource);

        PDPage page = document.getPage(1);
        PDResources pageResources = page.getResources();
        COSName f1Name = COSName.getPDFName("R144");
        PDType3Font fontF1 = (PDType3Font) pageResources.getFont(f1Name);
        Map<String, Integer> f1NameToCode = fontF1.getEncoding().getNameToCodeMap();

        COSDictionary charProcsDictionary = fontF1.getCharProcs();
        for (COSName key : charProcsDictionary.keySet())
        {
            COSStream stream = (COSStream) charProcsDictionary.getDictionaryObject(key);
            PDType3CharProc charProc = new PDType3CharProc(fontF1, stream);
            PDRectangle bbox = charProc.getGlyphBBox();
            if (bbox == null)
                bbox = charProc.getBBox();
            Integer code = f1NameToCode.get(key.getName());

            if (code != null)
            {
                PDDocument charDocument = new PDDocument();
                PDPage charPage = new PDPage(bbox);
                charDocument.addPage(charPage);
                charPage.setResources(pageResources);
                PDPageContentStream charContentStream = new PDPageContentStream(charDocument, charPage);
                charContentStream.beginText();
                charContentStream.setFont(fontF1, bbox.getHeight());
                //charContentStream.getOutputStream().write(String.format("<%2X> Tj\n", code).getBytes());
                PDPageContentStreamWrite.invoke(charContentStream, String.format("<%2X> Tj\n", code));
                charContentStream.endText();
                charContentStream.close();

                File result = new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.png", key.getName(), code));
                PDFRenderer renderer = new PDFRenderer(charDocument);
                BufferedImage image = renderer.renderImageWithDPI(0, 96);
                ImageIO.write(image, "PNG", result);
                charDocument.save(new File(RESULT_FOLDER, String.format("sdnlist-%s-%s.pdf", key.getName(), code)));
                charDocument.close();
            }
        }
    }
}
 
Example 15
Source File: NPEfix17_seventeen_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * This will get a field by name, possibly using the cache if setCache is true.
 *
 * @param fullyQualifiedName The name of the field to get.
 * @return The field with that name of null if one was not found.
 * @throws IOException If there is an error getting the field type.
 */
public PDField getField(String fullyQualifiedName)
{
    PDField retval = null;
    if (fieldCache != null)
    {
        retval = fieldCache.get(fullyQualifiedName);
    }
    else
    {
        String[] nameSubSection = fullyQualifiedName.split("\\.");
        COSArray fields = (COSArray) dictionary.getDictionaryObject(COSName.FIELDS);

        for (int i = 0; i < fields.size() && retval == null; i++)
        {
            COSDictionary element = (COSDictionary) fields.getObject(i);
            if (element != null)
            {
                COSString fieldName =
                        (COSString)element.getDictionaryObject(COSName.T);
                if (fieldName.getString().equals(fullyQualifiedName) ||
                        fieldName.getString().equals(nameSubSection[0]))
                {
                    PDField root = PDField.fromDictionary(this, element, null);
                    if (root != null)
                    {
                        if (nameSubSection.length > 1)
                        {
                            PDField kid = root.findKid(nameSubSection, 1);
                            if (kid != null)
                            {
                                retval = kid;
                            }
                            else
                            {
                                retval = root;
                            }
                        }
                        else
                        {
                            retval = root;
                        }
                    }
                }
            }
        }
    }
    return retval;
}
 
Example 16
Source File: ContentStreamWriter.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
private void writeObject( Object o ) throws IOException
{
    if( o instanceof COSString )
    {
        COSWriter.writeString((COSString)o, output);
        output.write( SPACE );
    }
    else if( o instanceof COSFloat )
    {
        ((COSFloat)o).writePDF( output );
        output.write( SPACE );
    }
    else if( o instanceof COSInteger )
    {
        ((COSInteger)o).writePDF( output );
        output.write( SPACE );
    }
    else if( o instanceof COSBoolean )
    {
        ((COSBoolean)o).writePDF( output );
        output.write( SPACE );
    }
    else if( o instanceof COSName )
    {
        ((COSName)o).writePDF( output );
        output.write( SPACE );
    }
    else if( o instanceof COSArray )
    {
        COSArray array = (COSArray)o;
        output.write(COSWriter.ARRAY_OPEN);
        for( int i=0; i<array.size(); i++ )
        {
            writeObject( array.get( i ) );
            output.write( SPACE );
        }

        output.write( COSWriter.ARRAY_CLOSE );
    }
    else if( o instanceof COSDictionary )
    {
        COSDictionary obj = (COSDictionary)o;
        output.write( COSWriter.DICT_OPEN );
        for (Map.Entry<COSName, COSBase> entry : obj.entrySet())
        {
            if (entry.getValue() != null)
            {
                writeObject( entry.getKey() );
                output.write( SPACE );
                writeObject( entry.getValue() );
                output.write( SPACE );
            }
        }
        output.write( COSWriter.DICT_CLOSE );
        output.write( SPACE );
    }
    else if( o instanceof Operator)
    {
        Operator op = (Operator)o;
        if (op.getName().equals(OperatorName.BEGIN_INLINE_IMAGE))
        {
            output.write(OperatorName.BEGIN_INLINE_IMAGE.getBytes(Charsets.ISO_8859_1));
            COSDictionary dic = op.getImageParameters();
            for( COSName key : dic.keySet() )
            {
                Object value = dic.getDictionaryObject( key );
                key.writePDF( output );
                output.write( SPACE );
                writeObject( value );
                output.write( EOL );
            }
            output.write(OperatorName.BEGIN_INLINE_IMAGE_DATA.getBytes(Charsets.ISO_8859_1));
            output.write( EOL );
            output.write( op.getImageData() );
            output.write( EOL );
            output.write(OperatorName.END_INLINE_IMAGE.getBytes(Charsets.ISO_8859_1));
            output.write( EOL );
        }
        else
        {
            output.write( op.getName().getBytes(Charsets.ISO_8859_1) );
            output.write( EOL );
        }
    }
    else
    {
        throw new IOException( "Error:Unknown type in content stream:" + o );
    }
}
 
Example 17
Source File: ExtractText.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
COSDictionary asDictionary(COSDictionary dictionary, COSName name)
{
    COSBase object = dictionary.getDictionaryObject(name);
    return object instanceof COSDictionary ? (COSDictionary) object : null;
}
 
Example 18
Source File: COSDictionaryMap.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * This will take a COS dictionary and convert it into COSDictionaryMap.  All cos
 * objects will be converted to their primitive form.
 *
 * @param map The COS mappings.
 * @return A standard java map.
 * @throws IOException If there is an error during the conversion.
 */
public static COSDictionaryMap<String, Object> convertBasicTypesToMap( COSDictionary map ) throws IOException
{
    COSDictionaryMap<String, Object> retval = null;
    if( map != null )
    {
        Map<String, Object> actualMap = new HashMap<String, Object>();
        for( COSName key : map.keySet() )
        {
            COSBase cosObj = map.getDictionaryObject( key );
            Object actualObject = null;
            if( cosObj instanceof COSString )
            {
                actualObject = ((COSString)cosObj).getString();
            }
            else if( cosObj instanceof COSInteger )
            {
                actualObject = ((COSInteger)cosObj).intValue();
            }
            else if( cosObj instanceof COSName )
            {
                actualObject = ((COSName)cosObj).getName();
            }
            else if( cosObj instanceof COSFloat )
            {
                actualObject = ((COSFloat)cosObj).floatValue();
            }
            else if( cosObj instanceof COSBoolean )
            {
                actualObject = ((COSBoolean)cosObj).getValue() ? Boolean.TRUE : Boolean.FALSE;
            }
            else
            {
                throw new IOException( "Error:unknown type of object to convert:" + cosObj );
            }
            actualMap.put( key.getName(), actualObject );
        }
        retval = new COSDictionaryMap<String, Object>( actualMap, map );
    }

    return retval;
}
 
Example 19
Source File: COSParser.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
private int checkPagesDictionary(COSDictionary pagesDict, Set<COSObject> set)
{
    // check for kids
    COSBase kids = pagesDict.getDictionaryObject(COSName.KIDS);
    int numberOfPages = 0;
    if (kids instanceof COSArray)
    {
        COSArray kidsArray = (COSArray) kids;
        List<? extends COSBase> kidsList = kidsArray.toList();
        for (COSBase kid : kidsList)
        {
            if (!(kid instanceof COSObject) || set.contains((COSObject) kid))
            {
                kidsArray.remove(kid);
                continue;
            }
            COSObject kidObject = (COSObject) kid;
            COSBase kidBaseobject = kidObject.getObject();
            // object wasn't dereferenced -> remove it
            if (kidBaseobject == null || kidBaseobject.equals(COSNull.NULL))
            {
                LOG.warn("Removed null object " + kid + " from pages dictionary");
                kidsArray.remove(kid);
            }
            else if (kidBaseobject instanceof COSDictionary)
            {
                COSDictionary kidDictionary = (COSDictionary) kidBaseobject;
                COSName type = kidDictionary.getCOSName(COSName.TYPE);
                if (COSName.PAGES.equals(type))
                {
                    // process nested pages dictionaries
                    set.add(kidObject);
                    numberOfPages += checkPagesDictionary(kidDictionary, set);
                }
                else if (COSName.PAGE.equals(type))
                {
                    // count pages
                    numberOfPages++;
                }
            }
        }
    }
    // fix counter
    pagesDict.setInt(COSName.COUNT, numberOfPages);
    return numberOfPages;
}
 
Example 20
Source File: PDFVerify.java    From signer with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testTimeStampOnly() {
	

		String filePath = "caminho do arquivo";
		
		PDDocument document;
		try {
			document = PDDocument.load(new File(filePath));
			Timestamp varTimeStamp = null;

		for (PDSignature sig : document.getSignatureDictionaries()) {
				COSDictionary sigDict = sig.getCOSObject();
				COSString contents = (COSString) sigDict.getDictionaryObject(COSName.CONTENTS);
				FileInputStream fis = new FileInputStream(filePath);
				byte[] buf = null;

				try {
					buf = sig.getSignedContent(fis);
				} finally {
					fis.close();
				}

				CAdESTimeStampSigner varCAdESTimeStampSigner = new CAdESTimeStampSigner();
				varTimeStamp = varCAdESTimeStampSigner.checkTimeStampPDFWithContent(contents.getBytes(), buf);
			}
		if (varTimeStamp != null){
			System.out.println("Carimbo do tempo");
			System.out.println(varTimeStamp.getTimeStampAuthorityInfo());
			System.out.println(varTimeStamp.getSerialNumber());
			System.out.println(varTimeStamp.getCertificates());
			System.out.println(varTimeStamp.getTimeStamp());				
			
		}
		
		
			
					
		assertTrue(true);
		
	} catch (IOException e) {	
		e.printStackTrace();
		assertTrue(false);
	}
}