Java を使用した注釈と特殊テキスト

ハイライトテキストの抽出

ページの注釈を反復し、マークされたテキストを読み取る HighlightAnnotation。

  1. ソース PDF を Document インスタンスで開いてください。
  2. ターゲットの Page 上の Annotation オブジェクトを反復処理してください。
  3. 各アノテーションが HighlightAnnotation 型であるかを確認してください。
  4. 各ハイライトアノテーションからマーキングされたテキストを読み取り、コンソールに出力してください。
public static void extractHighlightedText(Path inputFile) {
    try (Document document = new Document(inputFile.toString())) {
        for (Annotation annotation : document.getPages().get_Item(1).getAnnotations()) {
            if (annotation instanceof HighlightAnnotation) {
                HighlightAnnotation highlightAnnotation = (HighlightAnnotation) annotation;
                System.out.println(highlightAnnotation.getMarkedText());
            }
        }
    }
}

スタンプ注釈からテキストの抽出

スタンプ注釈から標準外観ストリームを読み取り、それをそのまま TextAbsorber に渡します。

  1. ソース PDF を Document インスタンスで開いてください。
  2. ターゲットの Page 上の Annotation オブジェクトを反復処理してください。
  3. 注釈をタイプが Stamp のものにフィルタリングしてください。
  4. TextAbsorber を作成し、スタンプ注釈の外観辞書から通常の外観エントリを要求してください。
  5. 外観の XForm を訪問し、抽出したテキストを印刷してください。
public static void extractStampText(Path inputFile) {
    try (Document document = new Document(inputFile.toString())) {
        for (Annotation annotation : document.getPages().get_Item(1).getAnnotations()) {
            if (annotation.getAnnotationType() == AnnotationType.Stamp) {
                TextAbsorber absorber = new TextAbsorber();
                Object[] xforms = new Object[1];
                if (annotation.getAppearance().tryGetValue("N", xforms) && xforms[0] instanceof XForm) {
                    absorber.visit((XForm) xforms[0]);
                    System.out.println(absorber.getText());
                }
            }
        }
    }
}

上付き文字と下付き文字のテキストの詳細の抽出

各フラグメントについて、抽出したテキストと上付きまたは下付きフラグの両方を必要とする場合は、TextFragmentAbsorber を使用してください。

  1. ソース PDF を Document インスタンスで開いてください。
  2. フラグメントレベルのテキスト分析用に TextFragmentAbsorber を作成してください。
  3. 対象の Page を訪問し、その TextFragment オブジェクトを収集してください。
  4. それらのフラグメントを反復処理し、fragment.getTextState() から上付きおよび下付きのフラグ付きでテキストを読み取ってください。
  5. 抽出した詳細を出力ファイルに書き込んでください。
public static void extractSuperSubDetails(Path inputFile, Path outputFile, int pageNumber) throws Exception {
    try (Document document = new Document(inputFile.toString())) {
        TextFragmentAbsorber absorber = new TextFragmentAbsorber();
        document.getPages().get_Item(pageNumber).accept(absorber);
        StringBuilder details = new StringBuilder();
        for (TextFragment fragment : absorber.getTextFragments()) {
            details.append("Text: '").append(fragment.getText())
                    .append("' | Superscript: ").append(fragment.getTextState().isSuperscript())
                    .append(" | Subscript: ").append(fragment.getTextState().isSubscript())
                    .append(System.lineSeparator());
        }
        Files.writeString(outputFile, details.toString());
    }
}