当前位置:   article > 正文

vue2 pdf 预览(可粘贴,超链接可点),创建文本层和批注层_vue2 封装一个批注功能

vue2 封装一个批注功能

        vue2的项目,其中使用"pdfjs-dist的2的版本;

        页面引入:

  1. const PDFJS = require('pdfjs-dist')
  2. PDFJS.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.min')
  3. import { TextLayerBuilder,AnnotationLayerBuilder, SimpleLinkService } from 'pdfjs-dist/web/pdf_viewer'
  4. import 'pdfjs-dist/web/pdf_viewer.css'
  1. <div class="wrapper" id="pdf-container">
  2. <div v-for="item in totals" :id="`page-${item}`" :key="item" class="pdf-box">
  3. <canvas :id="`canvas-${item}`" class="canvas-pdf"></canvas>
  4. </div>
  5. </div>
  1. // 接口获取数据
  2. xxxapi().then(res=>{
  3. var binaryData = [];
  4. binaryData.push(res.data);
  5. console.log(binaryData);
  6. // 记得一定要设置application的类型
  7. let url = window.URL.createObjectURL(
  8. new Blob(binaryData, {
  9. type: "application/pdf;charset=utf-8",
  10. })
  11. );
  12. if (url) {
  13. this.contentSpining=false
  14. this.showPdf = true;
  15. let source = { url: url };
  16. PDFJS.getDocument(source).then(pdf => {
  17. // 得到PDF的总的页数
  18. let totalPage = pdf.numPages
  19. let idName = 'canvas-pdf-'
  20. // 根据总的页数创建相同数量的canvas
  21. this.createCanvas(totalPage, idName)
  22. for (let i = 1; i <= totalPage; i++) {
  23. pdf.getPage(i).then((page) => {
  24. let pageDiv = document.getElementById(`page-${i}`)
  25. let viewport = page.getViewport(this.scale)
  26. let canvas = document.getElementById(idName + i)
  27. let context = canvas.getContext('2d')
  28. canvas.height = viewport.height
  29. canvas.width = viewport.width
  30. this.viewHeight = viewport.height
  31. let renderContext = {
  32. canvasContext: context,
  33. viewport
  34. }
  35. page.render(renderContext).then(() => {
  36. return page.getTextContent()
  37. }).then((textContent) => {
  38. // 创建文本图层div
  39. const textLayerDiv = document.createElement('div')
  40. textLayerDiv.setAttribute('class', 'textLayer')
  41. // 将文本图层div添加至每页pdf的div中
  42. pageDiv.appendChild(textLayerDiv)
  43. let textLayer = new TextLayerBuilder({
  44. textLayerDiv: textLayerDiv,
  45. pageIndex: page.pageIndex,
  46. viewport: viewport
  47. })
  48. textLayer.setTextContent(textContent)
  49. textLayer.render()
  50. })
  51. // 批注层
  52. page.getAnnotations().then(annotations=>{
  53. // const annoLayerDiv=document.createElement(`div`)
  54. // annoLayerDiv.setAttribute('class', 'annotationLayer')
  55. const annolayer = new AnnotationLayerBuilder({
  56. pageDiv: pageDiv,
  57. annotations: annotations,
  58. pdfPage: page,
  59. linkService: new SimpleLinkService(),
  60. });
  61. annolayer.render(viewport);
  62. })
  63. })
  64. }
  65. })
  66. })

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/880286
推荐阅读
相关标签
  

闽ICP备14008679号