【问题标题】:Print blob (pdf) in IE / Edge with typescript使用打字稿在 IE / Edge 中打印 blob (pdf)
【发布时间】:2019-09-11 17:56:23
【问题描述】:

我想使用打字稿打印 blob (pdf)。我尝试了下面的代码,它适用于 Chrome,但不适用于 Edge。

代码 1(适用于 Chrome,但在 Edge 中打印时显示空白)-

    const fileURL = URL.createObjectURL(blob);
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.src = fileURL;
    iframe.name = fileName;
    document.body.appendChild(iframe);
    iframe.contentWindow.print();

代码 2(适用于 Chrome,但 contentWindow 为空,因此会为 contentWindow.document 引发错误)-

    const fileURL = URL.createObjectURL(blob);
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.src = fileURL;
    iframe.name = fileName;
    document.body.appendChild(iframe);
    document.getElementsByTagName('iframe')[0].contentWindow.document.execCommand('print', false, null)

我看到了很多问题,但没有一个问题得到解答。我正在使用 Angular 6,所以有没有直接的方法来实现这个或任何可以实现它的库。

【问题讨论】:

    标签: angular typescript internet-explorer iframe blob


    【解决方案1】:

    代码不起作用,因为 IE 和 Edge 都不支持以数据 url 作为 src 属性的 iframe。您可以在caniuse 中查看。更多信息可以参考我在another thread的回答。

    所以我们不能直接在 IE 和 Edge 中打印 blob pdf。有两种解决方法:

    1. 将其保存在 IE 和 Edge 中,然后手动打印。 IE 和 Edge 有自己的 API 用于创建和下载文件,称为msSaveOrOpenBlob。您可以使用如下代码:

      var blob = new Blob([byteArray], { type: 'application/pdf' });
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {  //if IE or Edge
          window.navigator.msSaveOrOpenBlob(blob);
      }
      else {
          var objectUrl = URL.createObjectURL(blob);
          ...
      }
      
    2. 使用PDF.js 解析和渲染pdf。它使用如下链接来显示 pdf:

      http://your_webserver_address/your_PDFjs_foldername/web/viewer.html?file=your_pdf_address
      

    【讨论】:

      猜你喜欢
      • 2021-12-05
      • 1970-01-01
      • 2018-11-14
      • 2016-03-30
      • 2017-12-10
      • 1970-01-01
      • 2011-11-30
      • 2015-10-23
      • 2013-05-12
      相关资源
      最近更新 更多