pdf.js 请求传参关键词并高亮显示
1.去官网下载: http://mozilla.github.io/pdf.js/getting_started/#download
2.将下载的包copy到static下 该演示项目为springboot集成thymealf 所以放在static下 即可(按项目修改请求路径)
3.前端代码
对iframe 的src属性赋予pdf链接
file= :从后端获取pdf文件
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>pdfjs跳转到指定页面并高亮显示关键词</title>
<th:block th:insert="include::header"></th:block>
</head>
<body>
<h1>pdfjs跳转到指定页面并高亮显示关键词</h1>
<iframe width="100%" height="100%" id="pdf"></iframe>
</body>
<th:block th:insert="include::js"></th:block>
<script type="text/javascript">
//跳转页面
var page=2;
//高亮显示关键词
var keyword='题库';
//跳转到指定页面 /pdf/localPdf为控制层获取pdf字节响应给浏览器
//$('#pdf').attr('src',ctx+'/plugin/pdfjs/web/viewer.html?file='+encodeURIComponent(ctx+'/pdf/localPdf')+'#page='+page);
//传入关键字
$('#pdf').attr('src',ctx+'/plugin/pdfjs/web/viewer.html?file='+encodeURIComponent(ctx+'/pdf/localPdf')+'&keyword='+keyword);
</script>
</html>
4.获取本地pdf文件响应给浏览器 控制层/pdf/localPdf 调用该方法
public void getPdf(HttpServletResponse response) throws IOException {
try {
String path="D:\\yaxin\\pdfjs.pdf";
response.reset();
response.setContentType("application/pdf");
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
InputStream in = new FileInputStream(new File(path));
int tempbyte;
while ((tempbyte = in.read(buf)) != -1) {
out.write(buf);
}
out.flush();
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
4.修改view.js的初始化setInitialView方法 往该方法最下面加入下面代码
//获取链接
var urlPath=decodeURIComponent(window.location.href);
var index=urlPath.indexOf("&keyword");
//获取关键词
var keyword=urlPath.substr(index+9);
//对查询输入框进行赋值
document.getElementById("findInput").value=keyword;
//点击高亮按钮实现高亮显示关键词
document.getElementById("findHighlightAll").click();
5.效果显示