Java を使用した注釈と特殊テキスト
Contents
[
Hide
]
ハイライトテキストの抽出
ページの注釈を反復し、マークされたテキストを読み取る HighlightAnnotation。
- ソース PDF を Document インスタンスで開いてください。
- ターゲットの Page 上の Annotation オブジェクトを反復処理してください。
- 各アノテーションが HighlightAnnotation 型であるかを確認してください。
- 各ハイライトアノテーションからマーキングされたテキストを読み取り、コンソールに出力してください。
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 に渡します。
- ソース PDF を Document インスタンスで開いてください。
- ターゲットの Page 上の Annotation オブジェクトを反復処理してください。
- 注釈をタイプが
Stampのものにフィルタリングしてください。 - TextAbsorber を作成し、スタンプ注釈の外観辞書から通常の外観エントリを要求してください。
- 外観の 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 を使用してください。
- ソース PDF を Document インスタンスで開いてください。
- フラグメントレベルのテキスト分析用に TextFragmentAbsorber を作成してください。
- 対象の Page を訪問し、その TextFragment オブジェクトを収集してください。
- それらのフラグメントを反復処理し、
fragment.getTextState()から上付きおよび下付きのフラグ付きでテキストを読み取ってください。 - 抽出した詳細を出力ファイルに書き込んでください。
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());
}
}