background

The company needs the front end to circle the area on the PDF, give the area to the back end, and then recognize the text function. The first idea was to use a canvas.

Use PDF.js in vue

1, install,

Note: Be sure to install this version, it will be wrong…

NPM [email protected] - I D

2. Use and introduction

  • html
<canvas
    style="border: solid 1px red"
    v-for="page in pdf_pages" :id="'the-canvas'+page" :key="page">
</canvas>
Copy the code
  • js
/ / into PDF. Js
import PDFJS from 'pdfjs-dist'
import workerSrc from 'pdfjs-dist/build/pdf.worker.entry'

export default {
  data() {
      return {
        pdf_page: 0/ / PDF page}},methods: {

        loadTestCanvas() {
          const url = '/static/SE_BOOKING_GEN_SHAASCAVAN1000069.pdf' / / PDF address
          let loadingTask = PDFJS.getDocument(url)
          loadingTask.promise
              .then((pdf) = > {
                this.pdfDoc = pdf
                this.pdf_pages = this.pdfDoc.numPages
                this.$nextTick(() = > {
                  // The default is 1 page
                  this._renderPage(1)})})},_renderPage(num) {  // Render the PDF page
          const that = this
          this.pdfDoc.getPage(num)
              .then((page) = > {
                let canvas = document.getElementById('the-canvas' + num)
                let ctx = canvas.getContext('2d')
                let dpr = window.devicePixelRatio || 1
                let bsr = ctx.webkitBackingStorePixelRatio ||
                    ctx.mozBackingStorePixelRatio ||
                    ctx.msBackingStorePixelRatio ||
                    ctx.oBackingStorePixelRatio ||
                    ctx.backingStorePixelRatio || 1
                let ratio = dpr / bsr
                let viewport = page.getViewport({scale: 1}) // Zoom defaults to 1
                console.log(85. page) canvas.width = viewport.width * ratio canvas.height = viewport.height * ratio canvas.style.width = viewport.width +'px'

                that.pdf_div_width = viewport.width + 'px'

                canvas.style.height = viewport.height + 'px'

                ctx.setTransform(ratio, 0.0, ratio, 0.0)
                let renderContext = {
                  canvasContext: ctx,
                  viewport: viewport
                }
                page.render(renderContext)
                if (this.pdf_pages > num) {
                  this._renderPage(num + 1)}})},}}Copy the code

reference

reference