如何使用 Apache PDFBox 使 PDF 文本可选择?

How to make PDF text selectable using Apache PDFBox?

我正在尝试在 JavaFX 上制作的 PDF 阅读应用程序中选择文本。我有 PDF 文件,其中包含带有文本和 OCR 层的屏幕截图。所以我需要像普通观众一样可选择文本。我设置了从页面获取图像,现在想弄清楚如何突出显示文本。

我试过以下方法:

    InputStream is = this.getClass().getResourceAsStream(currentPdf);
    Image convertedImage;
    try {
        PDDocument document = PDDocument.load(is);
        List<PDPage> list = document.getDocumentCatalog().getAllPages();
        PDPage page = list.get(pageNum);
        List annotations = page.getAnnotations();
        PDAnnotationTextMarkup markup = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT);
        markup.setRectangle(new PDRectangle(600, 600));
        markup.setQuadPoints(new float[]{100, 100, 200, 100, 100, 500, 200, 500});
        annotations.add(markup);
        page.setAnnotations(annotations);
        BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 128);
        convertedImage = SwingFXUtils.toFXImage(image, null);
        document.close();
        imageView.setImage(convertedImage);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

但这会导致图像没有任何高光。

我也尝试在堆栈溢出或其他资源中查找信息,但没有找到任何信息。

希望能提供一些 Java 代码示例,它可以使用鼠标突出显示文本。

我使用 ICEpdf 并执行了以下操作:

question.getSelectedBounds()
                .stream()
                .map(Shape::getBounds)
                .forEach(bounds -> {
                    SquareAnnotation squareAnnotation = (SquareAnnotation)
                            AnnotationFactory.buildAnnotation(
                                    pdfController.getPageTree().getLibrary(),
                                    Annotation.SUBTYPE_SQUARE,
                                    bounds);
                    squareAnnotation.setFillColor(true);
                    squareAnnotation.setFillColor(new Color(255, 250, 57, 120));
                    squareAnnotation.setRectangle(bounds);
                    squareAnnotation.setBBox(bounds);
                    squareAnnotation.resetAppearanceStream(null);
                    AbstractAnnotationComponent annotationComponent = AnnotationComponentFactory
                            .buildAnnotationComponent(squareAnnotation, pdfController.getDocumentViewController(),
                                    pageViewComponent, pdfController.getDocumentViewController().getDocumentViewModel());
                    pageViewComponent.addAnnotation(annotationComponent);
                });