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

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

Introduction

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

Prototype

COSName NAME

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

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();//from  ww  w.  j a v a 2 s.  co m
    } 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:cz.muni.pdfjbim.PdfImageExtractor.java

License:Apache License

/**
 * This method extracts images by going through all COSObjects pointed from xref table
 * @param is input stream containing PDF file
 * @param prefix output basename for images
 * @param password password for access to PDF if needed
 * @param pagesToProcess list of pages which should be processed if null given => processed all pages
 *      -- not working yet/*from www .j a  v  a  2 s.c om*/
 * @param binarize -- enables processing of nonbitonal images as well (LZW is still not
 *      processed because of output with inverted colors)
 * @throws PdfRecompressionException if problem to extract images from PDF
 */
public void extractImagesUsingPdfParser(InputStream is, String prefix, String password,
        Set<Integer> pagesToProcess, Boolean binarize) throws PdfRecompressionException {
    // checking arguments and setting appropriate variables
    if (binarize == null) {
        binarize = false;
    }

    log.debug("Extracting images (binarize set to {})", binarize);

    InputStream inputStream = null;
    if (password != null) {
        try (ByteArrayOutputStream decryptedOutputStream = new ByteArrayOutputStream()) {
            PdfReader reader = new PdfReader(is, password.getBytes(StandardCharsets.UTF_8));
            PdfStamper stamper = new PdfStamper(reader, decryptedOutputStream);
            if (stamper != null) {
                stamper.close();
            }
            inputStream = new ByteArrayInputStream(decryptedOutputStream.toByteArray());
        } catch (DocumentException ex) {
            throw new PdfRecompressionException(ex);
        } catch (IOException ex) {
            throw new PdfRecompressionException("Reading file caused exception", ex);
        }
    } else {
        inputStream = is;
    }

    PDFParser parser = null;
    COSDocument doc = null;
    try {
        parser = new PDFParser(inputStream);
        parser.parse();
        doc = parser.getDocument();

        List<COSObject> objs = doc.getObjectsByType(COSName.XOBJECT);
        if (objs != null) {
            for (COSObject obj : objs) {
                COSBase subtype = obj.getItem(COSName.SUBTYPE);
                if (subtype.toString().equalsIgnoreCase("COSName{Image}")) {
                    COSBase imageObj = obj.getObject();
                    COSBase cosNameObj = obj.getItem(COSName.NAME);
                    String key;
                    if (cosNameObj != null) {
                        String cosNameKey = cosNameObj.toString();
                        int startOfKey = cosNameKey.indexOf("{") + 1;
                        key = cosNameKey.substring(startOfKey, cosNameKey.length() - 1);
                    } else {
                        key = "im0";
                    }
                    int objectNum = obj.getObjectNumber().intValue();
                    int genNum = obj.getGenerationNumber().intValue();
                    PDXObjectImage image = (PDXObjectImage) PDXObjectImage.createXObject(imageObj);

                    PDStream pdStr = new PDStream(image.getCOSStream());
                    List<COSName> filters = pdStr.getFilters();

                    log.debug("Detected image with color depth: {} bits", image.getBitsPerComponent());
                    if (filters == null) {
                        continue;
                    }
                    log.debug("Detected filters: {}", filters.toString());

                    if ((image.getBitsPerComponent() > 1) && (!binarize)) {
                        log.info("It is not a bitonal image => skipping");
                        continue;
                    }

                    // at this moment for preventing bad output (bad coloring) from LZWDecode filter
                    if (filters.contains(COSName.LZW_DECODE)) {
                        log.info("This is LZWDecoded => skipping");
                        continue;
                    }

                    if (filters.contains(COSName.FLATE_DECODE)) {
                        log.debug("FlateDecoded image detected");
                    }

                    if (filters.contains(COSName.JBIG2_DECODE)) {
                        if (skipJBig2Images) {
                            log.warn("Allready compressed according to JBIG2 standard => skipping");
                            continue;
                        } else {
                            log.debug("JBIG2 image detected");
                        }
                    }

                    // detection of unsupported filters by pdfBox library
                    if (filters.contains(COSName.JPX_DECODE)) {
                        log.warn("Unsupported filter JPXDecode => skipping");
                        continue;
                    }

                    String name = getUniqueFileName(prefix, image.getSuffix());
                    log.info("Writing image: {}", name);
                    image.write2file(name);

                    PdfImageInformation pdfImageInfo = new PdfImageInformation(key, image.getWidth(),
                            image.getHeight(), objectNum, genNum);
                    originalImageInformations.add(pdfImageInfo);

                    namesOfImages.add(name + "." + image.getSuffix());

                }
            }
        }
    } catch (IOException ex) {
        Tools.deleteFilesFromList(namesOfImages);
        throw new PdfRecompressionException("Unable to parse PDF document", ex);
    } catch (Exception ex) {
        Tools.deleteFilesFromList(namesOfImages);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                throw new PdfRecompressionException(ex);
            }
        }
    }
}

From source file:cz.muni.pdfjbim.PdfImageProcessor.java

License:Apache License

/**
 * This method extracts images by going through all COSObjects pointed from xref table
 * @param is input stream containing PDF file
 * @param password password for access to PDF if needed
 * @param pagesToProcess list of pages which should be processed if null given => processed all pages
 *      -- not working yet//from  w  ww . j  a v a 2 s  .c o  m
 * @param binarize -- enables processing of nonbitonal images as well (LZW is still not
 *      processed because of output with inverted colors)
 * @throws PdfRecompressionException if problem to extract images from PDF
 */
public void extractImagesUsingPdfParser(InputStream is, String prefix, String password,
        Set<Integer> pagesToProcess, Boolean binarize) throws PdfRecompressionException {
    // checking arguments and setting appropriate variables
    if (binarize == null) {
        binarize = false;
    }

    InputStream inputStream = null;
    if (password != null) {
        try {
            ByteArrayOutputStream decryptedOutputStream = null;
            PdfReader reader = new PdfReader(is, password.getBytes());
            PdfStamper stamper = new PdfStamper(reader, decryptedOutputStream);
            stamper.close();
            inputStream = new ByteArrayInputStream(decryptedOutputStream.toByteArray());
        } catch (DocumentException ex) {
            throw new PdfRecompressionException(ex);
        } catch (IOException ex) {
            throw new PdfRecompressionException("Reading file caused exception", ex);
        }
    } else {
        inputStream = is;
    }

    PDFParser parser = null;
    COSDocument doc = null;
    try {
        parser = new PDFParser(inputStream);
        parser.parse();
        doc = parser.getDocument();

        List<COSObject> objs = doc.getObjectsByType(COSName.XOBJECT);
        if (objs != null) {
            for (COSObject obj : objs) {
                COSBase subtype = obj.getItem(COSName.SUBTYPE);
                if (subtype.toString().equalsIgnoreCase("COSName{Image}")) {
                    COSBase imageObj = obj.getObject();
                    COSBase cosNameObj = obj.getItem(COSName.NAME);
                    String key;
                    if (cosNameObj != null) {
                        String cosNameKey = cosNameObj.toString();
                        int startOfKey = cosNameKey.indexOf("{") + 1;
                        key = cosNameKey.substring(startOfKey, cosNameKey.length() - 1);
                    } else {
                        key = "im0";
                    }
                    int objectNum = obj.getObjectNumber().intValue();
                    int genNum = obj.getGenerationNumber().intValue();
                    PDXObjectImage image = (PDXObjectImage) PDXObjectImage.createXObject(imageObj);

                    PDStream pdStr = new PDStream(image.getCOSStream());
                    List filters = pdStr.getFilters();

                    if ((image.getBitsPerComponent() > 1) && (!binarize)) {
                        log.info("It is not a bitonal image => skipping");

                        continue;
                    }

                    // at this moment for preventing bad output (bad coloring) from LZWDecode filter
                    if (filters.contains(COSName.LZW_DECODE.getName())) {
                        log.info("This is LZWDecoded => skipping");
                        continue;

                    }

                    // detection of unsupported filters by pdfBox library
                    if (filters.contains("JBIG2Decode")) {
                        log.warn("Allready compressed according to JBIG2 standard => skipping");
                        continue;
                    }

                    if (filters.contains("JPXDecode")) {
                        log.warn("Unsupported filter JPXDecode => skipping");
                        continue;
                    }

                    String name = getUniqueFileName(prefix, image.getSuffix());
                    log.info("Writing image:" + name);
                    image.write2file(name);

                    PdfImageInformation pdfImageInfo = new PdfImageInformation(key, image.getWidth(),
                            image.getHeight(), objectNum, genNum);
                    originalImageInformations.add(pdfImageInfo);

                    namesOfImages.add(name + "." + image.getSuffix());

                }
                //                    }
            }
        }
    } catch (IOException ex) {
        throw new PdfRecompressionException("Unable to parse PDF document", ex);
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                throw new PdfRecompressionException(ex);
            }
        }
    }
}

From source file:test.be.fedict.eid.applet.PdfSpikeTest.java

License:Open Source License

@Test
public void testSignPDF() throws Exception {
    // create a sample PDF file
    Document document = new Document();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);

    document.open();//from  w  ww.ja  va 2 s .co m

    Paragraph titleParagraph = new Paragraph("This is a test.");
    titleParagraph.setAlignment(Paragraph.ALIGN_CENTER);
    document.add(titleParagraph);

    document.newPage();
    Paragraph textParagraph = new Paragraph("Hello world.");
    document.add(textParagraph);

    document.close();

    File tmpFile = File.createTempFile("test-", ".pdf");
    LOG.debug("tmp file: " + tmpFile.getAbsolutePath());
    FileUtils.writeByteArrayToFile(tmpFile, baos.toByteArray());

    // eID
    PcscEid pcscEid = new PcscEid(new TestView(), new Messages(Locale.getDefault()));
    if (false == pcscEid.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEid.waitForEidPresent();
    }

    List<X509Certificate> signCertificateChain = pcscEid.getSignCertificateChain();
    Certificate[] certs = new Certificate[signCertificateChain.size()];
    for (int idx = 0; idx < certs.length; idx++) {
        certs[idx] = signCertificateChain.get(idx);
    }

    // open the pdf
    FileInputStream pdfInputStream = new FileInputStream(tmpFile);
    File signedTmpFile = File.createTempFile("test-signed-", ".pdf");
    PdfReader reader = new PdfReader(pdfInputStream);
    FileOutputStream pdfOutputStream = new FileOutputStream(signedTmpFile);
    PdfStamper stamper = PdfStamper.createSignature(reader, pdfOutputStream, '\0', null, true);

    // add extra page
    Rectangle pageSize = reader.getPageSize(1);
    int pageCount = reader.getNumberOfPages();
    int extraPageIndex = pageCount + 1;
    stamper.insertPage(extraPageIndex, pageSize);

    // calculate unique signature field name
    int signatureNameIndex = 1;
    String signatureName;
    AcroFields existingAcroFields = reader.getAcroFields();
    List<String> existingSignatureNames = existingAcroFields.getSignatureNames();
    do {
        signatureName = "Signature" + signatureNameIndex;
        signatureNameIndex++;
    } while (existingSignatureNames.contains(signatureName));
    LOG.debug("new unique signature name: " + signatureName);

    PdfSignatureAppearance signatureAppearance = stamper.getSignatureAppearance();
    signatureAppearance.setCrypto(null, certs, null, PdfSignatureAppearance.SELF_SIGNED);
    signatureAppearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
    signatureAppearance.setReason("PDF Signature Test");
    signatureAppearance.setLocation("Belgium");
    signatureAppearance.setVisibleSignature(new Rectangle(54, 440, 234, 566), extraPageIndex, signatureName);
    signatureAppearance.setExternalDigest(new byte[128], new byte[20], "RSA");
    signatureAppearance.preClose();

    byte[] content = IOUtils.toByteArray(signatureAppearance.getRangeStream());
    byte[] hash = MessageDigest.getInstance("SHA-1").digest(content);
    byte[] signatureBytes = pcscEid.sign(hash, "SHA-1");
    pcscEid.close();

    PdfSigGenericPKCS sigStandard = signatureAppearance.getSigStandard();
    PdfPKCS7 signature = sigStandard.getSigner();
    signature.setExternalDigest(signatureBytes, hash, "RSA");
    PdfDictionary dictionary = new PdfDictionary();
    dictionary.put(PdfName.CONTENTS, new PdfString(signature.getEncodedPKCS1()).setHexWriting(true));
    signatureAppearance.close(dictionary);

    LOG.debug("signed tmp file: " + signedTmpFile.getAbsolutePath());

    // verify the signature
    reader = new PdfReader(new FileInputStream(signedTmpFile));
    AcroFields acroFields = reader.getAcroFields();
    ArrayList<String> signatureNames = acroFields.getSignatureNames();
    for (String signName : signatureNames) {
        LOG.debug("signature name: " + signName);
        LOG.debug("signature covers whole document: " + acroFields.signatureCoversWholeDocument(signName));
        LOG.debug("document revision " + acroFields.getRevision(signName) + " of "
                + acroFields.getTotalRevisions());
        PdfPKCS7 pkcs7 = acroFields.verifySignature(signName);
        Calendar signDate = pkcs7.getSignDate();
        LOG.debug("signing date: " + signDate.getTime());
        LOG.debug("Subject: " + PdfPKCS7.getSubjectFields(pkcs7.getSigningCertificate()));
        LOG.debug("Document modified: " + !pkcs7.verify());
        Certificate[] verifyCerts = pkcs7.getCertificates();
        for (Certificate certificate : verifyCerts) {
            X509Certificate x509Certificate = (X509Certificate) certificate;
            LOG.debug("cert subject: " + x509Certificate.getSubjectX500Principal());
        }
    }

    /*
     * Reading the signature using Apache PDFBox.
     */
    PDDocument pdDocument = PDDocument.load(signedTmpFile);
    COSDictionary trailer = pdDocument.getDocument().getTrailer();
    /*
     * PDF Reference - third edition - Adobe Portable Document Format -
     * Version 1.4 - 3.6.1 Document Catalog
     */
    COSDictionary documentCatalog = (COSDictionary) trailer.getDictionaryObject(COSName.ROOT);

    /*
     * 8.6.1 Interactive Form Dictionary
     */
    COSDictionary acroForm = (COSDictionary) documentCatalog.getDictionaryObject(COSName.ACRO_FORM);

    COSArray fields = (COSArray) acroForm.getDictionaryObject(COSName.FIELDS);
    for (int fieldIdx = 0; fieldIdx < fields.size(); fieldIdx++) {
        COSDictionary field = (COSDictionary) fields.getObject(fieldIdx);
        String fieldType = field.getNameAsString("FT");
        if ("Sig".equals(fieldType)) {
            COSDictionary signatureDictionary = (COSDictionary) field.getDictionaryObject(COSName.V);
            /*
             * TABLE 8.60 Entries in a signature dictionary
             */
            COSString signatoryName = (COSString) signatureDictionary.getDictionaryObject(COSName.NAME);
            if (null != signatoryName) {
                LOG.debug("signatory name: " + signatoryName.getString());
            }
            COSString reason = (COSString) signatureDictionary.getDictionaryObject(COSName.REASON);
            if (null != reason) {
                LOG.debug("reason: " + reason.getString());
            }
            COSString location = (COSString) signatureDictionary.getDictionaryObject(COSName.LOCATION);
            if (null != location) {
                LOG.debug("location: " + location.getString());
            }
            Calendar signingTime = signatureDictionary.getDate(COSName.M);
            if (null != signingTime) {
                LOG.debug("signing time: " + signingTime.getTime());
            }
            String signatureHandler = signatureDictionary.getNameAsString(COSName.FILTER);
            LOG.debug("signature handler: " + signatureHandler);
        }
    }
}