从 BLOB 打印 PDF

Tom*_*oro 4 javascript ajax jquery

我从外部 API 获取 PDF 文件,使用此代码我可以正确下载该文件:

\n
var req = new XMLHttpRequest();\n    req.open("POST", url, true);\n    req.responseType = "blob";\n    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");\n    req.send(data);\n\n    req.onload = function (event) {\n       var blob = req.response;\n       var link=document.createElement('a');\n       link.href=window.URL.createObjectURL(blob);\n       link.download="receipt_" + new Date() + ".pdf";\n       link.click();\n    };\n
Run Code Online (Sandbox Code Playgroud)\n

但我真正需要的是打印文件而不打开它,我尝试了类似的方法

\n
window.open(window.URL.createObjectURL(blob));\nwindow.print();\n
Run Code Online (Sandbox Code Playgroud)\n

但是,当这样做时,文件无法正确显示,它显示如下:

\n
PDF-1.7\n%\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\n6 0 obj\n<< /Type /Page /Parent 1 0 R /LastModified (D:20201027223421-03'00') ... bla bla\n
Run Code Online (Sandbox Code Playgroud)\n

提前致谢!

\n

Tom*_*oro 12

我已经使用以下方法解决了这个问题:

req.onload = function (event) {
    var blob = new Blob([req.response], {type: 'application/pdf'}); //this make the magic
    var blobURL = URL.createObjectURL(blob);

    iframe =  document.createElement('iframe'); //load content in an iframe to print later
    document.body.appendChild(iframe);

    iframe.style.display = 'none';
    iframe.src = blobURL;
    iframe.onload = function() {
      setTimeout(function() {
        iframe.focus();
        iframe.contentWindow.print();
      }, 1);
    };
};
Run Code Online (Sandbox Code Playgroud)