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();
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);
});
Here is HTML to display pdf after ajax
<object id="pdfviewer" data="/files/sample.pdf" type="application/pdf" style="width:100%;height:500px;"></object>
I am getting below error
Failed to load PDF document
Please help to fix this. How to display pdf file.
I like guest271314 answer a lot, especially the second version using fetch, but I wanted to add a solution that does not use a polyfill or an experimental technology like
fetch
.This solution uses the native XMLHttpRequest API to create the request. This allows us to change the
responseType
toarrayBuffer
.I forked guest271314s plnkr to show this method in action: http://plnkr.co/edit/7tfBYQQdnih9cW98HSXX?p=preview
From my tests the responce is in response not response.data, so the following should work:
Although it seems JQuery is doing something with the responce causing a blank PDF output... (PDF is blank when downloading using javascript). This will work:
jQuery.ajax()
does not have aresponseType
setting by default. You can use a polyfill, for example jquery-ajax-blob-arraybuffer.js which implements binary data transport, or utilizefetch()
.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.Using
fetch()
,.arrayBuffer()
plnkr http://plnkr.co/edit/9R5WcsMSWQaTbgNdY3RJ?p=preview
version 1
jquery-ajax-blob-arraybuffer.js
,jQuery.ajax()
; version 2fetch()
,.arrayBuffer()