Example usage for org.apache.pdfbox.cos COSName CONTENTS

List of usage examples for org.apache.pdfbox.cos COSName CONTENTS

Introduction

In this page you can find the example usage for org.apache.pdfbox.cos COSName CONTENTS.

Prototype

COSName CONTENTS

To view the source code for org.apache.pdfbox.cos COSName CONTENTS.

Click Source Link

Usage

From source file:ShowSignature.java

License:Apache License

private void showSignature(String[] args) throws IOException, CertificateException {
    if (args.length != 2) {
        usage();// ww w. j  a  va 2s  . c om
    } else {
        String password = args[0];
        String infile = args[1];
        PDDocument document = null;
        try {
            document = PDDocument.load(new File(infile), password);
            if (!document.isEncrypted()) {
                System.err.println("Warning: Document is not encrypted.");
            }

            COSDictionary trailer = document.getDocument().getTrailer();
            COSDictionary root = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT);
            COSDictionary acroForm = (COSDictionary) root.getDictionaryObject(COSName.ACRO_FORM);
            COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS);
            for (int i = 0; i < fields.size(); i++) {
                COSDictionary field = (COSDictionary) fields.getObject(i);
                COSName type = field.getCOSName(COSName.FT);
                if (COSName.SIG.equals(type)) {
                    COSDictionary cert = (COSDictionary) field.getDictionaryObject(COSName.V);
                    if (cert != null) {
                        System.out.println("Certificate found");
                        System.out.println("Name=" + cert.getDictionaryObject(COSName.NAME));
                        System.out.println("Modified=" + cert.getDictionaryObject(COSName.M));
                        COSName subFilter = (COSName) cert.getDictionaryObject(COSName.SUB_FILTER);
                        if (subFilter != null) {
                            if (subFilter.getName().equals("adbe.x509.rsa_sha1")) {
                                COSString certString = (COSString) cert
                                        .getDictionaryObject(COSName.getPDFName("Cert"));
                                byte[] certData = certString.getBytes();
                                CertificateFactory factory = CertificateFactory.getInstance("X.509");
                                ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
                                Collection<? extends Certificate> certs = factory
                                        .generateCertificates(certStream);
                                System.out.println("certs=" + certs);
                            } else if (subFilter.getName().equals("adbe.pkcs7.sha1")) {
                                COSString certString = (COSString) cert.getDictionaryObject(COSName.CONTENTS);
                                byte[] certData = certString.getBytes();
                                CertificateFactory factory = CertificateFactory.getInstance("X.509");
                                ByteArrayInputStream certStream = new ByteArrayInputStream(certData);
                                Collection<? extends Certificate> certs = factory
                                        .generateCertificates(certStream);
                                System.out.println("certs=" + certs);
                            } else {
                                System.err.println("Unknown certificate type:" + subFilter);
                            }
                        } else {
                            throw new IOException("Missing subfilter for cert dictionary");
                        }
                    } else {
                        System.out.println("Signature found, but no certificate");
                    }
                }
            }
        } finally {
            if (document != null) {
                document.close();
            }
        }
    }
}

From source file:com.aaasec.sigserv.csspsupport.pdfbox.modifications.CsCOSWriter.java

License:Apache License

/**
 * visitFromDictionary method comment./*from ww  w  .  j a  va  2 s  .  c o  m*/
 *
 * @param obj The object that is being visited.
 *
 * @throws COSVisitorException If there is an exception while visiting this
 * object.
 *
 * @return null
 */
public Object visitFromDictionary(COSDictionary obj) throws COSVisitorException {
    try {
        getStandardOutput().write(DICT_OPEN);
        getStandardOutput().writeEOL();
        for (Map.Entry<COSName, COSBase> entry : obj.entrySet()) {
            COSBase value = entry.getValue();
            if (value != null) {
                entry.getKey().accept(this);
                getStandardOutput().write(SPACE);
                if (value instanceof COSDictionary) {
                    COSDictionary dict = (COSDictionary) value;

                    // write all XObjects as direct objects, this will save some size
                    COSBase item = dict.getItem(COSName.XOBJECT);
                    if (item != null) {
                        item.setDirect(true);
                    }
                    item = dict.getItem(COSName.RESOURCES);
                    if (item != null) {
                        item.setDirect(true);
                    }

                    if (dict.isDirect()) {
                        // If the object should be written direct, we need
                        // to pass the dictionary to the visitor again.
                        visitFromDictionary(dict);
                    } else {
                        addObjectToWrite(dict);
                        writeReference(dict);
                    }
                } else if (value instanceof COSObject) {
                    COSBase subValue = ((COSObject) value).getObject();
                    if (subValue instanceof COSDictionary || subValue == null) {
                        addObjectToWrite(value);
                        writeReference(value);
                    } else {
                        subValue.accept(this);
                    }
                } else {
                    // If we reach the pdf signature, we need to determinate the position of the
                    // content and byterange
                    if (reachedSignature && COSName.CONTENTS.equals(entry.getKey())) {
                        signaturePosition = new int[2];
                        signaturePosition[0] = (int) getStandardOutput().getPos();
                        value.accept(this);
                        signaturePosition[1] = (int) getStandardOutput().getPos();
                    } else if (reachedSignature && COSName.BYTERANGE.equals(entry.getKey())) {
                        byterangePosition = new int[2];
                        byterangePosition[0] = (int) getStandardOutput().getPos() + 1;
                        value.accept(this);
                        byterangePosition[1] = (int) getStandardOutput().getPos() - 1;
                        reachedSignature = false;
                    } else {
                        value.accept(this);
                    }
                }
                getStandardOutput().writeEOL();

            } else {
                //then we won't write anything, there are a couple cases
                //were the value of an entry in the COSDictionary will
                //be a dangling reference that points to nothing
                //so we will just not write out the entry if that is the case
            }
        }
        getStandardOutput().write(DICT_CLOSE);
        getStandardOutput().writeEOL();
        return null;
    } catch (IOException e) {
        throw new COSVisitorException(e);
    }
}

From source file:PDF.RotatePDF.java

private void transformPage(PDDocument document, PDPage page, AffineTransform at)
        throws IOException, COSVisitorException {
    PDRectangle cropBox = page.findCropBox();
    float xOffset = (cropBox.getUpperRightX() + cropBox.getLowerLeftX()) / 2f;
    float yOffset = (cropBox.getUpperRightY() + cropBox.getLowerLeftY()) / 2f;
    AffineTransform transform = AffineTransform.getTranslateInstance(xOffset, yOffset);
    transform.concatenate(at);//ww  w. j  a va 2  s  .co m
    transform.concatenate(AffineTransform.getTranslateInstance(-xOffset, -yOffset));

    PDPageContentStream stream = new PDPageContentStream(document, page, true, false);
    stream.concatenate2CTM(transform);
    stream.close();

    COSBase contents = page.getCOSDictionary().getDictionaryObject(COSName.CONTENTS);
    if (contents instanceof COSStreamArray) {
        COSStreamArray contentsArray = (COSStreamArray) contents;
        COSArray newArray = new COSArray();
        newArray.add(contentsArray.get(contentsArray.getStreamCount() - 1));

        for (int i = 0; i < contentsArray.getStreamCount() - 1; i++) {
            newArray.add(contentsArray.get(i));
        }

        COSStreamArray newStreamArray = new COSStreamArray(newArray);
        page.getCOSDictionary().setItem(COSName.CONTENTS, newStreamArray);
    }
}

From source file:pdfbox.SignatureVerifier.java

License:Apache License

public Map<String, SignatureResult> extractSignatures(File infile) throws IOException, CertificateException,
        NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException {
    Map<String, SignatureResult> result = new HashMap<>();

    try (PDDocument document = PDDocument.load(infile)) {
        for (PDSignature sig : document.getSignatureDictionaries()) {
            COSDictionary sigDict = sig.getCOSObject();
            COSString contents = (COSString) sigDict.getDictionaryObject(COSName.CONTENTS);

            // download the signed content
            byte[] buf;
            try (FileInputStream fis = new FileInputStream(infile)) {
                buf = sig.getSignedContent(fis);
            }//from w w w .j  ava  2 s .  co  m

            System.out.println("Signature found");
            System.out.println("Name:     " + sig.getName());
            System.out.println("Modified: " + sdf.format(sig.getSignDate().getTime()));
            String subFilter = sig.getSubFilter();
            if (subFilter != null) {
                switch (subFilter) {
                case "adbe.pkcs7.detached": // COSName.ADBE_PKCS7_DETACHED
                    result.put(sig.getName(), verifyPKCS7(buf, contents, sig));

                    //TODO check certificate chain, revocation lists, timestamp...
                    break;
                case "adbe.pkcs7.sha1": // COSName.ADBE_PKCS7_SHA1
                {
                    // example: PDFBOX-1452.pdf
                    //COSString certString = (COSString) sigDict.getDictionaryObject(
                    //        COSName.CONTENTS);
                    byte[] certData = contents.getBytes();
                    Collection<? extends Certificate> certs = getCertificates(certData);
                    System.out.println("certs=" + certs);
                    byte[] hash = MessageDigest.getInstance("SHA1").digest(buf);
                    result.put(sig.getName(), verifyPKCS7(hash, contents, sig));

                    //TODO check certificate chain, revocation lists, timestamp...
                    break;
                }
                case "adbe.x509.rsa_sha1": // COSName.ADBE_PKCS7_SHA1
                {
                    // example: PDFBOX-2693.pdf
                    COSString certString = (COSString) sigDict.getDictionaryObject(COSName.getPDFName("Cert"));
                    byte[] certData = certString.getBytes();
                    Collection<? extends Certificate> certs = getCertificates(certData);
                    System.out.println("certs=" + certs);

                    //TODO verify signature
                    throw new IOException(subFilter + " verification not supported");
                    //break;
                }
                default:
                    throw new IOException("Unknown certificate type: " + subFilter);
                    //break;
                }
            } else {
                throw new IOException("Missing subfilter for cert dictionary");
            }
        }
    } catch (CMSException | OperatorCreationException ex) {
        throw new IOException(ex);
    }

    return result;
}

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  ww .ja v  a  2  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++;
    }
}