JavaでPDFをテキストに変換する方法

この短いチュートリアルでは、入力されたPDFドキュメントをロードしてText形式で保存することにより、PDFをJavaでテキストに変換する方法について詳しく説明します。さらに、** Java PDFからテキストへのコンバーター**を使用して、ソースPDFファイルと比較してフォーマットの有無にかかわらず出力テキストが必要かどうかを制御するようにカスタマイズできます。

JavaでPDFをテキストに変換する手順

  1. MavenリポジトリからAspose.PDFへの参照を追加してアプリケーションを構成し、PDFをテキストファイルに変換します
  2. PDFをテキストファイルに変換するために、Documentクラスオブジェクトを含む入力PDFファイルをロードします
  3. TextAbsorberクラスのオブジェクトを作成して、テキスト抽出オプションを設定します
  4. 抽出したテキストをテキストファイルに書き込みます

上記の手順は、* PDF to TextJava*ベースのコンバーターアプリケーションを開発するプロセスを詳しく説明しています。最初のステップでは、Documentクラスインスタンスを使用して入力PDFドキュメントをロードし、テキストを書式設定するかどうかを選択します。最後に、テキスト文字列を使用してファイルに書き込んだり、要件に応じてさらに処理したりできます。

JavaでPDFをテキストに変換するコード

import com.aspose.pdf.Document;
import com.aspose.pdf.License;
import com.aspose.pdf.TextAbsorber;
import com.aspose.pdf.TextExtractionOptions;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.nio.file.Files;
public class ConvertPdfToTextInJava {
public static void main(String[] args) throws Exception { // main method to convert a PDF document to Text file
// Instantiate the license to avoid trial limitations while converting the PDF to a text file
License asposePdfLicenseText = new License();
asposePdfLicenseText.setLicense("Aspose.pdf.lic");
// Load the source PDF file that is to be converted to Text file
Document convertPDFDocumentToText = new Document("input.pdf");
// Instantiate a TextAbsorber class object for converting PDF to Text
TextAbsorber textAbsorber = new TextAbsorber(new TextExtractionOptions(TextExtractionOptions.TextFormattingMode.Pure));
// Call the Accept method exposed by the TextAbsorber class
convertPDFDocumentToText.getPages().accept(textAbsorber);
// Read the text as string
String ExtractedText = textAbsorber.getText();
// Create the BufferedWriter object to open the file
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("SampleOutput.txt")));
// Write extracted contents to the file
writer.write(ExtractedText);
// Close writer
writer.close();
System.out.println("Done");
}
}

このサンプルコードは、TextAbsorberクラスのようなさまざまなオプションを使用して完全に制御できる* Java convert PDF to text *を使用することにより、ソースPDFのシェーディングされたテキストを個別のテキストとして変換するオプションを提供するTextSearchOptionsを使用できる複数のコンストラクターがあることを示しています。同様に、バインドされたページ内でのみテキストを検索するようにフラグを設定したり、すべてのページで指定された領域からのみテキストを検索するように長方形を設定したりできます。

ここでは、コードスニペットとともにJavaでPDFをテキストに変換する方法を学びました。 PDFをWordに変換するプロセスを学びたい場合は、JavaでPDFをWordに変換する方法の記事を参照してください。

 日本語