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

时间:2016-01-16 21:34:21

标签: java apache pdf javafx 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代码示例。

1 个答案:

答案 0 :(得分:0)

我使用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);
                });
相关问题