跨域打印pdf

2020-01-06  本文已影响0人  大佬啊

公司有个需求,能下载能打印pdf,但是公司文件系统部署在其他服务器,与当前前端项目不在一个服务器,于是就产生了目前的问题-跨域怎么操作?

一、需要安装的依赖

print-js: 为了打印使用的js工具库

npm install print-js --save

二、纯前端处理(无效的实验)

暂时没有办法,试过通过一个iframe代理生成实际的iframe,然后在实际iframe的onload方法来打印代理iframe,但是想法很美好,实验结果很残酷,打印imge类型的可以,pdf的话全是白纸,及实际iframe没有加载完毕就执行了代理iframe打印。

帖上尝试的代码,有想法能实现的,请联系我 哈哈

function printIframe(url) {
  const proxyIframe = document.createElement('iframe');
  const body = document.getElementsByTagName('body')[0];
  body.appendChild(proxyIframe);
  proxyIframe.style.width = '100%';
  proxyIframe.style.height = '100%';
  proxyIframe.style.display = 'none';
  const contentWindow = proxyIframe.contentWindow;
  contentWindow.document.open();
  contentWindow.document.write('<iframe id="myifa" src="' + url + '"  width="800" height="900" frameborder="0" marginheight="0" marginwidth="0">');
  contentWindow.onload = function() {
    setTimeout(function() {
      const Iframe = contentWindow.document.getElementById('myifa');
      setTimeout(function() {
        contentWindow.focus();
        contentWindow.print();
      }, 5000);
    }, 0);
  };

  contentWindow.document.close();
}

三、让后台服务器来处理,把数据拿过来然后前端再处理

这种方法是目前笔者试过最有效的办法,虽然效率低,但其至少实现了功能......
实现步骤:
1.通过ajax拿到后台返回的二进制文件流
2.处理得到base64格式的数据
3.通过pdf-js打印

import printJs from 'print-js';
// axios类似于ajax,这里简写了
axios.get('/api/getfile', {
  ...payload,
})
.then(response => {
  // 假设response时后台返回的二级制文件流
  let result;
  const uint8Array = new Uint8Array(response);
  for(let i = 0; i< uint8Array.length; i++) {
    // String.fromCharCode:将 Unicode 编码转为一个字符:
    result += String.fromCharCode(uint8Array[i]);
  }
  let printBase64 = window.btoa(result);
  // 与src里直接放入data:application/pdf;base64 xxxx这样的格式, 真正的base64数据是xxx不包含之前的
  // 如果要是做预览,请自行加上前边类型字段
  printJs({ printable: printBase64, type: 'pdf', base64: true });
})
.catch(error => {
  console.log(error);
});

OVER~

如果你有更好的办法,烦请留言@我了

上一篇 下一篇

猜你喜欢

热点阅读