Use pdf.js in Vue to implement online preview of pdf file stream

The following are the steps to use pdf.js in Vue to implement online preview of pdf file flow:

1. Install pdf.js

npm install pdfjs-dist

2. Introduce pdf.js

In the components that need to be used, use the following code to introduce pdf.js:

import pdfjsLib from 'pdfjs-dist'

3. Load pdf file stream

Use the pdf.js getDocument()method to load the pdf file stream. A file stream can be passed to this method as a Blob object. For example, you can use axios to get a pdf file stream from the server:

axios.get('/api/pdf', {
    
     responseType: 'blob' })
  .then(response => {
    
    
    const blob = new Blob([response.data], {
    
     type: 'application/pdf' })
    this.loadPdf(blob)
  })

In loadPdf()the method, getDocument()load the pdf file using the method:

loadPdf(blob) {
    
    
  pdfjsLib.getDocument({
    
     data: blob }).then(pdf => {
    
    
    this.pdf = pdf
    this.renderPdf()
  })
}

At this point, the pdf file has been loaded into the pdf object.

4. Render pdf

Use pdf.js's Renderer to render pdf files. You can use getViewport()the method to get the view size of the pdf page.

In renderPdf()the method, iterate through each page of the pdf file and render it using Renderer:

renderPdf() {
    
    
  this.pdf.getPage(1).then(page => {
    
    
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    const viewport = page.getViewport({
    
     scale: 1 })
    canvas.height = viewport.height
    canvas.width = viewport.width
    page.render({
    
     canvasContext: context, viewport })
    this.pdfUrl = canvas.toDataURL('image/jpeg')
  })
}

At this point, the pdf file has been rendered into a picture. Bind the URL of the image to the src attribute of the img tag to achieve online preview:

<img v-if="pdfUrl" :src="pdfUrl">

The above are the detailed steps for using pdf.js in Vue to preview pdf file flow online.

Guess you like

Origin blog.csdn.net/qq_45585640/article/details/132730840