Example usage for org.apache.pdfbox.pdmodel PDDocument getDocumentCatalog

List of usage examples for org.apache.pdfbox.pdmodel PDDocument getDocumentCatalog

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocument getDocumentCatalog.

Prototype

public PDDocumentCatalog getDocumentCatalog() 

Source Link

Document

This will get the document CATALOG.

Usage

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

License:EUPL

/**
 * Extracts an attachment from a PDF/*from   www.j  a  v a  2  s.  c o  m*/
 * 
 * @param pdf the PDF; this is unaffected by the method
 * @param name the name of the attachment
 * @return the attachment
 */
public static byte[] extractAttachment(final byte[] pdf, final String name) {
    PDDocument doc = null;
    try {
        InputStream is = new ByteArrayInputStream(pdf);
        doc = PDDocument.load(is);
        PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(doc.getDocumentCatalog());
        PDEmbeddedFilesNameTreeNode efTree = namesDictionary.getEmbeddedFiles();
        Map<String, COSObjectable> names = efTree.getNames();
        byte[] data = null;
        if (names != null) {
            PDComplexFileSpecification attach = (PDComplexFileSpecification) names.get(name);
            data = attach.getEmbeddedFile().getByteArray();
        }

        // Remove the \r\n added by PdfBox (PDDocument.saveIncremental).
        if (data != null) {
            String newString = new String(data, "UTF-8");
            while (newString.endsWith("\r\n")) {
                newString = newString.replaceAll("\\r\\n$", "");
                data = newString.getBytes(Charset.forName("UTF-8"));
            }
        }

        return data;

    } catch (IOException e) {
        LOGGER.error("Error detaching.", e);
        throw new SigningException(e);
    } finally {
        closeQuietly(doc);
    }
}

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

License:EUPL

/**
 * Append an attachment to the PDF. This method will only work for attachments with unique names
 * //from w  w w .j a  va 2s.  co m
 * @param pdf the PDF document
 * @param attachment the bytes for the attachment
 * @param fileName the name of the attachment
 */
public static byte[] appendAttachment(byte[] pdf, byte[] attachment, String fileName) {

    try {

        InputStream is = new ByteArrayInputStream(pdf);
        PDDocument doc = PDDocument.load(is);
        Map<String, byte[]> attachments = getAttachments(doc);
        doc = removeAllAttachments(doc);
        attachments.put(fileName, attachment);
        PDDocumentNameDictionary names2 = new PDDocumentNameDictionary(doc.getDocumentCatalog());
        Map<String, COSObjectable> efMap = new HashMap<String, COSObjectable>();
        for (String key : attachments.keySet()) {
            PDComplexFileSpecification afs = new PDComplexFileSpecification();
            afs.setFile(key);
            InputStream isa = new ByteArrayInputStream(attachments.get(key));
            PDEmbeddedFile ef = new PDEmbeddedFile(doc, isa);
            ef.setSize(attachments.get(key).length);
            afs.setEmbeddedFile(ef);
            efMap.put(key, afs);
        }

        PDEmbeddedFilesNameTreeNode efTree = new PDEmbeddedFilesNameTreeNode();
        efTree.setNames(efMap);
        names2.setEmbeddedFiles(efTree);
        doc.getDocumentCatalog().setNames(names2);
        return toByteArray(doc);
    } catch (COSVisitorException e) {
        throw new SigningException(e);
    } catch (IOException e) {
        throw new SigningException(e);
    }

}

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

License:EUPL

/**
 * Append attachments to the PDF.// ww w .  j  a v  a  2s  .  c  o m
 * 
 * @param pdf the PDF document
 * @param attachments the bytes for the attachment
 * @param ignore the names to be ignored
 */
public static byte[] appendAttachment(byte[] pdf, Map<String, byte[]> attachments, String... ignore) {

    try {
        List<String> ignoreList = Arrays.asList(ignore);
        InputStream is = new ByteArrayInputStream(pdf);
        PDDocument doc = PDDocument.load(is);
        PDEmbeddedFilesNameTreeNode tree = new PDDocumentNameDictionary(doc.getDocumentCatalog())
                .getEmbeddedFiles();
        if (tree == null) {
            tree = new PDEmbeddedFilesNameTreeNode();
            PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
            names.setEmbeddedFiles(tree);
            doc.getDocumentCatalog().setNames(names);
        }
        Map<String, COSObjectable> temp = tree.getNames();
        Map<String, COSObjectable> map = new HashMap<String, COSObjectable>();
        if (temp != null) {
            map.putAll(temp);
        }
        for (String fileName : attachments.keySet()) {
            if (ignoreList.contains(fileName)) {
                continue;
            }
            byte[] bytes = attachments.get(fileName);
            if (bytes == null) {
                continue;
            }
            PDComplexFileSpecification cosObject = new PDComplexFileSpecification();
            cosObject.setFile(fileName);
            InputStream isa = new ByteArrayInputStream(bytes);
            PDEmbeddedFile ef = new PDEmbeddedFile(doc, isa);
            ef.setSize(bytes.length);
            cosObject.setEmbeddedFile(ef);
            map.put(fileName, cosObject);
        }
        tree.setNames(map);
        return toByteArray(doc);
    } catch (COSVisitorException e) {
        throw new SigningException(e);
    } catch (IOException e) {
        throw new SigningException(e);
    }
}

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

License:EUPL

/**
 * Get a map of file name/byte for all embedded files in the pdf
 * //  w w w.j a v a 2  s .  com
 * @param doc the pdf
 * @return the map of attachments
 * @throws IOException
 */
private static Map<String, byte[]> getAttachments(PDDocument doc) throws IOException {
    PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
    Map<String, byte[]> attachments = new LinkedHashMap<String, byte[]>();
    if (names.getEmbeddedFiles() != null && names.getEmbeddedFiles().getNames() != null) {
        for (String key : names.getEmbeddedFiles().getNames().keySet()) {
            attachments.put(key, ((PDComplexFileSpecification) names.getEmbeddedFiles().getNames().get(key))
                    .getEmbeddedFile().getByteArray());
        }
    }
    return attachments;
}

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

License:EUPL

/**
 * Get a map of file name/byte for all embedded files in the pdf
 * //from   w w w . j  a  va 2 s  .  c o  m
 * @param doc the pdf
 * @return the map of attachments
 * @throws IOException
 */
private static Set<String> getAttachmentsNames(PDDocument doc) throws IOException {
    PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
    Set<String> attachments = new HashSet<String>();
    if (names.getEmbeddedFiles() != null && names.getEmbeddedFiles().getNames() != null) {
        for (String key : names.getEmbeddedFiles().getNames().keySet()) {
            attachments.add(key);
        }
    }
    return attachments;
}

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

License:EUPL

/**
 * Remove all embedded file attachments from the document
 * //from  w  w  w . ja v  a  2 s.  co  m
 * @param doc the document
 * @return the document with
 * @throws COSVisitorException
 * @throws IOException
 */
private static PDDocument removeAllAttachments(PDDocument doc) throws COSVisitorException, IOException {
    PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(doc.getDocumentCatalog());
    namesDictionary.setEmbeddedFiles(null);
    doc.getDocumentCatalog().setNames(namesDictionary);
    InputStream is = new ByteArrayInputStream(toByteArray(doc));
    return PDDocument.load(is);
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxSignatureService.java

License:Open Source License

private List<PdfSignatureOrDocTimestampInfo> getSignatures(CertificatePool validationCertPool,
        byte[] originalBytes) {
    List<PdfSignatureOrDocTimestampInfo> signatures = new ArrayList<PdfSignatureOrDocTimestampInfo>();
    ByteArrayInputStream bais = null;
    PDDocument doc = null;
    try {//  w  w w .j  a  va  2 s.c om

        bais = new ByteArrayInputStream(originalBytes);
        doc = PDDocument.load(bais);

        List<PDSignature> pdSignatures = doc.getSignatureDictionaries();
        if (CollectionUtils.isNotEmpty(pdSignatures)) {
            logger.debug("{} signature(s) found", pdSignatures.size());

            PdfDict catalog = new PdfBoxDict(doc.getDocumentCatalog().getCOSDictionary(), doc);
            PdfDssDict dssDictionary = PdfDssDict.extract(catalog);

            for (PDSignature signature : pdSignatures) {
                String subFilter = signature.getSubFilter();
                byte[] cms = signature.getContents(originalBytes);

                if (StringUtils.isEmpty(subFilter) || ArrayUtils.isEmpty(cms)) {
                    logger.warn("Wrong signature with empty subfilter or cms.");
                    continue;
                }

                byte[] signedContent = signature.getSignedContent(originalBytes);
                int[] byteRange = signature.getByteRange();

                PdfSignatureOrDocTimestampInfo signatureInfo = null;
                if (PdfBoxDocTimeStampService.SUB_FILTER_ETSI_RFC3161.getName().equals(subFilter)) {
                    boolean isArchiveTimestamp = false;

                    // LT or LTA
                    if (dssDictionary != null) {
                        // check is DSS dictionary already exist
                        if (isDSSDictionaryPresentInPreviousRevision(
                                getOriginalBytes(byteRange, signedContent))) {
                            isArchiveTimestamp = true;
                        }
                    }

                    signatureInfo = new PdfBoxDocTimestampInfo(validationCertPool, signature, dssDictionary,
                            cms, signedContent, isArchiveTimestamp);
                } else {
                    signatureInfo = new PdfBoxSignatureInfo(validationCertPool, signature, dssDictionary, cms,
                            signedContent);
                }

                if (signatureInfo != null) {
                    signatures.add(signatureInfo);
                }
            }
            Collections.sort(signatures, new PdfSignatureOrDocTimestampInfoComparator());
            linkSignatures(signatures);

            for (PdfSignatureOrDocTimestampInfo sig : signatures) {
                logger.debug("Signature " + sig.uniqueId() + " found with byteRange "
                        + Arrays.toString(sig.getSignatureByteRange()) + " (" + sig.getSubFilter() + ")");
            }
        }

    } catch (Exception e) {
        logger.warn("Cannot analyze signatures : " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(doc);
    }

    return signatures;
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxSignatureService.java

License:Open Source License

private boolean isDSSDictionaryPresentInPreviousRevision(byte[] originalBytes) {
    ByteArrayInputStream bais = null;
    PDDocument doc = null;
    PdfDssDict dssDictionary = null;/*from ww w. j a v  a  2 s . c  om*/
    try {
        bais = new ByteArrayInputStream(originalBytes);
        doc = PDDocument.load(bais);
        List<PDSignature> pdSignatures = doc.getSignatureDictionaries();
        if (CollectionUtils.isNotEmpty(pdSignatures)) {
            PdfDict catalog = new PdfBoxDict(doc.getDocumentCatalog().getCOSDictionary(), doc);
            dssDictionary = PdfDssDict.extract(catalog);
        }
    } catch (Exception e) {
        logger.warn("Cannot check in previous revisions if DSS dictionary already exist : " + e.getMessage(),
                e);
    } finally {
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(doc);
    }

    return dssDictionary != null;
}

From source file:eu.europa.esig.dss.pdf.pdfbox.PdfBoxSignatureService.java

License:Open Source License

@Override
public void addDssDictionary(InputStream inputStream, OutputStream outpuStream,
        List<DSSDictionaryCallback> callbacks) {
    File toSignFile = null;/*from  w  w w . j a v  a 2 s  .co m*/
    File signedFile = null;
    FileInputStream fis = null;
    PDDocument pdDocument = null;
    try {
        toSignFile = DSSPDFUtils.getFileFromPdfData(inputStream);
        pdDocument = PDDocument.load(toSignFile);

        signedFile = File.createTempFile("sd-dss-", "-signed.pdf");

        final FileOutputStream fileOutputStream = DSSPDFUtils.getFileOutputStream(toSignFile, signedFile);

        if (CollectionUtils.isNotEmpty(callbacks)) {
            final COSDictionary cosDictionary = pdDocument.getDocumentCatalog().getCOSDictionary();
            cosDictionary.setItem("DSS", buildDSSDictionary(callbacks));
            cosDictionary.setNeedToBeUpdate(true);
        }

        if (pdDocument.getDocumentId() == null) {
            pdDocument.setDocumentId(0L);
        }
        pdDocument.saveIncremental(inputStream, fileOutputStream);

        fis = new FileInputStream(signedFile);
        IOUtils.copy(fis, outpuStream);
    } catch (Exception e) {
        throw new DSSException(e);
    } finally {
        IOUtils.closeQuietly(pdDocument);
        IOUtils.closeQuietly(fis);
        DSSUtils.delete(toSignFile);
        DSSUtils.delete(signedFile);
    }
}

From source file:fi.riista.feature.permit.invoice.pdf.PermitHarvestInvoicePdfBuilder.java

private PermitHarvestInvoicePdfBuilder(final PDDocument pdfDocument, final PermitHarvestInvoicePdfModel model) {
    this.pdfDocument = Objects.requireNonNull(pdfDocument);
    this.pdfPage = Objects.requireNonNull(pdfDocument.getPage(0));
    this.acroForm = Objects.requireNonNull(pdfDocument.getDocumentCatalog().getAcroForm());
    this.model = Objects.requireNonNull(model);
}