从 arraybuffer 显示 pdf [英] Displaying pdf from arraybuffer
问题描述
我正在从此代码返回来自 laravel dompdf 的流数据
I am returning stream data from laravel dompdf from this code
$pdf = App::make('dompdf.wrapper');
$pdf->loadHTML("<div>This is test</div>");
return $pdf->stream();
这是我的 JS ajax 代码
And this is my JS ajax code
$.ajax({
type:"GET",
url: "/display",
responseType: 'arraybuffer'
}).done(function( response ) {
var blob = new Blob([response.data], {type: 'application/pdf'});
var pdfurl = window.URL.createObjectURL(blob)+"#view=FitW";
$("#pdfviewer").attr("data",pdfurl);
});
这是在ajax后显示pdf的HTML
Here is HTML to display pdf after ajax
<object id="pdfviewer" data="/files/sample.pdf" type="application/pdf" style="width:100%;height:500px;"></object>
我收到以下错误
无法加载 PDF 文档
Failed to load PDF document
请帮忙解决这个问题.如何显示pdf文件.
Please help to fix this. How to display pdf file.
推荐答案
jQuery.ajax()
默认没有 responseType
设置.您可以使用 polyfill,例如实现二进制数据的 jquery-ajax-blob-arraybuffer.js传输,或使用 fetch()
.
jQuery.ajax()
does not have a responseType
setting by default. You can use a polyfill, for example jquery-ajax-blob-arraybuffer.js which implements binary data transport, or utilize fetch()
.
另请注意,chrome、chromium 在 和
元素中显示
.pdf
时存在问题,请参阅 使用带有 blob URL 的对象嵌入标签显示 PDF, 使用 PDFObject 嵌入 Blob.使用 元素替换
元素.
Note also, chrome, chromium have issues displaying .pdf
at either <object>
and <embed>
elements, see Displaying PDF using object embed tag with blob URL, Embed a Blob using PDFObject. Substitute using <iframe>
element for <object>
element.
$(function() {
var pdfsrc = "/display";
var jQueryAjaxBlobArrayBuffer = "https://gist.githubusercontent.com/SaneMethod/"
+ "7548768/raw/ae22b1fa2e6f56ae6c87ad0d7fbae8fd511e781f/"
+ "jquery-ajax-blob-arraybuffer.js";
var script = $("<script>");
$.get(jQueryAjaxBlobArrayBuffer)
.then(function(data) {
script.text(data).appendTo("body")
}, function(err) {
console.log(err);
})
.then(function() {
$.ajax({
url: pdfsrc,
dataType: "arraybuffer"
})
.then(function(data) {
// do stuff with `data`
console.log(data, data instanceof ArrayBuffer);
$("#pdfviewer").attr("src", URL.createObjectURL(new Blob([data], {
type: "application/pdf"
})))
}, function(err) {
console.log(err);
});
});
});
使用fetch()
, .arrayBuffer()
var pdfsrc = "/display";
fetch(pdfsrc)
.then(function(response) {
return response.arrayBuffer()
})
.then(function(data) {
// do stuff with `data`
console.log(data, data instanceof ArrayBuffer);
$("#pdfviewer").attr("src", URL.createObjectURL(new Blob([data], {
type: "application/pdf"
})))
}, function(err) {
console.log(err);
});
plnkr http://plnkr.co/edit/9R5WcsMSWQaTbgNdY3RJ?p=preview
version 1 jquery-ajax-blob-arraybuffer.js
, jQuery.ajax()
;版本 2 fetch()
, .arrayBuffer()
version 1 jquery-ajax-blob-arraybuffer.js
, jQuery.ajax()
; version 2 fetch()
, .arrayBuffer()
这篇关于从 arraybuffer 显示 pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!