通过 Java 从 PDF 文档中提取附件

如何使用 Java 以编程方式从 PDF 中提取附件。

如何使用 Java 库提取附件

为了提取附件,我们将使用 Aspose.PDF for Java API,这是一款功能丰富、功能强大且易于使用的适用于 Java 平台的转换 API。你可以直接从 Maven 下载它的最新版本,然后通过在 pom.xml 中添加以下配置将其安装在基于 Maven 的项目中。

Repository

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java AP</name>
    <url>https://releases.aspose.com/java/repo/</url>
</repository>

Dependency

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>

从 PDF 中提取附件 Java


你需要 Aspose.PDF for Java 才能在你的环境中试用代码。

1.获取嵌入式文件集合。 1.获取嵌入文件的计数。 1.循环浏览集合以获取所有附件。 1.检查参数对象是否包含参数。 1.获取附件并写入文件或流。

将附件提取到 PDF 文档。


    // Open document
    Document pdfDocument = new Document(_dataDir+"input.pdf");
    // Get particular embedded file
    FileSpecification fileSpecification = pdfDocument.getEmbeddedFiles().get_Item(1);
    // Get the file properties
    System.out.printf("Name: - " + fileSpecification.getName());
    System.out.printf("\nDescription: - " + fileSpecification.getDescription());
    System.out.printf("\nMime Type: - " + fileSpecification.getMIMEType());
    // Get attachment form PDF file
    try {
    InputStream input = fileSpecification.getContents();
    File file = new File(fileSpecification.getName());
    // Create path for file from pdf
    file.getParentFile().mkdirs();
    // Create and extract file from pdf
    java.io.FileOutputStream output = new java.io.FileOutputStream(fileSpecification.getName(), true);
    byte[] buffer = new byte[4096];
    int n = 0;
    while (-1 != (n = input.read(buffer)))
        output.write(buffer, 0, n);
    // Close InputStream object
    input.close();
    output.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    // Close Document object
    pdfDocument.dispose();