Java を介して PDF ドキュメントから添付ファイルを抽出

Java を使用してPDFから添付ファイルをプログラムで抽出する方法

Java ライブラリを使用して添付ファイルを抽出する方法

添付ファイルを抽出するために、Javaプラットフォーム用の機能が豊富で強力で使いやすい変換APIである Aspose.PDF for 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();