この簡単なチュートリアルでは、Javaを使用してPDF内のテキストを検索および置換する方法について説明します。また、機密情報や分類された情報を除外したいシナリオでも役立ちます。テキストを置き換えるには、** PDF検索をロードし、Java **を使用して置き換えてから、更新されたPDFドキュメントを保存します。
Javaを使用してPDF内のテキストを検索および置換する手順
- テキストを検索して置換するためにAspose.PDF for Javaをインストールするようにアプリケーションを構成します
- テキストを置き換えるためにDocumentクラスを使用して入力PDFファイルをロードします
- TextFragmentAbsorberオブジェクトで検索する必要のあるテキストフレーズを指定します
- テキスト置換オプションを設定し、すべてのページでテキストアブソーバーを受け入れます
- PDFで一致するテキストフレーズのコレクションを作成します
- 見つかったテキストを新しいテキストに置き換えて更新します
- テキストを置き換えた後、出力PDFファイルを保存します
これらの手順は、アプリケーションでJavaがPDFのテキストを置き換える方法をまとめたものです。この操作は、アプリケーションのワークフローに応じて、新しく作成されたPDFファイルと既存のPDFドキュメントに対して実行できます。テキストを置き換えるときに、テキストフォント、前景色、背景色も変更できることに注意してください。
Javaを使用してPDFのテキストを置き換えるコード
import com.aspose.pdf.Document; | |
import com.aspose.pdf.License; | |
public class FindAndReplaceTextInPdfUsingJava { | |
public static void main(String[] args) throws Exception { | |
// Instantiate license to create presentation in HTML | |
License pdfLicense = new License(); | |
pdfLicense.setLicense("Aspose.Pdf.lic"); | |
// Load the input PDF document | |
Document pdfDocument = new Document("Input.pdf"); | |
// Create TextFragmentAbsorber object | |
com.aspose.pdf.TextFragmentAbsorber textFragmentAbsorber = new com.aspose.pdf.TextFragmentAbsorber("Rack"); | |
// Set text replace options | |
com.aspose.pdf.TextReplaceOptions options = new com.aspose.pdf.TextReplaceOptions(); | |
options.setReplaceScope(com.aspose.pdf.TextReplaceOptions.Scope.REPLACE_FIRST); | |
textFragmentAbsorber.setTextReplaceOptions(options); | |
// Accept the text absorber for the entire collection of pages | |
pdfDocument.getPages().accept(textFragmentAbsorber); | |
// Get the extracted fragments in a collection | |
com.aspose.pdf.TextFragmentCollection textFragmentCollection = textFragmentAbsorber.getTextFragments(); | |
// Loop through all text fragments | |
for (com.aspose.pdf.TextFragment textFragment : textFragmentCollection) { | |
// Update the text | |
textFragment.setText("New Rack"); | |
} | |
// Save the updated PDF file | |
pdfDocument.save("Output.pdf"); | |
System.out.println("Done"); | |
} | |
} |
このコードサンプルは、Javaを使用してPDFのテキストを置き換える方法を示しています。さらに、多くのプロパティを操作して、コードスニペットを拡張できます。たとえば、テキストの外観プロパティの更新、特定のページ領域からのテキストの検索、正規表現を使用したテキストの検索、テキスト置換スコープ、テキスト置換戦略などです。
- PDF Java *ベースの環境構成でテキストを置き換えるために、この記事ではコードスニペットについて説明します。ただし、パスワードでPDFを保護する方法を学びたい場合は、Javaでパスワードを使用してPDFを保護する方法の記事を参照してください。