Displaying Pdf from Arraybuffer

Displaying pdf from arraybuffer

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().

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);
});

});
});

Using 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(); version 2 fetch(), .arrayBuffer()

Creating pdf Blob from array and viewing it

I solved the problem by adding responseType='arraybuffer' to the request config. After that this worked well.

const blob = new Blob([byteArray], {type: 'application/pdf'});
const blobURL = URL.createObjectURL(blob);
window.open(blobURL)

PDF.JS: Render PDF using an ArrayBuffer or Blob instead of URL

You're not passing the response data to PDF.js, but an instance of the resource:

var myPdf = myService.$getPdf({ Id: 123 });
myPdf.$promise.then(function() {
var docInitParams = {
data: myPdf

You haven't shown your code for $getPdf, but I guess that it is something equivalent to

var myService = $resource('/foo', {}, {$getPdf:{responseType: 'arraybuffer'}});
var myPdf = myService.$getPdf();

By default, an AngularJS $resource treats the response as an object (deserialized from JSON) and copies any properties from the object to the resource instance (myPdf in the previous snippet).

Obviously, since your response is an array buffer (or Blob, typed array or whatever), this is not going to work. One of the ways to get the desired response is to use transformResponse to wrap the response object in an object:

var myService = $resource('/foo', {}, {
$getPdf: {
responseType: 'arraybuffer',
transformResponse: function(data, headersGetter) {
// Stores the ArrayBuffer object in a property called "data"
return { data : data };
}
}
});
var myPdf = myService.$getPdf();
myPdf.$promise.then(function() {
var docInitParams = {
data: myPdf.data
};

PDFJS.getDocument(docInitParams).then(function (pdf) {
// ...
});
});

Or simply the following (avoided unnecessary local variables):

myService.$getPdf().$promise.then(function(myPdf) {
PDFJS.getDocument({
data: myPdf.data
}).then(function (pdf) {
// ...
});
});

How can I open a PDF from array of bytes in Angular 9?

Problem can exist in angular's HttpClient which for some reason doesn't read your response as an array buffer correctly. Try to convert it into Uint8Array before, it could give you proper structure that would become ready to further process:

Try that:



const blob = new Blob([new Uint8Array(byteArrays)], { type: "application/pdf" });
const exportUrl = URL.createObjectURL(blob);
window.open(exportUrl);
URL.revokeObjectURL(exportUrl);

How to show pdf in browser using byte array of pdf in javascript?

Found the solution here it is, i was sending byte array from spring controller which is in the form like %PDF-1 %����.
So i send base64 encoded string from spring controller and send the base64 encoded string to browser and it works.

javascript code :

var arrrayBuffer = base64ToArrayBuffer(data); //data is the base64 encoded string
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
var blob = new Blob([arrrayBuffer], {type: "application/pdf"});
var link = window.URL.createObjectURL(blob);
window.open(link,'', 'height=650,width=840');

convert byte array to base64 encoded string in spring controller

String encodedString = Base64.getEncoder().encodeToString(bytearrayofpdf);

Download PDF in browser with blob

I thought that from var uri = 'data:application/pdf;base64,' + blob; in your script, in this case, it is required to convert the downloaded data as the base64. Although I'm not sure about the relationship between the scripts between Node JS: and Javascript:, in your situation, how about the following modification?

From:

let blob = await fetch(url).then(r => r.blob());

To:

let buf = await fetch(url).then((r) => r.arrayBuffer());
const data = Buffer.from(buf).toString("base64");

By this, you can use data as follows.

var uri = 'data:application/pdf;base64,' + data;

Note:

  • As the additional information, for example, if you want to download your Spreadsheet as a PDF file using only Javascript, you can also use the following script. But, in this case, the Spreadsheet is required to be publicly shared. Please be careful about this.

      async function downloadURI(name) {
    var url = "https://docs.google.com/spreadsheets/d/1fLjKASR_g5wsvOjjJi6RclqMVd2o_1On-OfimXtId4E/export?exportFormat=pdf&format=pdf&size=A4&fzr=true&gid=477517973&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&portrait=true&fitw=true&fith=true&top_margin=0.20&bottom_margin=0.20&left_margin=0.20&right_margin=0.20";

    let blob = await fetch(url).then((r) => r.blob());
    var f = new FileReader();
    f.readAsDataURL(blob);
    f.onload = d => {
    var uri = d.target.result;
    var link = document.createElement('a');
    link.download = name;
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    delete link;
    }
    }
    downloadURI("test"+".pdf")

Open pdf from bytes array in angular 5

At last, I was able to render pdf. There were two small mistakes from my side.

1 st Problem was, I gave 'responseType' inside HttpHeaders which was wrong.
It should be outside as below.

2 nd Problem was, even though if you mention as responseType : 'arraybuffer', it was unable to take it. For that you need to mention as responseType : 'arraybuffer' as 'json'.(Reference)

The corrected and working code below.

Trial 3

component.ts (nochanges)

clickEvent(){
this.service.getPDF().subscribe((response)=>{

let file = new Blob([response], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
})

service.ts

getPDF(){
const url = `${this.serviceUrl}/pdf`;

const httpOptions = {
'responseType' : 'arraybuffer' as 'json'
//'responseType' : 'blob' as 'json' //This also worked
};

return this.http.get<any>(url, httpOptions);

}

Referred from the below link

https://github.com/angular/angular/issues/18586



Related Topics



Leave a reply



Submit