Base64转PDF方法

方法一、blob实现

 //content是base64格式
    viewPdf(content) {
      console.log("content",content)
      const blob = this.base64ToBlob(content)
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob)
      } else {
        const fileURL = URL.createObjectURL(blob)
        // window.open(fileURL);//弹出ppf文件
      }
 
 //code是base64格式
    base64ToBlob(code) {
      code = code.replace(/[\n\r]/g, '')
      // atob() 方法用于解码使用 base-64 编码的字符串。
      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' })
    },

方法二、embed或者iframe

// 打开一个新窗口或新标签页

const newWindow = window.open('', '_blank');

// 如果窗口打开成功,在新窗口中加载一个包含iframe的页面

if (newWindow) {

// 写入HTML到新窗口中

newWindow.document.write(`<embed v-if="${url}" : src="${url}" type="application/pdf" width="100%" height="600px"/>`);

// newWindow.document.write(`<iframe src="${url}" style="width:100%;height:100vh;" frameborder="0"></iframe>`);

} else {

// 窗口打开失败的处理逻辑

}

方法三、pdf.js实现

<!DOCTYPE html>
<html>
<head>
  <title>PDF.js Preview</title>
</head>
<body>

<canvas id="the-canvas"></canvas>
 
<script src="./build/pdf.js"></script>
<script>

// 预览PDF的函数
function showPDF(pdfData) {
  // 使用PDF.js加载PDF
  pdfjsLib.getDocument({data: pdfData}).promise.then(function(pdf) {
    // 获取第一页
    pdf.getPage(1).then(function(page) {
      var viewport = page.getViewport({scale: 1.5});
      var canvas = document.getElementById('the-canvas');
      var context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;
      // 渲染页码
      var renderContext = {
        canvasContext: context,
        viewport: viewport
      };
      page.render(renderContext).promise.then(function() {
        console.log('Page rendered');
      });
    });
  });
}

var data;
showPDF(data);

</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值