다중 열 PDF에서 텍스트 추출 개선

다중 열 레이아웃에는 읽기 순서와 추출 품질을 향상시키기 위해 추가 처리가 필요한 경우가 많습니다.

글꼴 크기를 줄인 후 텍스트 추출

이 기술은 텍스트 조각 글꼴 크기를 업데이트하고 조정된 문서를 메모리에 저장한 다음 변환된 결과에서 텍스트를 추출합니다.

  1. Document 인스턴스에서 소스 PDF를 여세요.
  2. TextFragmentAbsorber를 만들고 모든 문서 페이지를 방문하여 TextFragment 개체를 수집하세요.
  3. 추출 전에 텍스트 조각을 순회하고 각 글꼴 크기를 지정된 비율로 줄여 조밀한 열 레이아웃을 정규화하세요.
  4. 조정된 Document를 메모리 내 바이트 스트림에 저장하세요.
  5. 해당 메모리 버퍼에서 두 번째 Document를 다시 여세요.
  6. TextAbsorber를 생성하고 변환된 문서의 모든 페이지를 방문하여 추출된 텍스트를 출력 파일에 쓰세요.
public static void extractTextReduceFont(Path inputFile, Path outputFile, double reduceRatio) throws Exception {
    try (Document document = new Document(inputFile.toString())) {
        TextFragmentAbsorber fragmentAbsorber = new TextFragmentAbsorber();
        document.getPages().accept(fragmentAbsorber);
        for (TextFragment fragment : fragmentAbsorber.getTextFragments()) {
            fragment.getTextState().setFontSize((float) (fragment.getTextState().getFontSize() * reduceRatio));
        }

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        document.save(stream);
        try (Document document2 = new Document(new ByteArrayInputStream(stream.toByteArray()))) {
            TextAbsorber textAbsorber = new TextAbsorber();
            document2.getPages().accept(textAbsorber);
            Files.writeString(outputFile, textAbsorber.getText());
        }
    }
}

축척 비율을 사용하여 텍스트 추출

순수 서식 모드에서 TextExtractionOptions를 사용하고 열이 많은 레이아웃의 배율을 조정하세요.

  1. Document 인스턴스에서 소스 PDF를 여세요.
  2. 전체 문서 추출을 위해 TextAbsorber를 만드세요.
  3. 레이아웃에 맞는 추출 동작이 사용되도록 순수 서식 모드에서 TextExtractionOptions를 만드세요.
  4. 페이지를 방문하기 전에 스케일 팩터를 설정하고 흡수체에 추출 옵션을 적용하세요.
  5. 모든 문서 페이지를 방문하고 추출된 텍스트를 출력 파일에 쓰세요.
public static void extractTextScaleFactor(Path inputFile, Path outputFile, double scaleFactor) throws Exception {
    try (Document document = new Document(inputFile.toString())) {
        TextAbsorber textAbsorber = new TextAbsorber();
        TextExtractionOptions extractionOptions =
                new TextExtractionOptions(TextExtractionOptions.TextFormattingMode.Pure);
        extractionOptions.setScaleFactor(scaleFactor);
        textAbsorber.setExtractionOptions(extractionOptions);
        document.getPages().accept(textAbsorber);
        Files.writeString(outputFile, textAbsorber.getText());
    }
}