vue实现pdf高亮显示,以及矩形绘图(vue-pdf插件使用)

<template>
  <div class="container" >
    <el-row style="padding: 10px 10px 10px 10px;width: 100% ; height: 100%">
      <!-- 上一页、下一页 -->
      <el-row  style="background-color: #fff;height: 100%">
        <!-- 输入页码 -->
        <el-row >
          <el-col :span="4" style="padding-top: 4px ; padding-left: 10px" >
            <input v-model.number="currentPage"
                   type="number"
                   class="inputNumber"
                   @input="inputEvent()"> / <span style="color:#666666">{{pageCount}}</span>
          </el-col>
          <el-col :span="2">
            <div @click="changePdfPage('first')"
                 style="color: #1787EE;line-height: 30px;cursor: pointer">
              首页
            </div>
          </el-col>
          <!-- 在按钮不符合条件时禁用 -->
          <el-col :span="2">
            <div @click="changePdfPage('pre')"
                 style="color: #1787EE;line-height: 30px;cursor: pointer"
                 :style="currentPage===1?'cursor: not-allowed;':''">
              上一页
            </div>
          </el-col>
          <el-col :span="2">
            <div @click="changePdfPage('next')"
                 style="color: #1787EE;line-height: 30px;cursor: pointer"
                 :style="currentPage===pageCount?'cursor: not-allowed;':''">
              下一页
            </div>
          </el-col>
          <el-col :span="2">
            <div @click="changePdfPage('last')"
                 style="color: #1787EE;line-height: 30px;cursor: pointer">
              尾页
            </div>
          </el-col>
          <el-col :span="2">
            <div @click="scaleD()"
                 style="color: #1787EE;line-height: 30px;cursor: pointer">
              放大
            </div>
          </el-col>
          <el-col :span="2">
            <div  @click="scaleX()"
                 style="color: #1787EE;line-height: 30px;cursor: pointer">
              缩小
            </div>
          </el-col>
          <el-col :span="4">
            <div  @click="printPdf"
                 style="color: #1787EE;line-height: 30px;cursor: pointer">
              打印
            </div>
          </el-col>
          <el-col :span="2">
            <div  @click="customQuery"
                  style="color: #1787EE;line-height: 30px;cursor: pointer">
              抽取
            </div>
          </el-col>
          <el-col :span="2">
            <div  @click="fillColorByPoint"
                  style="color: #1787EE;line-height: 30px;cursor: pointer">
              绘图
            </div>
          </el-col>
        </el-row>
        <el-row style="padding: 4px 4px 0px 4px;height: 100%">
          <el-row class="pdfArea" id = "container" ref="container">
            <div style="position: relative;width: 100%;height: 100%;overflow-y: auto"  @mousedown="mousedown" @mousemove="mousemove"
                 @mouseup="mouseup" @Mouseleave="Mouseleave">
              <pdf :src="`${getFilePath}`"
                   ref="pdf"
                   v-show="loadedRatio===1"
                   :page="currentPage"
                   @num-pages="pageCount=$event"
                   @progress="loadedRatio = $event"
                   @page-loaded="pageLoaded"
                   @loaded="loadPdfHandler"
                   @link-clicked="currentPage = $event"
                   style="width:100%; height: 100%;overflow-y: auto"
                   id="pdfID"
                   @click.native="onclickM($event)"></pdf>
            </div>
          </el-row>
        </el-row>
      </el-row>
    </el-row>

    <!-- 加载未完成时,展示进度条组件并计算进度 -->
    <div class="progress"
         v-show="loadedRatio!==1">
      <el-progress type="circle"
                   :width="70"
                   color="#53a7ff"
                   :percentage="Math.floor(loadedRatio * 100)"></el-progress>
      <br>
      <!-- 加载提示语 -->
      <span>{{remindShow}}</span>
    </div>
  </div>
</template>

<script>
  import pdf from 'vue-pdf'
  import vue from 'vue'

  export default {
    components: {
      pdf
    },
    props: {
      fileName: String,
      path:String,
      // 当前页数
      currentPage: {
        type: Number,
        default: 1
      }
    },
    computed:{
      getFilePath: function () {
        if(this.fileName!==''){
          return this.path +'?file=' + this.fileName
        }
        return this.path
      }
    },
    created () {
      // this.prohibit()
    },
    destroyed () {
      // 在页面销毁时记得清空 setInterval
      clearInterval(this.intervalID)
    },
    mounted () {
      let _this = this
      this.$nextTick(() => {
          setTimeout(() => {
            _this.setWatermarkContent("田伟");
          },3000)
      })
    },
    data () {
      return {
        // ----- loading -----
        remindText: {
          loading: '加载文件中,文件较大请耐心等待...',
          refresh: '若卡住不动,可刷新页面重新加载...'
        },
        remindShow: '加载文件中,文件较大请耐心等待...',
        intervalID: '',
        // ----- vuepdf -----
        // src静态路径: /static/xxx.pdf
        // src服务器路径: 'http://.../xxx.pdf'
        src: '你的pdf路径',

        // 总页数
        pageCount: 0,
        // 加载进度
        loadedRatio: 0,
        scale: 100,

        //  customPositionShow:false, //自定义位置
        //   showclose:false,
        startX: '',  //画画开始的X坐标
        startY: '',  //画画开始的Y坐标
        endX: '',    //画画结束的X坐标
        endY: '',    //画画结束的Y坐标
        isMouseDownInCanvas: '', //鼠标是否按下
        customcxt: '',      // cxt
        customRwidth: 1,    //原图与展示图片的宽度比
        customRheight: 1,   //原图与展示图片的高度比
        imgstyle: '',        //根据图片大小自适应样式
        canvasstyle: '',     //根据图片大小canvas自适应样式 居中显示
        canvasWidth: '',     //根据图片大小自适应canvas宽
        canvasHeight: '',    //根据图片大小自适应canvas高
        DivWidth: 1460,      //最大宽度
        DivHeight: 740,      //最大高度
      }
    },
    methods: {
      fillColorByPoint(){
        // 清除指定区域的所有像素
        this.customcxt.clearRect(0, 0, this.DivWidth, this.DivHeight);
        this.customcxt.fillStyle = "rgba(255,255,0,0.5)"; //矩形框颜色	
        this.customcxt.lineWidth = "2";  //矩形框宽度
        this.customcxt.fillRect(238.44,456.6042,370.7885,478.5542);  //绘制矩形
      },
      //取消时返回组件调用处所需的数据
      customClose() {
        this.customcxt.clearRect(0, 0, this.DivWidth, this.DivHeight);
        this.$emit('custom', { 'type': 1, 'data': '' });
      },
      //确定时返回组件调用处所需的数据
      customQuery() {
        this.customcxt.clearRect(0, 0, this.DivWidth, this.DivHeight);
        //根据绘制进行图片裁剪

        //获取矩形框Left,Width'
        let cLeft = 0;
        let cWidth = 0;
        if (this.startX > this.endX) {
          cLeft = this.endX;
          cWidth = this.startX - this.endX;
        } else {
          cLeft = this.startX;
          cWidth = this.endX - this.startX;
        }

        //获取矩形框Top,Height
        let cTop = 0;
        let cHeight = 0;
        if (this.startY > this.endY) {
          cTop = this.endY;
          cHeight = this.startY - this.endY;
        } else {
          cTop = this.startY;
          cHeight = this.endY - this.startY;
        }

        var oMark = [];
        oMark['offsetLeft'] = parseInt(cLeft / this.customRwidth);
        oMark['offsetTop'] = parseInt(cTop / this.customRheight);
        oMark['offsetWidth'] = parseInt(cWidth / this.customRwidth);
        oMark['offsetHeight'] = parseInt(cHeight / this.customRheight);
        debugger
        this.$emit('custom', { 'type': 2, 'data': oMark });
      },

      //鼠标按下时执行
      mousedown(e) {
        // this.customcxt = this.$refs.pdf.$el.children[0].getContext("2d");// canvas显示层
        this.isMouseDownInCanvas = true;
        // 鼠标按下时开始位置与结束位置相同
        // 防止鼠标在画完矩形后 点击图画形成第二个图形
        this.endX = e.offsetX;
        this.endY = e.offsetY;
        this.startX = e.offsetX;
        this.startY = e.offsetY;
        this.mousemove(e)

      },
      //鼠标移动式时执行
      mousemove(e) {
        if (this.isMouseDownInCanvas) { // 当鼠标有按下操作时执行
          this.endX = e.offsetX;
          this.endY = e.offsetY;
          let wwidth = this.endX - this.startX;
          let wheigth = this.endY - this.startY;

          // 清除指定区域的所有像素
          this.customcxt.clearRect(0, 0, this.DivWidth, this.DivHeight);
          this.customcxt.strokeStyle = " #00ff00"; //矩形框颜色
          this.customcxt.lineWidth = "2";  //矩形框宽度
          this.customcxt.strokeRect(this.startX, this.startY, wwidth, wheigth);  //绘制矩形

        }
      },
      //鼠标松开时执行
      mouseup(e) {
        this.isMouseDownInCanvas = false;
      },

      Mouseleave(e) {
        this.isMouseDownInCanvas = false
      },
      //创建画板
      setWatermarkContent(content) {
        let id = "1.23452384164.1223412415";
        if (document.getElementById(id) !== null) {
          document.body.removeChild(document.getElementById(id));
        }
        let ele = document.createElement("canvas");
        ele.width = this.$refs.pdf.$el.children[0].clientWidth;
        ele.height = this.$refs.pdf.$el.children[0].clientHeight;
        this.DivWidth = ele.width;      //最大宽度
        this.DivHeight = ele.height ;      //最大高度
        let getCanvas = ele.getContext("2d");
        this.customcxt = getCanvas;
        ele.style.top = "0px";
        ele.style.left = "0px";
        ele.style.position = "absolute";
        document.getElementById("pdfID").appendChild(ele);
        return id;
      },
      //放大
      scaleD() {
        this.scale += 5;
        this.$refs.pdf.$el.style.width = parseInt(this.scale) + "%";
      },
      //缩小
      scaleX() {
        if (this.scale === 100) {
          return;
        }
        this.scale += -5;
        this.$refs.pdf.$el.style.width = parseInt(this.scale) + "%";
      },
      printPdf(){ // 调用打印
        this.$refs.pdf.print()
      },
      // 打印全部
      pdfPrintAll() {
        this.$refs.pdf.handleOpen();
      },
      // 监听滚动条事件
      listenerFunction (e) {
        // document.getElementById('container').addEventListener('scroll', true)
      },
      // 页面回到顶部
      toTop () {
        document.getElementById('pdfID').scrollTop = 0
      },
      // 输入页码时校验
      inputEvent () {
        if (this.currentPage > this.pageCount) {
          // 1. 大于max
          this.currentPage = this.pageCount
        } else if (this.currentPage < 1) {
          // 2. 小于min
          this.currentPage = 1
        }
      },
      // 切换页数
      changePdfPage (val) {
        if (val === 'pre' && this.currentPage > 1) {
          // 切换后页面回到顶部
          this.currentPage--
          this.toTop()
        } else if (val === 'next' && this.currentPage < this.pageCount) {
          this.currentPage++
          this.toTop()
        } else if (val === 'first') {
          this.currentPage = 1
          this.toTop()
        } else if (val === 'last' && this.currentPage < this.pageCount) {
          this.currentPage = this.pageCount
          this.toTop()
        }
      },

      // pdf加载时
      loadPdfHandler (e) {
        // 加载的时候先加载第一页
        let _this = this ;
        this.currentPage = 1

        // _this.customcxt = this.$refs.pdf.$el.children[0].getContext("2d");// canvas显示层
      },
      pageLoaded(e){
      },
      onclickM(e){

      },
      // 禁用鼠标右击、F12 来禁止打印和打开调试工具
      prohibit () {
        // console.log(document)
        document.oncontextmenu = function () {
          return false
        }
        document.onkeydown = function (e) {
          if (e.ctrlKey && (e.keyCode === 65 || e.keyCode === 67 || e.keyCode === 73 || e.keyCode === 74 || e.keyCode === 80 || e.keyCode === 83 || e.keyCode === 85 || e.keyCode === 86 || e.keyCode === 117)) {
            return false
          }
          if (e.keyCode === 18 || e.keyCode === 123) {
            return false
          }
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .container {
    overflow: hidden;
    height: 100%;
    font-family: PingFang SC;
    width: 100%;
    /* justify-content: center; */
    position: relative;
  }

  /* 右侧功能按钮区 */
  .right-btn {
    height: 30px;
    width: 100%;
  }

  .pdfArea {
    position: relative;
    overflow-x: auto;
    padding: 4px;
    width: 100%;
    /*overflow-y: auto;*/
    height: calc(100% - 34px);
    border: 2px solid #999999;
  }

  /* ------------------- 输入页码 ------------------- */
  .pageNum {
    margin: 10px 0;
    font-size: 18px;
  }
  /*在谷歌下移除input[number]的上下箭头*/
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
    margin: 0;
  }
  /*在firefox下移除input[number]的上下箭头*/
  input[type='number'] {
    -moz-appearance: textfield;
  }

  .inputNumber {
    border-radius: 5px;
    border: 1px solid #999999;
    height: 25px;
    font-size: 18px;
    width: 40px;
    text-align: center;
  }
  .inputNumber:focus {
    border: 1px solid #00aeff;
    background-color: rgba(18, 163, 230, 0.096);
    outline: none;
    transition: 0.2s;
  }

  /* ------------------- 切换页码 ------------------- */
  .turn {
    background-color: #888888;
    opacity: 0.7;
    color: #ffffff;
    height: 70px;
    width: 70px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 5px 0;
  }

  .turn-btn {
    background-color: #000000;
    opacity: 0.6;
    color: #ffffff;
    height: 70px;
    width: 70px;
    border-radius: 50%;
    margin: 5px 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .turn-btn:hover,
  .turn:hover {
    transition: 0.3s;
    opacity: 0.5;
    cursor: pointer;
  }

  /* ------------------- 进度条 ------------------- */
  .progress {
    position: absolute;
    right: 50%;
    top: 50%;
    text-align: center;
  }
  .progress > span {
    color: #199edb;
    font-size: 14px;
  }
  /*.inputNumber {*/
  /*  border-radius: 8px;*/
  /*  border: 1px solid #666666;*/
  /*  height: 35px;*/
  /*  font-size: 18px;*/
  /*  width: 60px;*/
  /*  text-align: center;*/
  /*}*/
  /*.inputNumber:focus {*/
  /*  border: 1px solid #00aeff;*/
  /*  background-color: rgba(18, 163, 230, 0.096);*/
  /*  outline: none;*/
  /*  transition: 0.2s;*/
  /*}*/
  .PDFViewer{
    background-color: #3a3a3a;
    font-size: 16px;
    height: 100%;
    overflow: scroll;
    a {
      text-decoration: none;
    }
    .PDFViewerHeader{
      background-color:white;
      color: #3a3a3a;
      height: 60px;
      line-height: 60px;
      h1 {
        margin: 0;
        padding-left: 20px;
        font-size: 16px;
        height: 60px;
        line-height: 60px;
      }
      span {
        width: 100%;
        display: inline-block;
        text-align: center;
      }
    }
    .DownloadBtn{
      float: right;
    }
    .PDFViewerBody{
      padding: 40px;
    }
    .card {
      margin-bottom: 10px;
    }
  }
</style>

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,实现Vue3中使用vue3-pdf实现PDF搜索高亮的步骤如下: 1. 首先,确保你的项目中已经安装了vue3-pdf插件。你可以通过以下命令来安装: ```shell npm install vue3-pdf ``` 2. 在你的Vue组件中引入vue3-pdf插件: ```javascript import { PdfViewer, PdfHighlighter } from 'vue3-pdf'; ``` 3. 在模板中使用PdfViewer组件来显示PDF文件: ```html <PdfViewer :src="pdfUrl" ref="pdfViewer"></PdfViewer> ``` 其中,pdfUrl是你要显示的PDF文件的URL。 4. 在Vue组件的data中定义一个highlightText变量,用于存储用户输入的搜索关键字: ```javascript data() { return { pdfUrl: 'your_pdf_url', highlightText: '' }; } ``` 5. 在模板中添加一个输入框,用于用户输入搜索关键字,并绑定到highlightText变量: ```html <input type="text" v-model="highlightText" placeholder="Enter search keyword"> ``` 6. 在PdfViewer组件上添加一个ref属性,以便在后续的步骤中可以访问到PdfViewer实例: ```html <PdfViewer :src="pdfUrl" ref="pdfViewer"></PdfViewer> ``` 7. 在Vue组件的methods中定义一个searchHighlight方法,用于执行搜索和高亮操作: ```javascript methods: { searchHighlight() { const pdfViewer = this.$refs.pdfViewer; pdfViewer.clearHighlights(); // 清除之前的高亮 const searchKeyword = this.highlightText; if (searchKeyword) { pdfViewer.search(searchKeyword); // 执行搜索 pdfViewer.highlight(searchKeyword); // 执行高亮 } } } ``` 8. 在输入框上添加一个监听事件,当用户输入关键字时调用searchHighlight方法: ```html <input type="text" v-model="highlightText" placeholder="Enter search keyword" @input="searchHighlight"> ``` 9. 最后,你可以根据需要自定义高亮的样式。你可以在PdfHighlighter组件上添加一个highlightStyle属性,来设置高亮的样式: ```html <PdfHighlighter :highlightStyle="{ backgroundColor: 'yellow' }"></PdfHighlighter> ``` 以上是使用vue3-pdf实现PDF搜索高亮的步骤。你可以根据自己的需求进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值