javascript - 如何使用 JavaScript 从 Web 服务返回的二进制字符串构建 PDF 文件

标签 javascript jquery pdf cross-browser binary-data

我正在尝试从二进制流中构建一个 PDF 文件,我收到的二进制流是 Ajax 请求的响应。

通过XmlHttpRequest我收到以下数据:

%PDF-1.4....
.....
....hole data representing the file
....
%% EOF

到目前为止,我尝试的是通过 data:uri 嵌入我的数据。现在,没有任何问题,并且工作正常。不幸的是,它在 IE9 和 Firefox 中不起作用。可能的原因是 FF 和 IE9 在使用 data-uri 时存在问题。

现在,我正在寻找适用于所有浏览器的解决方案。这是我的代码:

// responseText encoding 
pdfText = $.base64.decode($.trim(pdfText));

// Now pdfText contains %PDF-1.4 ...... data...... %%EOF

var winlogicalname = "detailPDF";
var winparams = 'dependent=yes,locationbar=no,scrollbars=yes,menubar=yes,'+
            'resizable,screenX=50,screenY=50,width=850,height=1050';

var htmlText = '<embed width=100% height=100%'
                     + ' type="application/pdf"'
                     + ' src="data:application/pdf,'
                     + escape(pdfText)
                     + '"></embed>'; 

                // Open PDF in new browser window
                var detailWindow = window.open ("", winlogicalname, winparams);
                detailWindow.document.write(htmlText);
                detailWindow.document.close();

正如我所说,它在 Opera 和 Chrome 上运行良好(Safari 尚未经过测试)。使用 IE 或 FF 将打开一个空白的新窗口。

是否有任何解决方案,例如在文件系统上构建 PDF 文件 为了让用户下载它?我需要适用于所有浏览器的解决方案,至少适用于 IE、FF、Opera、Chrome 和 Safari。

我无权编辑 Web 服务实现。所以它必须是客户端的解决方案。有什么想法吗?

最佳答案

Is there any solution like building a pdf file on file system in order to let the user download it?

尝试将 XMLHttpRequestresponseType 设置为 blob ,替换 a 处的 download 属性window.open 元素允许从 XMLHttpRequest 下载响应作为 .pdf 文件

var request = new XMLHttpRequest();
request.open("GET", "/path/to/pdf", true); 
request.responseType = "blob";
request.onload = function (e) {
    if (this.status === 200) {
        // `blob` response
        console.log(this.response);
        // create `objectURL` of `this.response` : `.pdf` as `Blob`
        var file = window.URL.createObjectURL(this.response);
        var a = document.createElement("a");
        a.href = file;
        a.download = this.response.name || "detailPDF";
        document.body.appendChild(a);
        a.click();
        // remove `a` following `Save As` dialog, 
        // `window` regains `focus`
        window.onfocus = function () {                     
          document.body.removeChild(a)
        }
    };
};
request.send();

关于javascript - 如何使用 JavaScript 从 Web 服务返回的二进制字符串构建 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45762621/

相关文章:

javascript - JavaScript 匿名函数可以返回自身吗?

pdf - pdf.js 以外的任何选项,用于在所有浏览器中以编程方式显示 PDF 文件

jquery - 为什么这个 select id 不起作用?

javascript - 验证对话框中未触发成功函数

html - Coldfusion PDF 中的字符集

azure - 使用 google gview 在 iframe 中嵌入 Azure blob pdf 文件

javascript - 无法作用于 iframe

javascript - 使用 VeeValidate,我如何查看某个字段是否已被触摸并且是否有效?

javascript - 使用 JQuery 插入 rails partial 时遇到问题

javascript - 检查元素是否有特定的 id