PDFjs 魔改支持从地址栏传入关键字高亮显示及双指捏合缩放

修改代码

修改 view.js 的初始化 setInitialView 方法 在该方法最下面加入下面代码

1
2
3
4
5
6
7
8
9
var urlPath=decodeURIComponent(window.parent.document.location);
var index=urlPath.indexOf("keyword");
if (index === -1) {
return;
}
var keyword=urlPath.substr(index+8);
console.log(urlPath, index, keyword);
document.getElementById("findInput").value=keyword;
document.getElementById("findHighlightAll").click();

使用方法

访问时在地址栏传入 &keyword=xxx 关键字

双指捏合缩放

在 viewer.html 中的 <script src="viewer.js"></script> 下面添加如下代码

1
<script src="custom-pinch-zoom.js"></script>

custom-pinch-zoom.js 代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
window.addEventListener("webviewerloaded", () => {
const container = document.getElementById("viewerContainer");

let startDistance = 0;
let startScale = 1;
let currentScale = 1;
let isPinching = false;

const viewer = document.getElementById("viewer");

function getDistance(touches) {
const dx = touches[0].clientX - touches[1].clientX;
const dy = touches[0].clientY - touches[1].clientY;

return Math.sqrt(dx * dx + dy * dy);
}

container.addEventListener(
"touchstart",
(e) => {
if (e.touches.length === 2) {
isPinching = true;

startDistance = getDistance(e.touches);

startScale =
PDFViewerApplication.pdfViewer.currentScale;

currentScale = startScale;
}
},
{ passive: true }
);

container.addEventListener(
"touchmove",
(e) => {
if (!isPinching || e.touches.length !== 2) {
return;
}

e.preventDefault();

const currentDistance =
getDistance(e.touches);

const scaleFactor =
currentDistance / startDistance;

currentScale = startScale * scaleFactor;

currentScale = Math.max(
0.5,
Math.min(currentScale, 5)
);

// 关键:
// pinch 过程中只做 transform
viewer.style.transform =
`scale(${currentScale / startScale})`;

viewer.style.transformOrigin = "center center";
},
{ passive: false }
);

container.addEventListener("touchend", () => {
if (!isPinching) {
return;
}

isPinching = false;

// 清除临时 transform
viewer.style.transform = "";

// 最终真正 rerender
PDFViewerApplication.pdfViewer.currentScale =
currentScale;
});
});


不是很完美,但是能用