使用 PDFObject 嵌入 Blob

Embed a Blob using PDFObject

我正在使用:https://pdfobject.com/

在我的网络应用程序上显示嵌入的 pdf 文件。但是我无法渲染从 blob 创建的 pdf

这是我试过的:

var arrayBufferView = new Uint8Array(response.Body.data);
var file = new Blob([arrayBufferView], {
    type: response.ContentType
});
var url = window.URL.createObjectURL(file)
PDFObject.embed(url, "#my-container");

在 html 上得到这个结果:

<div id="my-container" class="ng-scope pdfobject-container">

    <embed class="pdfobject" src="blob:http%3A//localhost%3A4000/869a8d9a-7eaa-48dd-99aa-49bf299114aa" type="application/pdf" style="overflow: auto; width: 100%; height: 100%;" internalinstanceid="88">

</div>

但是嵌入容器在我的浏览器中不显示任何内容。我正在使用 Chrome 51.0.2704.103 m

尝试使用 <iframe> 元素,请求资源作为 Blob

html

<div id="my-container" class="ng-scope pdfobject-container">
    <iframe src="" type="application/pdf" width="100%" height="100%" style="overflow: auto;">
    </iframe>
</div>

javascript

var xhr = new XMLHttpRequest();
// load `document` from `cache`
xhr.open("GET", "/path/to/file.pdf", true); 
xhr.responseType = "blob";
xhr.onload = function (e) {
    if (this.status === 200) {
        // `blob` response
        console.log(this.response);
        var file = window.URL.createObjectURL(this.response);
        document.querySelector("iframe").src = file;

    }
};
xhr.send();

plnkrhttp://plnkr.co/edit/9E5sGfMhUeIWV9yodAUd?p=preview

我相信这就是您要找的。

function previewPdf(billName) {

var xhr = new XMLHttpRequest();
xhr.open('GET', 'home/download?pdfBillId=' + billName, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
    if (this.status == 200) {
        var file = new Blob([this.response], { type: 'application/pdf' });
        var fileURL = URL.createObjectURL(file);
        var viewer = $('#viewpdf');
        PDFObject.embed(fileURL, viewer);
    }
};
xhr.send(); 
}

只是通过使用 iframe 对答案的补充,我们还需要在此使用 pdfjs 查看器,否则它会下载。

<div id="my-container" class="PDFObject-container">
    <iframe src="/pdfjs/web/viewer.html?file=blob:http://xxx:8098/fsadfsaf" type="application/pdf" width="1000" height="600" style="overflow: auto;">
    </iframe>
</div>

blob 是根据使用 Javascript

创建的二进制响应创建的
const url = window.URL.createObjectURL(new Blob([response], { type: 'application/pdf' }));

我希望 PDFObject 可以在不使用 iframe 的情况下完成工作,但经过测试,它并不成功。

而不是使用:

 var url = window.URL.createObjectURL(file)

尝试使用:

 var url = window.URL.createObjectURL(file, { type: 'application/pdf' })