Example usage for org.apache.pdfbox.pdmodel PDDocumentNameDictionary PDDocumentNameDictionary

List of usage examples for org.apache.pdfbox.pdmodel PDDocumentNameDictionary PDDocumentNameDictionary

Introduction

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

Prototype

public PDDocumentNameDictionary(PDDocumentCatalog cat) 

Source Link

Document

Constructor.

Usage

From source file:algorithm.PDFFileAttacher.java

License:Apache License

private void attachAll(File outputFile, List<File> payloadList) throws IOException {
    PDDocument document = PDDocument.load(outputFile);
    List<PDComplexFileSpecification> fileSpecifications = getFileSpecifications(document, payloadList);
    PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(document.getDocumentCatalog());
    PDEmbeddedFilesNameTreeNode filesTree = namesDictionary.getEmbeddedFiles();
    filesTree = new PDEmbeddedFilesNameTreeNode();
    Map<String, COSObjectable> fileMap = new HashMap<String, COSObjectable>();
    for (int i = 0; i < fileSpecifications.size(); i++) {
        fileMap.put("PericlesMetadata-" + i, fileSpecifications.get(i));
    }//from w  w  w  .j ava 2  s . co m
    filesTree.setNames(fileMap);
    namesDictionary.setEmbeddedFiles(filesTree);
    document.getDocumentCatalog().setNames(namesDictionary);
    try {
        document.save(outputFile);
    } catch (COSVisitorException e) {
    }
    document.close();
}

From source file:algorithm.PDFFileAttacher.java

License:Apache License

@Override
public List<RestoredFile> restore(File originalPdf) throws IOException {
    RestoredFile copiedPdf = getRestoredCarrier(originalPdf);
    List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>();
    PDDocument document = PDDocument.load(copiedPdf);
    PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(document.getDocumentCatalog());
    PDEmbeddedFilesNameTreeNode filesTree = namesDictionary.getEmbeddedFiles();
    if (filesTree != null) {
        int i = 0;
        while (true) {
            PDComplexFileSpecification fileSpecification = (PDComplexFileSpecification) filesTree
                    .getValue("PericlesMetadata-" + i);
            if (fileSpecification == null) {
                break;
            }/*from   w w  w .  j  a  v a  2s.co  m*/
            File oldAttachedFile = new File(fileSpecification.getFile());
            RestoredFile restoredPayload = new RestoredFile(RESTORED_DIRECTORY + oldAttachedFile.getName());
            PDEmbeddedFile embeddedFile = fileSpecification.getEmbeddedFile();
            InputStream inputStream = embeddedFile.createInputStream();
            FileOutputStream outputStream = new FileOutputStream(restoredPayload);
            IOUtils.copy(inputStream, outputStream);
            removeBuggyLineEnding(restoredPayload);
            restoredPayload.wasPayload = true;
            restoredPayload.checksumValid = true;
            restoredPayload.restorationNote = "Checksum wasn't calculated, because this algorithm isn't using restoration metadata. The original payload file survives the encapsulation with this algorithm.";
            restoredFiles.add(restoredPayload);
            i++;
        }
    }
    document.close();
    copiedPdf.wasCarrier = true;
    copiedPdf.checksumValid = false;
    copiedPdf.restorationNote = "Checksum can't be valid, because attached payload files can't be removed from carrier.";
    restoredFiles.add(copiedPdf);
    for (RestoredFile file : restoredFiles) {
        file.algorithm = this;
        for (RestoredFile relatedFile : restoredFiles) {
            if (file != relatedFile) {
                file.relatedFiles.add(relatedFile);
            }
        }
    }
    return restoredFiles;
}

From source file:dev.ztgnrw.ExtractEmbeddedFiles.java

License:Apache License

/**
 * This is the main method./*from  ww  w  .ja v a  2s .co  m*/
 *
 * @param args The command line arguments.
 *
 * @throws IOException If there is an error parsing the document.
 */
public static void extractEmbeddedFiles(String file) throws IOException {

    PDDocument document = null;
    try {
        File pdfFile = new File(file);
        String filePath = pdfFile.getParent() + System.getProperty("file.separator");
        document = PDDocument.load(pdfFile);
        PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(document.getDocumentCatalog());
        PDEmbeddedFilesNameTreeNode efTree = namesDictionary.getEmbeddedFiles();
        if (efTree != null) {
            Map<String, PDComplexFileSpecification> names = efTree.getNames();
            if (names != null) {
                extractFiles(names, filePath);
            } else {
                List<PDNameTreeNode<PDComplexFileSpecification>> kids = efTree.getKids();
                for (PDNameTreeNode<PDComplexFileSpecification> node : kids) {
                    names = node.getNames();
                    extractFiles(names, filePath);
                }
            }
        }

        // extract files from annotations
        for (PDPage page : document.getPages()) {
            for (PDAnnotation annotation : page.getAnnotations()) {
                if (annotation instanceof PDAnnotationFileAttachment) {
                    PDAnnotationFileAttachment annotationFileAttachment = (PDAnnotationFileAttachment) annotation;
                    PDComplexFileSpecification fileSpec = (PDComplexFileSpecification) annotationFileAttachment
                            .getFile();
                    PDEmbeddedFile embeddedFile = getEmbeddedFile(fileSpec);
                    extractFile(filePath, fileSpec.getFilename(), embeddedFile);
                }
            }
        }

    } finally {
        if (document != null) {
            document.close();
        }
    }

}

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

License:EUPL

/**
 * Adds an attachment to a PDF//from w  w  w. j  a v a  2 s. c  om
 * 
 * @param pdf the PDF to attach to
 * @param attachment to attachment
 * @param name the name given to the attachment
 * @return the PDF with attachment
 */
public static byte[] attach(final byte[] pdf, final byte[] attachment, final String name) {
    PDDocument doc = null;
    try {

        PDEmbeddedFilesNameTreeNode efTree = new PDEmbeddedFilesNameTreeNode();

        InputStream isDoc = new ByteArrayInputStream(pdf);
        doc = PDDocument.load(isDoc);
        PDComplexFileSpecification fs = new PDComplexFileSpecification();
        fs.setFile("Test.txt");
        InputStream isAttach = new ByteArrayInputStream(attachment);
        PDEmbeddedFile ef = new PDEmbeddedFile(doc, isAttach);
        ef.setSize(attachment.length);
        ef.setCreationDate(Calendar.getInstance());
        fs.setEmbeddedFile(ef);

        Map<String, PDComplexFileSpecification> efMap = new HashMap<String, PDComplexFileSpecification>();
        efMap.put(name, fs);
        efTree.setNames(efMap);
        PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
        names.setEmbeddedFiles(efTree);
        doc.getDocumentCatalog().setNames(names);
        return toByteArray(doc);
    } catch (Exception e) {
        LOGGER.error("Error attaching.", e);
        throw new SigningException(e);
    } finally {
        closeQuietly(doc);
    }
}

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

License:EUPL

/**
 * Extracts an attachment from a PDF/*from   w  w w  .  j  a v  a  2s. co 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  . ja  v  a 2s  .c o  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./*from w  ww .  jav a  2 s.  co  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
 * //from   ww 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 v  a2 s .com
 * @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
 * /*w w  w. j  a va 2  s . c  o  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);
}