关于angular:ng2-pdf-viewer:获取高亮文本的坐标

ng2-pdf-viewer: get coordinates of highlighted text

我正在将实验性AngularJS应用移植到Angular 4。

该应用程序的主要功能之一是用户可以突出显示PDF中的文本并获得相应于其选择的坐标(PDF为595x842像素矩形,为使事情简单,假设用户只能选择一行文字,然后返回所选内容的最左下角)

为此,AngularJS应用程序使用了第一个函数,该函数可以在响应中找到。如何从pdf.js中的用户选择中检索文本?而且效果很好。更确切地说,我们的代码是

1
2
3
4
5
6
7
8
9
10
function getHightlightCoords() {
    var pageIndex = PDFViewerApplication.pdfViewer.currentPageNumber - 1;
    var page = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
    var pageRect = page.canvas.getClientRects()[0];
    var selectionRects = window.getSelection().getRangeAt(0).getClientRects();
    var selectionRect = selectionRects[0]; //only care about one line, maybe forbid multi line
    var viewport = page.viewport;
    var leftAndBot = viewport.convertToPdfPoint(selectionRect.left - pageRect.x, selectionRect.top - pageRect.y);
    return leftAndBot
}

我一直在尝试使用ng2-pdf-viewer包重现此行为(我无法使用Angular 4来获取pdf.js来提供可搜索的文本),这是一些样板代码,可以快速使ng2-pdf-viewer正常工作: //stackblitz.com/edit/ng2-pdf-viewer

我已经在源代码中浏览了两个小时,以寻找可以从中获取坐标的某种回调,但是到目前为止,我还没有发现任何高级函数可以执行此操作。

有没有人遇到过这一挑战并找到了解决之道?该模块不提供此功能吗?


我最终直接使用在网页PDF上呈现的textLayer而不是库本身进行工作。

我将pdf容器的大小调整为595x842

1
2
3
  <pdf-viewer [src]="src"
              [zoom]="0.75">
  </pdf-viewer>

然后我添加了以下功能

1
2
3
4
5
public onClick(){
    const textLayer = document.getElementsByClassName('TextLayer');
    const x = window.getSelection().getRangeAt(0).getClientRects()[0].left - textLayer[0].getBoundingClientRect().left;
    const y = window.getSelection().getRangeAt(0).getClientRects()[0].top - textLayer[0].getBoundingClientRect().top;
}

正如您可能从函数名称中猜到的那样,我只需单击一个按钮即可调用此函数,但是当然您可以根据需要随意调用它(只要已渲染PDF)

请注意,由于使用PDF.JS呈现文本层的方式,所选的坐标可能与所选PDF上的实际坐标相差几个像素。 使用这种方法,我对此无能为力。 如果有人提出更好的选择,我将批准一个新的答案。