JavaでPDFファイルを読む方法

この簡単なチュートリアルでは、JavaでPDFファイルを読み取る方法について説明します。これには、** PDFファイルを読み取るためのJavaコード**が含まれています。最初に、JavaのPDFからテキストを文字列に読み取り、次にPDFファイルからすべての画像をフェッチしてディスクにJPGJavaでPDFを読み取るためにサードパーティのツールをインストールする必要はありません。

JavaでPDFファイルを読み取る手順

  1. PDFファイルを読み取るためにMavenリポジトリーを使用して、プロジェクトにAspose.PDFを構成します
  2. サンプルPDFファイルをDocumentクラスオブジェクトにロードします
  3. PDFファイルからテキスト全体を読み取ることができるTextAbsorberクラスオブジェクトをインスタンス化します
  4. TextAbsorberクラスオブジェクトを使用して、ロードされたファイルからPDFテキストを読み取ります
  5. PDFファイルから読み取ったテキスト全体をコンソールに表示します
  6. 画像にアクセスするためにPDFファイルのすべてのページを繰り返し処理します
  7. 各ページの画像コレクションのすべての画像を解析し、ディスクに保存します

この簡単なステップバイステップのチュートリアルでは、最初にターゲットPDFファイルをロードしてから、PDF内のすべてのページでテキストを検索できるTextAbsorberクラスオブジェクトを開始します。このテキスト全体は、要件に従って表示または処理できる文字列に返されます。同様に、画像コレクション内のすべての画像を解析し、このチュートリアルでJPGとして保存したので、任意の形式でディスクに保存できます。

Javaを使用してPDFを読み取るコード

import com.aspose.pdf.License;
import com.aspose.pdf.Document;
import com.aspose.pdf.Page;
import com.aspose.pdf.TextAbsorber;
import com.aspose.pdf.XImage;
public class HowToReadPDFFileInJava {
public static void main(String[] args) throws Exception {//main() function for HowToReadPDFFileInJava
// Instantiate the license to remove trial version restrictions while reading the PDF file
License license = new License();
license.setLicense("Aspose.PDF.lic");
// Load the PDF file from which text and images are to be read
Document pdf = new Document("Input.pdf");
// 1. Read entire text from the PDF file
// Instantiate a TextAbsorber Class object to read Text from PDF file
TextAbsorber textAbsorberObject = new TextAbsorber();
// Call PageCollection.accept() method to let TextAbsorber find text in PDF Pages
pdf.getPages().accept(textAbsorberObject);
// Write the extracted text from the sample PDF to console
System.out.println(textAbsorberObject.getText());
// 2. Extract images from PDF file
int imageCount = 1;
// Iterate through all the PDF pages to access images collection and save them on the disc
for (Page pdfPage : pdf.getPages())
{
// Iterate through images collection in the PDF file
for (XImage image : pdfPage.getResources().getImages())
{
java.io.FileOutputStream outputImageFromPdfFile = new java.io.FileOutputStream(pdfPage.getNumber() + "-"+ imageCount+"-output.jpg");
// Save each image in the PDF file images collection to a JPG file
image.save(outputImageFromPdfFile);
outputImageFromPdfFile.close();
imageCount++;
}
// Reset image index
imageCount = 1;
}
}
}

このサンプルコードでは、Page.getResources()のTextAbsorberクラスとgetImages()関数を使用して、Javaを使用してPDFを読み取ります。 TextAbsorberオブジェクトは、PDFPageCollectionのaccept関数によってテキストを読み取るために使用されます。一方、getResources()コレクションのgetImages()関数は、ページ上のすべての画像を返します。

JavaでPDFを読み取るためのこれらの手順は、Windows、Linux、macOSなどの任意のオペレーティングシステムで実行できることに注意してください。 PDFファイルの操作について詳しく知りたい場合は、Javaを使用してPDFでブックマークを読み取る方法の記事を参照してください。

 日本語