PdfCanvas.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. <template>
  2. <div class="pdf-container">
  3. <div class="header">
  4. <div class="title">{{ title }}</div>
  5. <div class="close-icon" @click="emits('close')">
  6. <CloseOutlined />
  7. </div>
  8. </div>
  9. <div ref="pdfRef" class="pdf-viewer"></div>
  10. </div>
  11. </template>
  12. <script setup>
  13. import { CloseOutlined } from '@ant-design/icons-vue';
  14. import { ref, watch } from 'vue';
  15. import PdfjsWorker from 'pdfjs-dist/build/pdf.worker.js?worker';
  16. const emits = defineEmits(['close']);
  17. const props = defineProps({
  18. src: { type: String, required: true },
  19. content: { type: String, required: true },
  20. num: { type: Number, required: false }
  21. });
  22. const pdfRef = ref(null);
  23. const height = ref(0);
  24. const start = ref(0);
  25. const pageContent = ref([]);
  26. const pageText = ref([]);
  27. // 侦听props的src改变,则立即切换渲染pdf
  28. watch(
  29. () => props.src,
  30. () => {
  31. setTimeout(() => init(), 1);
  32. },
  33. { immediate: true }
  34. );
  35. const title = computed(() => {
  36. return window.formatDocName(decodeURI(decodeURI(props.src)))
  37. // return `/lib/pdfjs/web/viewer.html?file=http://121.40.148.47:8530/doc/knowledge_base/download_doc/国土资源部 国家发展和改革委员会+财政部+住房和城乡建设部农业部+中国人民银行+国家林业局+中国银行业监督管理委员会关于扩大国有土地有偿使用范围的意见%28279-283%29.pdf`
  38. });
  39. // 渲染pdf
  40. async function init() {
  41. var pdfDom = document.getElementsByClassName('pdf-viewer')[0];
  42. while (pdfDom.firstChild) {
  43. pdfDom.removeChild(pdfDom.firstChild);
  44. }
  45. // 异步加载pdf.js
  46. const PDFJS = await import('pdfjs-dist/build/pdf.js');
  47. if (typeof window !== 'undefined' && 'Worker' in window) {
  48. PDFJS.GlobalWorkerOptions.workerPort = new PdfjsWorker();
  49. }
  50. // 加载文档
  51. let loadingTask = PDFJS.getDocument({ url: props.src });
  52. loadingTask.__PDFDocumentLoadingTask = true;
  53. pageContent.value = [];
  54. const pdf = await loadingTask.promise; // 使用await等待加载完毕
  55. // 循环渲染每一页
  56. for (let i = 1; i <= pdf.numPages; i++) {
  57. const page = await pdf.getPage(i);
  58. await renderPage(page, PDFJS, i);
  59. }
  60. console.log('pdf页面全部渲染完毕', pdf.numPages, pdf);
  61. pageText.value = [];
  62. //获取每页数据
  63. var textDivs = document.getElementsByClassName('textLayer');
  64. if (textDivs) {
  65. for (var i = 0; i < textDivs.length; i++) {
  66. var item = { page: i + 1, txt: textDivs[i].innerText };
  67. pageText.value.push(item);
  68. }
  69. }
  70. if (props.content) {
  71. goLocation(props.content);
  72. }
  73. }
  74. const goLocation = (txt) => {
  75. //获取页面
  76. var pageNumber = 0;
  77. var text =txt;
  78. var ptText = text.replaceAll('\n', '');
  79. ptText = ptText.replaceAll(' ', '');
  80. pageText.value.forEach((item) => {
  81. item.txt = item.txt.replaceAll('\n', '');
  82. item.txt = item.txt.replaceAll(' ', '');
  83. console.log(item.txt);
  84. if (item.txt.indexOf(ptText.substring(0, 18)) > -1) {
  85. pageNumber = item.page;
  86. }
  87. });
  88. text = text.replaceAll('\n', '');
  89. text = text.replaceAll(' ', '');
  90. if (text.endsWith('。') || text.endsWith(',') || text.endsWith('、')) {
  91. text = text.substring(0, text.length - 1);
  92. }
  93. //'left: 133.17px; top: 152.408px; font-size: 31.3597px; font-family: sans-serif; transform: scaleX(1.01878);'
  94. var arr = document
  95. .getElementsByClassName('textLayer')
  96. [pageNumber - 1].getElementsByTagName('span');
  97. if (arr) {
  98. var hightList = [];
  99. var startIndex = 0;
  100. var endIndex = 0;
  101. startIndex = getStartIndex(arr, text, text.length);
  102. endIndex = getEndIndex(arr, text, text.length, startIndex);
  103. var currentPageIndex = 0;
  104. var nextArr = [];
  105. if (endIndex == undefined) {
  106. currentPageIndex = arr.length;
  107. nextArr = document
  108. .getElementsByClassName('textLayer')
  109. [pageNumber].getElementsByTagName('span');
  110. endIndex = getEndIndex(nextArr, text, text.length, startIndex);
  111. } else {
  112. currentPageIndex = endIndex;
  113. }
  114. for (var i = startIndex; i < currentPageIndex; i++) {
  115. var element = arr[i];
  116. var hItem = {};
  117. var cssText = element.style.cssText;
  118. var spanText = element.innerText;
  119. console.log(spanText);
  120. if (text.includes(spanText)) {
  121. var topLabel = cssText.split('top: ')[1].split(';')[0];
  122. topLabel = topLabel.substring(0, topLabel.length - 2);
  123. var currentItems = [];
  124. pageContent.value.forEach((item) => {
  125. if (item.page == pageNumber) {
  126. currentItems = item.items;
  127. }
  128. });
  129. for (var m = 0; m < currentItems.length; m++) {
  130. var citem = currentItems[m];
  131. if (citem.str == spanText) {
  132. hItem.width = parseFloat(citem.width);
  133. hItem.height = parseFloat(citem.height);
  134. hItem.text = spanText;
  135. hItem.left = parseFloat(cssText.substring(6, cssText.indexOf('px')));
  136. hItem.top = parseFloat(topLabel);
  137. hightList.push(hItem);
  138. if (text.endsWith(citem.str)) {
  139. break;
  140. }
  141. }
  142. }
  143. }
  144. }
  145. var nextHightList = [];
  146. //跨页 目前只考虑跨1页
  147. if (endIndex != undefined) {
  148. for (var i = 0; i < nextArr.length; i++) {
  149. var element = nextArr[i];
  150. var hItem = {};
  151. var cssText = element.style.cssText;
  152. var spanText = element.innerText;
  153. console.log(spanText);
  154. if (text.includes(spanText)) {
  155. var topLabel = cssText.split('top: ')[1].split(';')[0];
  156. topLabel = topLabel.substring(0, topLabel.length - 2);
  157. var currentItems = [];
  158. pageContent.value.forEach((item) => {
  159. if (item.page == pageNumber + 1) {
  160. currentItems = item.items;
  161. }
  162. });
  163. for (var l = 0; l < currentItems.length; l++) {
  164. var citem = currentItems[l];
  165. if (citem.str == spanText) {
  166. hItem.width = parseFloat(citem.width);
  167. hItem.height = parseFloat(citem.height);
  168. hItem.text = spanText;
  169. hItem.left = parseFloat(cssText.substring(6, cssText.indexOf('px')));
  170. hItem.top = parseFloat(topLabel);
  171. nextHightList.push(hItem);
  172. if (text.endsWith(citem.str)) {
  173. break;
  174. }
  175. }
  176. }
  177. }
  178. if (text.endsWith(spanText)) {
  179. break;
  180. }
  181. }
  182. }
  183. //定位
  184. pdfRef.value.scrollTop = height.value * (pageNumber - 1) + hightList[0]['top'];
  185. //渲染
  186. var canvas = document.getElementsByClassName(`page`)[pageNumber - 1];
  187. const hightDiv = document.createElement('div');
  188. hightDiv.className = 'highlight-layer flash';
  189. hightList.forEach((it) => {
  190. const hDiv = document.createElement('div');
  191. hDiv.className = 'highlight';
  192. // 设置内联样式
  193. hDiv.style.width = it.width * 1.5 + 'px';
  194. hDiv.style.height = it.height * 1.5 + 'px';
  195. hDiv.style.left = it.left + 'px';
  196. hDiv.style.top = it.top + 'px';
  197. hightDiv.appendChild(hDiv);
  198. });
  199. canvas.appendChild(hightDiv);
  200. if (nextHightList && nextHightList.length > 0) {
  201. //渲染
  202. var nextCanvas = document.getElementsByClassName(`page`)[pageNumber];
  203. const hightDiv = document.createElement('div');
  204. hightDiv.className = 'highlight-layer flash';
  205. nextHightList.forEach((it) => {
  206. const hDiv = document.createElement('div');
  207. hDiv.className = 'highlight';
  208. // 设置内联样式
  209. hDiv.style.width = it.width * 1.5 + 'px';
  210. hDiv.style.height = it.height * 1.5 + 'px';
  211. hDiv.style.left = it.left + 'px';
  212. hDiv.style.top = it.top + 'px';
  213. hightDiv.appendChild(hDiv);
  214. });
  215. nextCanvas.appendChild(hightDiv);
  216. }
  217. }
  218. };
  219. const getStartIndex = (arr, text, total) => {
  220. var count = 0;
  221. for (var i = 0; i < arr.length; i++) {
  222. var element = arr[i];
  223. var spanText = element.innerText;
  224. console.log('===' + spanText);
  225. if (text.startsWith(spanText)) {
  226. return i;
  227. } else {
  228. count++;
  229. }
  230. }
  231. if (count == arr.length) {
  232. start.value = start.value + 1;
  233. text = text.substring(start.value, total);
  234. getStartIndex(arr, text, total);
  235. }
  236. };
  237. const getEndIndex = (arr, text, total, startIndex) => {
  238. for (var i = 0; i < arr.length; i++) {
  239. var element = arr[i];
  240. var spanText = element.innerText;
  241. console.log('===' + spanText);
  242. if (text.endsWith(spanText) && spanText.length > 1) {
  243. return i;
  244. }
  245. }
  246. };
  247. const renderPage = (page, PDFJS, num) => {
  248. return new Promise(async (resolve, reject) => {
  249. // 先渲染图片
  250. let pixelRatio = 1;
  251. const viewport = page.getViewport({ scale: 1.5 });
  252. const canvas = document.createElement('canvas');
  253. const context = canvas.getContext('2d');
  254. canvas.id = `page-${num}`;
  255. canvas.height = viewport.height * pixelRatio;
  256. console.log('==height', canvas.height);
  257. height.value = canvas.height;
  258. canvas.width = viewport.width * pixelRatio;
  259. const renderContext = {
  260. canvasContext: context,
  261. viewport: viewport,
  262. transform: [pixelRatio, 0, 0, pixelRatio, 0, 0]
  263. };
  264. await page.render(renderContext).promise;
  265. // 再渲染文字
  266. const textContent = await page.getTextContent();
  267. pageContent.value.push({ page: num, items: textContent.items });
  268. const textLayer = document.createElement('div');
  269. PDFJS.renderTextLayer({
  270. textContent: textContent,
  271. container: textLayer,
  272. viewport: viewport,
  273. transform: [pixelRatio, 0, 0, pixelRatio, 0, 0],
  274. textDivs: []
  275. });
  276. textLayer.className = 'textLayer';
  277. // 将文字覆盖在图片上
  278. const canvasWrapper = document.createElement('div');
  279. canvasWrapper.className = 'canvasWrapper';
  280. const pageDiv = document.createElement('div');
  281. pageDiv.className = 'page';
  282. canvasWrapper.appendChild(canvas);
  283. pageDiv.appendChild(canvasWrapper);
  284. pageDiv.appendChild(textLayer);
  285. pdfRef.value.appendChild(pageDiv);
  286. resolve();
  287. });
  288. };
  289. </script>
  290. <style scoped lang="scss">
  291. .pdf-container {
  292. width: 100%;
  293. height: 100%;
  294. position: relative;
  295. .header {
  296. height: 40px;
  297. position: sticky;
  298. display: flex;
  299. justify-content: center;
  300. align-items: center;
  301. border-bottom: 1px solid #eee;
  302. top: 0px;
  303. z-index: 9999999;
  304. background: #fff;
  305. width: 100%;
  306. right: 0px;
  307. left: 0px;
  308. .title {
  309. font-size: 18px;
  310. font-weight: bolder;
  311. text-overflow: ellipsis;
  312. width: 0px;
  313. white-space: nowrap;
  314. flex-grow: 1;
  315. overflow: hidden;
  316. margin-left: 30px;
  317. margin-right: 40px;
  318. }
  319. .close-icon {
  320. position: absolute;
  321. top: 10px;
  322. right: 21px;
  323. cursor: pointer;
  324. }
  325. }
  326. }
  327. .pdf-viewer {
  328. width: 100%;
  329. height: calc(100% - 40px);
  330. position: relative;
  331. border: 0px solid #ccc;
  332. overflow-y: auto;
  333. }
  334. </style>
  335. <style>
  336. /* 不能用scoped,因为动态创建的元素不会被编译带上hash */
  337. /* 不加上这些css修饰,元素会错位,样式来自vue-pdf-embed这个库 */
  338. .canvasWrapper {
  339. position: relative;
  340. /* display: flex;
  341. justify-content: center; */
  342. }
  343. .page {
  344. position: relative;
  345. box-shadow: 0 4px 10px 0 rgba(0, 0, 0, 0.08);
  346. margin: 30px auto;
  347. }
  348. .textLayer {
  349. text-align: initial;
  350. position: absolute;
  351. top: 0;
  352. left: 0;
  353. right: 0;
  354. bottom: 0;
  355. overflow: hidden;
  356. opacity: 0.2;
  357. line-height: 1;
  358. text-size-adjust: none;
  359. forced-color-adjust: none;
  360. }
  361. .textLayer span,
  362. .textLayer br {
  363. color: transparent;
  364. position: absolute;
  365. white-space: pre;
  366. cursor: text;
  367. transform-origin: 0% 0%;
  368. }
  369. .highlight-layer {
  370. position: absolute;
  371. top: 0;
  372. left: 0;
  373. right: 0;
  374. bottom: 0;
  375. pointer-events: none;
  376. opacity: 0.15;
  377. overflow: hidden;
  378. }
  379. .flash {
  380. animation: flashing 0.6s;
  381. animation-iteration-count: 2;
  382. }
  383. @keyframes flashing {
  384. 0% {
  385. opacity: 0;
  386. }
  387. 100% {
  388. opacity: 0.15;
  389. }
  390. }
  391. .highlight {
  392. background-color: #0076fa;
  393. position: absolute;
  394. }
  395. </style>