kkFileView基于pdf.js实现多词高亮

发布于:2024-04-17 ⋅ 阅读:(35) ⋅ 点赞:(0)

参考文档:

1.文件文档在线预览转换解决方案和应用

2.kkfileview预览pdf格式文件,实现多关键词高亮和定位_kkfileview+高亮方案-CSDN博客
3.PDF.js实现搜索多个不同的关键词高亮显示效果

最终效果:

需求描述:

预览文件时,在文档中高亮显示搜索的文字,并实现分词、多词搜索

如:需要搜索"项目",文件中需要高亮所有的 "项" 和 "目" 

解决代码:

1. kkFileView属于开源,我们是基于kkFileView的代码修改实现。

需要的可以kkFileView---gitee地址中下载。

2. 根据参考文档1和2,基本可以实现高亮,但不能分开高亮,"项" 和 "目" 。

3. 根据参考文档3,实现分开高亮。

在文件  resources/static/pdfjs/web/viewer.js  中添加代码:

  • _initializeViewerComponents 方法中:

    // 添加代码
    // 自定义搜索关键词----------------------------------------
    this.searchKeywords = keyword => {
      if (typeof PDFViewerApplication !== 'undefined') {
        PDFViewerApplication.eventBus.dispatch('find', {
          query: keyword,
          caseSensitive: false,
          highlightAll: true,
          findPrevious: true
        });
      }
    }
  • setInitialView 方法中:

    // 添加代码    
    // 高亮显示N个关键词----------------------------------------
    // 获取关键词数组
    var keywords = new URL(decodeURIComponent(location)).searchParams.get('keyword');
    if (keywords && keywords !== 'undefined') {
      this.searchKeywords(keywords.split('|'));
      setTimeout(() => {
        // 让高亮效果统一,避免最后一个聚焦的样式不同
        document.querySelector(`.highlight.selected`).classList.remove('selected');
      }, 1000);
    }
  1.  new URL(decodeURIComponent(location)).searchParams.get('keyword') 中的 ‘keyword’对应效果图中地址后拼接的 &keyword= 搜索的文字。
  2. this.searchKeywords(keywords.split('|')):根据 | 切割字符串为数组。后面优化了一下为this.searchKeywords(keywords.split('')),自动每个字都为搜索关键字。即最终效果图所示。

总结: 

这篇主要记录一下需求,所有成效均为借鉴参考文档。

后续会融入到项目中.....