通過Java從PDF文檔中提取附件

如何使用 Java以程式設計方式從 PDF 中提取附件。

如何使用 Java 庫提取附件

為了提取附件,我們將使用[Aspose.PDF用於Java](https://products.aspose.com/pdf/java)API,這是一個功能豐富,功能強大且易於使用的Java平台轉換API。您可以直接從 [Maven](https://repository.aspose.com/webapp/#/artifacts/browse/tree/General/repo/com/aspose/aspose-pdf)下載其最新版本,並通過將以下配置添加到 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. 抓取嵌入檔案集合。
  2. 抓取嵌入檔案的計數。 迴圈訪問集合以獲取所有附件。
  3. 檢查參數物件是否包含參數。
  4. 取得附件並寫入檔或流。

將附件提取到 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();