本教程演示如何将嵌入文件添加到 PDF 文档。
Maven 依赖项
我们使用 Apache Maven 来管理我们的项目依赖项。确保以下依赖项驻留在类路径中。
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.8</version>
</dependency>
Apache PDFBox 将嵌入文件添加到 PDF 文档
首先我们创建一个PDComplexFileSpecification
保存嵌入文件的 . 为了保持简单,我们创建了一个带有一些基本文本输入的虚拟文件流。我们创建了PDEmbeddedFile
包含虚拟文件的文件,我们可以使用它来设置一些可选参数。嵌入文件存储在一个命名的树类PDEmbeddedFilesNameTreeNode
中。最后,我们将树添加到文档目录中。
package com.memorynotfound.pdf.pdfbox;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class AddEmbeddedFiles {
public static void main(String[] args) throws Exception{
try (final PDDocument doc = new PDDocument()){
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
contentStream.beginText();
contentStream.setFont(PDType1Font.HELVETICA, 12);
contentStream.newLineAtOffset(100, 700);
contentStream.showText("Go to Document -> File Attachments to View Embedded Files");
contentStream.endText();
contentStream.close();
// embedded files are stored in a named tree
PDEmbeddedFilesNameTreeNode efTree = new PDEmbeddedFilesNameTreeNode();
// first create the file specification, which holds the embedded file
PDComplexFileSpecification fs = new PDComplexFileSpecification();
fs.setFile("example-document.txt");
// create a dummy file stream, this would probably normally be a FileInputStream
byte[] data = "This is the contents of the embedded file".getBytes("ISO-8859-1");
ByteArrayInputStream fakeFile = new ByteArrayInputStream(data);
// now lets some of the optional parameters
PDEmbeddedFile ef = new PDEmbeddedFile(doc, fakeFile);
ef.setSubtype("text/plain");
ef.setSize(data.length);
ef.setCreationDate(Calendar.getInstance());
fs.setEmbeddedFile(ef);
// create a new tree node and add the embedded file
PDEmbeddedFilesNameTreeNode treeNode = new PDEmbeddedFilesNameTreeNode();
treeNode.setNames(Collections.singletonMap("My first attachment", fs));
// add the new node as kid to the root node
List<PDEmbeddedFilesNameTreeNode> kids = new ArrayList<PDEmbeddedFilesNameTreeNode>();
kids.add(treeNode);
efTree.setKids(kids);
// add the tree to the document catalog
PDDocumentNameDictionary names = new PDDocumentNameDictionary(doc.getDocumentCatalog());
names.setEmbeddedFiles(efTree);
doc.getDocumentCatalog().setNames(names);
doc.save(new File("/tmp/embedded-file.pdf"));
} catch (IOException e){
System.err.println("Exception while trying to create pdf document - " + e);
}
}
}
输出
当我们运行这个应用程序时,会生成一个 PDF 文档。如果我们使用 Acrobat Reader 打开文档,我们可以在左栏中看到该文档现在是嵌入文件的骄傲所有者。