kkFileView默认高亮pdf关键字

需求:需要把关键字传入到pdf预览界面,并高亮展示。

这里使用的是:

1
2
var url = 'http://127.0.0.1:8080/file/test.txt'; //要预览文件的访问地址
window.open('http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(base64Encode(url)));

修改代码:

1、修改 onlinePreview 接口

1
2
3
4
5
6
7
8
9
10
11
12
public class OnlinePreviewController {
@GetMapping( "/onlinePreview")
// 添加 keyword 接收高亮关键字
public String onlinePreview(String url, String keyword, Model model, HttpServletRequest req) {
// *************
model.addAttribute("file", fileAttribute);
// 高亮关键字返回给前端
model.addAttribute("keyword", keyword);
// *************
return filePreview.filePreviewHandle(fileUrl, model, fileAttribute);
}
}

2、前端接收参数,并且高亮

打开 server\src\main\resources\static\pdfjs\web\viewer.js 文件,

找到 getViewerConfiguration() 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function getViewerConfiguration() {
let errorWrapper = null;
errorWrapper = {
container: document.getElementById("errorWrapper"),
errorMessage: document.getElementById("errorMessage"),
closeButton: document.getElementById("errorClose"),
errorMoreInfo: document.getElementById("errorMoreInfo"),
moreInfoButton: document.getElementById("errorShowMore"),
lessInfoButton: document.getElementById("errorShowLess")
};
// 获取关键字
const queryString = document.location.search.slice(1); //new
const m = /(^|&)keyword=([^&]*)/.exec(queryString);//new
const keyword = m ? decodeURIComponent(m[2]) : "";//new
if(keyword){//new
// 讲关键字放入输入框中,当前 id 可以在 viewer.html 中找到
document.getElementById("findInput").value = keyword;//new
}//new
}

找到 PDFViewerApplication对象中的 _initializeViewerComponents方法,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   if (!this.supportsIntegratedFind) {
this.findBar = new _pdf_find_bar.PDFFindBar(appConfig.findBar, eventBus, this.l10n);
// 添加打开查询框的操作
if (PDFViewerApplication.findBar.opened) {//new
PDFViewerApplication.findBar.open();//new
} else {//new
console.log('PDFViewerApplication.findBar.opened');//new
PDFViewerApplication.findBar.opened = false;//new
PDFViewerApplication.findBar.open();//new
}//new
// 执行高亮的操作
const highLightStr = appConfig.findBar.findField.value;//new
PDFViewerApplication.findController.executeCommand("find", {query:highLightStr, phraseSearch: false, caseSensitive: false, highlightAll: true, findPrevious: false,});//new
}

3、使前端修改生效

一个比较简单的方式,在 viewer.js 同目录下 viewer.js.map 中直接修改。

因为 viewer.js.map 中的代码为字符串,所以我们需要精确的找到我们修改的位置,把修改的内容复制进去。

本文地址: https://github.com/maxzhao-it/blog/post/d10ffa56/