通过 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>

通過Java在 PDF 檔中添加附件


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

  1. 建立一個新的 Java 專案。
  2. 新增對 Aspose.PDF DLL 的參考。
  3. 建立一個 Document 物件。
  4. 建立一個 FileSpecification 對象,其中包含您要新增的文件和文件描述。
  5. 使用集合的 Add 方法將 FileSpecification 物件加入 Document 物件的 EmbeddedFiles 集合中。
  6. 儲存 PDF 檔案。

將附件添加到 PDF 文件。

// Open a document
Document pdfDocument = new Document(DATA_DIR.resolve("input.pdf").toString());
// Set up a new file to be added as attachment
FileSpecification fileSpecification = new FileSpecification("sample.txt", "Sample text file");
// Add an attachment to document's attachment collection
pdfDocument.getEmbeddedFiles().add(fileSpecification);
// Save the updated document
pdfDocument.save("output.pdf");
pdfDocument.close();