pdf preview in base64 format

pdf preview in base64 format

In the project, we will encounter the need to Preview pdf. Generally, it is required to open it directly. Generally, there are two formats of back-end return pdf, one is the url address of direct transfer pdf, and the other is the pdf in base64 format. How do you know that it is a pdf in base64 format? The general format is like this

JVBERi0xLjQKJeLjz9MKMiAwIG9iaiA8PC9MZW5ndGggNzUzL0ZpbHRlci9GbGF0ZURlY29kZT4+c3RyZWFtCnicrZY/TxRBGIcXEy220d5mQgUF47zzf7EzUYyFkeMSTSSnggfGSAGKxMrSGDDQSExMSCz8EnZ+DS2s/AAmRhIbfOd218DtvHO3BMgdl/3NPvvsb2bnWM+vdXNlmReWdR/ngs2A9eHT9W4+n68PXpLdwmAuF9ywrdx7rpjTlknDJZOCbfTzhSoDUPg3hNpw5YZT47l3g9gabtRQLKXmGujYF7zQZKyM4bqEgwEuh/NSW/pSG3xEG8NSeyittDEuL3wyrrWpuNIm4lob40r7ZF5qg0hoY5jSxjilTcWVNhHX2hjT2raQtHYIE9ohTmiTcalNxZV2iBPaTie0MUxpY5zSpuJKm4hrbYwT2sYmtI1Nahub1KbiSpuIa21jU9oq8UiGMKWtko8kGVfaRFxrq8YjOR82S2ACf4HJcC5zHnfLtfzKDWCAO+gKbpbdjQBS+IOwqUcX3359Nvfw6nT3KW6imAEexc31GKkQvGDOwH+QOAZSNai3u3CYgABYDmNg7n9aenX7S/deCuWAWz0a1bnc+9v/8/53AiWV4+BGo5Y/9+0IlBKSj0EK9zeCpAG4GLOqMH2pqcN1KJlTEpdCxSoCaiqDcNZQr1JyW8RG799cuvThW+QMC1xBlC8zkUHmsxl8l/guM50xPOayWfxUNFlSWu7NGbEKyfHxOBNWVSHoJipWoRus8ubo59urv+gCY/TTFtiC5ZGlMk8X2JoV8VIWt8poJ9uH/TdrH8XE67t3Fqf3z2/97L1892P3+9Hiys7kzuTRBDUZtrANLUVORmT04ILkbMTwre+6mo02rAJZkFjObVmYNVla+DAbEdbe5vpq5+DFBXGO7N35hoAm95HI6FUIE04XH+GfuvgW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mo8PC9UeXBlL1BhZ2VzL0NvdW50IDEvS2lkc1s0IDAgUl0+PgplbmRvYmoKNyAwIG9iajw8L1R5cGUvQ2F0YWxvZy9QYWdlcyAzIDAgUj4+CmVuZG9iago4IDAgb2JqPDwvUHJvZHVjZXIoaVRleHQgMi4wLjcgXChieSBsb3dhZ2llLmNvbVwpKS9Nb2REYXRlKEQ6MjAyMTA2MzAwOTU1NDkrMDgnMDAnKS9DcmVhdGlvbkRhdGUoRDoyMDIxMDYzMDA5NTU0OSswOCcwMCcpPj4KZW5kb2JqCnhyZWYKMCA5CjAwMDAwMDAwMDAgNjU1MzUgZiAKMDAwMDAwMTM3OCAwMDAwMCBuIAowMDAwMDAwMDE1IDAwMDAwIG4gCjAwMDAwMDE1MDEgMDAwMDAgbiAKMDAwMDAwMDgzNSAwMDAwMCBuIAowMDAwMDAwOTkxIDAwMDAwIG4gCjAwMDAwMDExODEgMDAwMDAgbiAKMDAwMDAwMTU1MSAwMDAwMCBuIAowMDAwMDAxNTk1IDAwMDAwIG4gCnRyYWlsZXIKPDwvUm9vdCA3IDAgUi9JRCBbPDk5MGVjNjU1ZDZhODIzODRlYWFlODBkY2FhNzRiNjNiPjwyNDRjNjQ1Yzc5NWRkZWQ5MmI1NTM2MzViNGE3NmY2Zj5dL0luZm8gOCAwIFIvU2l6ZSA5Pj4Kc3RhcnR4cmVmCjE3MjYKJSVFT0YK

Let's first look at the requirements to be realized:

Before opening:

After opening:

How to open pdf in this format?

1. Open directly, because now pdf can be opened directly in the browser, which is the most convenient way, but one problem is that when you click preview on ie, the ie browser will let you download instead of open directly. Therefore, if your project can be opened directly, it's best to use this way. Here's how to open the code:

viewPdf (content) {
      if (!content) {
        console.log(content)
        this.$message.error('No comments')
        return
      }
      const blob = this.base64ToBlob(content)
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob)
      } else {
        const fileURL = URL.createObjectURL(blob)
        window.open(fileURL)
      }
    },
    base64ToBlob (code) {
      code = code.replace(/[\n\r]/g, '')
      const raw = window.atob(code)
      const rawLength = raw.length
      const uInt8Array = new Uint8Array(rawLength)
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: 'application/pdf' })
    }

The content here is the string of base64 pdf above. Just these two methods can be perfectly realized.

2. Preview using pdf.js. This method is slightly more troublesome than the above method.

The advantage is that no matter what browser, it can be opened perfectly. In addition, if you don't need any functions, you can comment them out and have strong customization.

Disadvantages: the file is large and needs to be optimized later

Steps:

1, Download pdf.js

Where to download, of course, is the official website, but it seems that the latest version of pdf.js does not support ie. you can download the old version or directly use the one in my project. In other words, you can download Babel Polyfill to try. When I was writing this demo, I always reported an error in ie, and then downloaded Babel Polyfill to solve it perfectly.

Note that these documents:

2, Throw the pdf folder into the public package of the project

The reason why it should be put in the public package is that when packaging, the webpack will package the things it depends on, but the open of another web page does not depend on this file. Therefore, if it is put in other folders, it may not be packaged, and the contents in the public package will be output to the dist folder intact (other tutorials on the Internet also refer to other folders, but they all refer to the folder where webpack will be packaged intact). Therefore, its disadvantages are also here. Because the package of pdf.js is still quite large, it is best to put it on the static resource server instead of its own files for optimization.

Some articles need to modify the content in pdf.js. I don't need this. Just throw it in.

3, Add two methods to convert to a format recognized by pdf.js

viewPdf (content) {
      let url = this.createDownloadFileUrl('pdf preview', content)
      // console.log(url);
      window.open('/pdf/web/viewer.html?file=' + url)
    },
    createDownloadFileUrl (fileName, file) {
      var blob = this.dataURLtoFile(
        `data:application/pdf;base64,${file}`,
        fileName
      ) // application/zip needs to be changed to the type of file to be downloaded
      blob.lastModifiedDate = new Date()
      blob.name = fileName
      return URL.createObjectURL(blob)
    },
    dataURLtoFile (dataurl, filename) {
      // Generate Blob
      var arr = dataurl.split(',')
      var mime = arr[0].match(/:(.*?);/)[1]
      var bstr = atob(arr[1])
      var n = bstr.length
      var u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    }

Special attention to this step: pay special attention to the open address of window.open('/ pdf/web/viewer.html?file =' + url). Don't write it wrong. You don't need public. We generally want to open the web in pdf under the public folder, but you don't need it, otherwise an error will be reported. In addition, if your folder is not named like this, you can name it yourself.

Generally, it only needs these three steps to solve the problem perfectly. When I wrote this demo, I referred to a lot of articles and contents, walked a lot of holes, and finally found this very simple method. In addition, users can upload pdf for preview. I won't mention it here. For details, please see the demo I wrote.

Reference articles: https://blog.csdn.net/shentibeitaokong/article/details/80011900

Your demo address: https://github.com/rui-rui-an/viewpdfbybase64

Tags: Vue.js

Posted on Sat, 20 Nov 2021 07:37:03 -0500 by dirkers