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

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

Introduction

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

Prototype

public void setEmbeddedFiles(PDEmbeddedFilesNameTreeNode ef) 

Source Link

Document

Set the named embedded files that are associated with this document.

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));
    }/*  w w w . j a  v a2 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:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

License:EUPL

/**
 * Adds an attachment to a PDF/*from  w w w. ja  v a 2s .  c o  m*/
 * 
 * @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

/**
 * Append an attachment to the PDF. This method will only work for attachments with unique names
 * /*from  w ww .j  a  va2s  . 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  w  w .j  av a  2s  . 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

/**
 * Remove all embedded file attachments from the document
 * //from  ww  w  .ja  va 2s. c  om
 * @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:io.konik.carriage.pdfbox.PDFBoxInvoiceAppender.java

License:Open Source License

private static void setNamesDictionary(PDDocument doc, PDEmbeddedFilesNameTreeNode fileNameTreeNode) {
    PDDocumentCatalog documentCatalog = doc.getDocumentCatalog();
    PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(documentCatalog);
    namesDictionary.setEmbeddedFiles(fileNameTreeNode);
    documentCatalog.setNames(namesDictionary);
}

From source file:org.mustangproject.ZUGFeRD.ZUGFeRDExporter.java

License:Open Source License

/**
 * Embeds an external file (generic - any type allowed) in the PDF.
 *
 * @param doc          PDDocument to attach the file to.
 * @param filename     name of the file that will become attachment name in the PDF
 * @param relationship how the file relates to the content, e.g. "Alternative"
 * @param description  Human-readable description of the file content
 * @param subType      type of the data e.g. could be "text/xml" - mime like
 * @param data         the binary data of the file/attachment
 * @throws java.io.IOException//ww  w  . j  a va  2  s  .c  o  m
 */
public void PDFAttachGenericFile(PDDocument doc, String filename, String relationship, String description,
        String subType, byte[] data) throws IOException {
    fileAttached = true;

    PDComplexFileSpecification fs = new PDComplexFileSpecification();
    fs.setFile(filename);

    COSDictionary dict = fs.getCOSObject();
    dict.setName("AFRelationship", relationship);
    dict.setString("UF", filename);
    dict.setString("Desc", description);

    ByteArrayInputStream fakeFile = new ByteArrayInputStream(data);
    PDEmbeddedFile ef = new PDEmbeddedFile(doc, fakeFile);
    ef.setSubtype(subType);
    ef.setSize(data.length);
    ef.setCreationDate(new GregorianCalendar());

    ef.setModDate(GregorianCalendar.getInstance());

    fs.setEmbeddedFile(ef);

    // In addition make sure the embedded file is set under /UF
    dict = fs.getCOSObject();
    COSDictionary efDict = (COSDictionary) dict.getDictionaryObject(COSName.EF);
    COSBase lowerLevelFile = efDict.getItem(COSName.F);
    efDict.setItem(COSName.UF, lowerLevelFile);

    // now add the entry to the embedded file tree and set in the document.
    PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
    PDEmbeddedFilesNameTreeNode efTree = names.getEmbeddedFiles();
    if (efTree == null) {
        efTree = new PDEmbeddedFilesNameTreeNode();
    }

    Map<String, PDComplexFileSpecification> namesMap = new HashMap<>();

    Map<String, PDComplexFileSpecification> oldNamesMap = efTree.getNames();
    if (oldNamesMap != null) {
        for (String key : oldNamesMap.keySet()) {
            namesMap.put(key, oldNamesMap.get(key));
        }
    }
    namesMap.put(filename, fs);
    efTree.setNames(namesMap);

    names.setEmbeddedFiles(efTree);
    doc.getDocumentCatalog().setNames(names);

    // AF entry (Array) in catalog with the FileSpec
    COSArray cosArray = (COSArray) doc.getDocumentCatalog().getCOSObject().getItem("AF");
    if (cosArray == null) {
        cosArray = new COSArray();
    }
    cosArray.add(fs);
    COSDictionary dict2 = doc.getDocumentCatalog().getCOSObject();
    COSArray array = new COSArray();
    array.add(fs.getCOSObject()); // see below
    dict2.setItem("AF", array);
    doc.getDocumentCatalog().getCOSObject().setItem("AF", cosArray);
}

From source file:org.pdfmetamodifier.IOHelper.java

License:Apache License

/**
 * Add new Attached (embedded) files./*from   w w w  . j  a va2  s. c  o m*/
 * 
 * @param pdfFile
 *            Source PDF file.
 * @param attachmentFiles
 *            Files that will be attached (embedded).
 * @throws IOException
 */
/*
 * See:
 *      https://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/EmbeddedFiles.java?view=markup
 */
public static void addAttachments(final File pdfFile, final List<File> attachmentFiles) throws IOException {
    PDDocument document = null;
    try {
        // Read PDF file.
        document = PDDocument.load(pdfFile);
        if (document.isEncrypted()) {
            throw new IOException("Document is encrypted.");
        }

        // Embedded (attached) files are stored in a named tree.
        final PDEmbeddedFilesNameTreeNode root = new PDEmbeddedFilesNameTreeNode();
        final List<PDEmbeddedFilesNameTreeNode> kids = new ArrayList<PDEmbeddedFilesNameTreeNode>();
        root.setKids(kids);

        // Add the tree to the document catalog.
        final PDDocumentNameDictionary namesDictionary = new PDDocumentNameDictionary(
                document.getDocumentCatalog());
        namesDictionary.setEmbeddedFiles(root);
        document.getDocumentCatalog().setNames(namesDictionary);

        // For all Embedded (attached) files.
        for (File file : attachmentFiles) {
            final String filename = file.getName();

            // First create the file specification, which holds the Embedded (attached) file.
            final PDComplexFileSpecification complexFileSpecification = new PDComplexFileSpecification();
            complexFileSpecification.setFile(filename);

            // Create a dummy file stream, this would probably normally be a FileInputStream.
            final ByteArrayInputStream fileStream = new ByteArrayInputStream(Files.readAllBytes(file.toPath()));
            final PDEmbeddedFile embededFile = new PDEmbeddedFile(document, fileStream);
            complexFileSpecification.setEmbeddedFile(embededFile);

            // Create a new tree node and add the Embedded (attached) file.
            final PDEmbeddedFilesNameTreeNode embeddedFilesNameTree = new PDEmbeddedFilesNameTreeNode();
            embeddedFilesNameTree.setNames(Collections.singletonMap(filename, complexFileSpecification));

            // Add the new node as kid to the root node.
            kids.add(embeddedFilesNameTree);
        }

        // Create temporary PDF file for result.
        if (TEMP_PDF.exists()) {
            TEMP_PDF.delete();
        }

        // Save result to temporary PDF file.
        document.save(TEMP_PDF);

        // Replace original PDF file.
        pdfFile.delete();
        Files.move(Paths.get(TEMP_PDF.toURI()), Paths.get(pdfFile.toURI()));
    } finally {
        if (document != null) {
            document.close();
        }
    }
}

From source file:pdfbox.PDFA3FileAttachment.java

License:Apache License

private void attachSampleFile(PDDocument doc) throws IOException {
    PDEmbeddedFilesNameTreeNode efTree = new PDEmbeddedFilesNameTreeNode();

    // first create the file specification, which holds the embedded file

    PDComplexFileSpecification fs = new PDComplexFileSpecification();
    fs.setFile("Test.txt");
    COSDictionary dict = fs.getCOSDictionary();
    // Relation "Source" for linking with eg. catalog
    dict.setName("AFRelationship", "Alternative");
    // dict.setName("AFRelationship", "Source");

    dict.setString("UF", "Test.txt");
    // fs.put(new PdfName("AFRelationship"), new PdfName("Source"));

    String payload = "This is a test";

    InputStream is = new ByteArrayInputStream(payload.getBytes());

    PDEmbeddedFile ef = new PDEmbeddedFile(doc, is);
    // set some of the attributes of the embedded file

    ef.setSubtype("text/plain");
    // ef.setFile(fs);
    // ef.getStream().setItem(COSName.UF, fs);

    ef.setModDate(GregorianCalendar.getInstance());

    // PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(writer,
    // src.getAbsolutePath(), src.getName(), null, false, "image/jpeg",
    // fileParameter);

    // fs.put(new PdfName("AFRelationship"), new PdfName("Source"));

    ef.setSize(payload.length());/*from   w  w  w.j  av  a2s  . c om*/
    ef.setCreationDate(new GregorianCalendar());
    fs.setEmbeddedFile(ef);

    // now add the entry to the embedded file tree and set in the document.
    efTree.setNames(Collections.singletonMap("My first attachment", fs));

    /**
     * Validating file "RE-20131206_22.pdf" for conformance level pdfa-3a The
     * key UF is required but missing. The key AFRelationship is required but
     * missing. File specification 'Test.txt' not associated with an object.
     */
    // attachments are stored as part of the "names" dictionary in the document
    // catalog
    PDDocumentCatalog catalog = doc.getDocumentCatalog();

    PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
    names.setEmbeddedFiles(efTree);
    catalog.setNames(names);

    // // AF entry (Array) in catalog with the FileSpec
    // PDAcroForm pdAcroForm = new PDAcroForm(doc);
    // COSArray cosArray = new COSArray();
    // cosArray.add(fs);
    // catalog.setItem("AF", cosArray);

}