PDFView.vue 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <script setup lang="ts">
  2. import { ref, toRefs } from 'vue'
  3. import VuePdfEmbed from 'vue-pdf-embed'
  4. import 'vue-pdf-embed/dist/styles/annotationLayer.css'
  5. import 'vue-pdf-embed/dist/styles/textLayer.css'
  6. import { debounce } from 'lodash'
  7. /**
  8. * pdf预览组件
  9. * 支持高亮指定内容
  10. */
  11. interface PDFViewProps {
  12. url: string // 文件地址
  13. highLightContent?: string // 需要高亮的内容
  14. }
  15. const props = defineProps<PDFViewProps>()
  16. const { url, highLightContent } = toRefs(props)
  17. const pdfViewerRef = ref<any>(null)
  18. const handleScrollToView = debounce(
  19. (element: Element) => {
  20. element?.scrollIntoView({
  21. behavior: 'smooth',
  22. block: 'center'
  23. })
  24. },
  25. 1000,
  26. { leading: true, trailing: false }
  27. )
  28. const handlePdfLoaded = (): void => {
  29. // 加载完成后可操作PDF实例
  30. if (highLightContent.value) {
  31. const container = document.getElementById('pdfViewerRef')
  32. if (container == null) return
  33. // 获取所有span元素
  34. const spans = container.getElementsByTagName('span')
  35. Array.from(spans).forEach((span) => {
  36. const text = span?.textContent?.trim() ?? ''
  37. // 检查内容是否在highLightContent数组中
  38. if (
  39. (text?.length ?? 0) > 4 &&
  40. /[a-zA-Z\u4e00-\u9fa5]/.test(text) &&
  41. highLightContent.value?.includes(text)
  42. ) {
  43. try {
  44. handleScrollToView(span)
  45. span.style.backgroundColor = '#ff06' // 设置高亮背景色
  46. } catch (e) {
  47. console.log('handleScrollToView error: ', e)
  48. }
  49. }
  50. })
  51. }
  52. }
  53. const onProcess = (e) => {
  54. // console.log('onProcess: ', e)
  55. }
  56. const onLoaded = (doc: any) => {
  57. console.log('onLoaded: ', doc)
  58. }
  59. </script>
  60. <template>
  61. <VuePdfEmbed
  62. id="pdfViewerRef"
  63. ref="pdfViewerRef"
  64. class="pdf-view"
  65. annotation-layer
  66. text-layer
  67. :source="url"
  68. @progress="onProcess"
  69. @loaded="onLoaded"
  70. @rendered="handlePdfLoaded"
  71. />
  72. </template>
  73. <style scoped lang="scss">
  74. .pdf-view {
  75. width: 100%;
  76. height: 100%;
  77. }
  78. </style>