PDF Blob is showing nothing in new tab, using stream from backend - javascript

I used https://github.com/barryvdh/laravel-dompdf
stream method for sending a response to front-end.
Here is my code which I wrote for opening pdf in a new tab.I'm calling stream from backend API in result it gives a response but when I try to create blob it shows nothing in PDF.
APICaller({
method: 'get',
responseType: "arraybuffer",
headers: {
'Accept': 'application/pdf'
},
endpoint: gep('generate/certificate?path=certificate.pdf', 'v3'),
}).then( (data) => {
var file = new Blob([data.data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
here is Empty PDF

I had a similar issue with axios, it doesn't work for downloading files using Blob. Use XMLHttpRequest and do the similar response handler in its on('load') event to achieve file download.

Related

How to save PDF format file if I get the Axios response content-type of application-stream?

I would like to save a octet-stream type data to a pdf file, the data is correct as I have tried to use Postman "Send and Save" function to get and open the pdf file successfully.
However, once I call axios request and receive the response from the server, I cannot get the correct pdf file. After I got the pdf file, it seems that the file is broken, can I cannot open it correctly.
Here's the header of the response:
enter image description here
axios.create({
baseURL: link,
timeout: 60000,
headers: {
Authorization: token
}
}).post(apiUrl, {
.
.
.
}).then(res=>{
var file_data = res["data"];
var file_type = res["headers"]["content-type"];
var blob = new Blob([file_data], {type: file_type});
saveAs(blob, "Test.pdf")
});
When downloading binaries with Axios, the format of the data returned by the server needs to be specified with the request. In the case of a PDF file, generally "arraybuffer" needs to be used.
axios.get(
"https://example.com/example.pdf",
{
responseType: "arraybuffer"
}
);
As per the documentation, the valid options are:
// `responseType` indicates the type of data that the server will respond with
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
// browser only: 'blob'
// default: 'json'
Axios documentation
I found the solution for this problem, it seems that the size of the file is different with the original one, and I make the following changes to receive the data in form of Blob object to solve it.
axios.create({
baseURL: link,
timeout: 60000,
responseType: 'blob'
headers: {
Authorization: token
}
}).post(apiUrl, {
.
.
.
}).then(res=>{
var file_data = res["data"];
var file_type = res["headers"]["content-type"];
saveAs(file_data, "Test.pdf");
});

Generating PDF from wkhtml using PHP wrapper, when sent back to Angular 4, opens only in Chrome

I generate a html in Angular 4, send it to PHP wrapper for wkhtmltopdf, after that it is returned to Angular, and this works fine in Chrome, the PDF is displayed. I need it to be displayed also in Firefox. This is the code that sends the PDF to PHP:
public getPdf() {
const html = this.pdfEl.innerHTML;
alert(html);
this.rest.post(
'/pdf',
{ html },
{
headers: new Headers(),
responseType: ResponseContentType.Blob
}
).subscribe(
(value) => {
//alert('subscribe receiver in pdf button directive');
this.url = URL.createObjectURL(value.blob());
open(this.url);
});
}
Things that I have tried so far, but none worked are:
1. Setting this.url = URL.createObjectURL(new Blob([value.blob()], {type: 'application/pdf'})); instead of this.url = URL.createObjectURL(value.blob());
2. Setting this as headers instead of new Headers() :
new Headers({
'Content-Type': 'application/json',
'Accept': 'application/pdf'
}),
any suggestions to resolve this, guys? Thanks.
If value.blob() returns a Blob you have also set the blob type to application/pdf. That has to be done on the response side, because the property is read only.
Blob Documentation
Blob.type Read only A string indicating the MIME type of the data
contained in the Blob. If the type is unknown, this string is empty.
Or if you value.blob() returns only an array buffer you have to create a new Blob on your own.
new Blob([value.blob()], {type: 'application/pdf'});

Pass image as a binary representation

I'm invoking an api that accepts image in the binary representation form. I'm uploading the image through a file upload html.
Here is my code:
let fileReader = new FileReader();
let fileData = fileReader.readAsArrayBuffer(text.data.uploadedFile);
yield call(fetchJson, 'url/fetch', {
method: 'POST',
headers: {
Authentication: 'Basic <key>',
'Content-type': 'image/jpeg'
},
body: fileData
});
I get fileData as undefined and my request does not go through. This 3rd party API accepts image in binary representation form in the body.
This is equivalent to the following in POSTMAN:
This works in POSTMAN but not sure how to achieve this using code.
I set uploadedFile on front-end using: event.target.files[0]

Posting a base64 encoded PDF file with AJAX

I'm trying to post a base64-encoded PDF file to a Zendesk file upload API endpoint but the file URL returned from the API shows that the file is corrupted.
First I receive the PDF as a base64-encoded string from a separate API call. Let's call it base64String.
If I do window.open("data:application/pdf;base64," + base64String) I can view the PDF in my browser.
Now I am trying to follow the documentation here for uploading files via the API. I can successfully complete a cURL call as shown in the example. However, the jQuery AJAX call will corrupt the PDF file.
client.request({
url: '/api/v2/uploads.json?filename=test.pdf',
type: 'POST',
data: atob(base64String),
contentType: 'application/binary'
}).then(function(data) {
window.open(data.upload.attachment.content_url); // corrupt file
}, function(response) {
console.log("Failed to upload file to Zendesk.");
console.log(response);
});
Like I said, this will succeed but when I visit the content_url the PDF does not display. I am quite sure the file is being corrupt in the POST request.
I have tried uploading the file as a base64 string (without decoding with atob()) with no luck among other things.
UPDATE
I'm still not able to view the PDF after converting the base64 string to blob.
var blob = base64ToBlob(base64String);
console.log(blob); // Blob {size:39574, type: "application/pdf"}
client.request({
url: '/api/v2/uploads.json?filename=test.pdf',
type: 'POST',
data: blob,
processData: false,
contentType: 'application/pdf'
}).then(function(data) {
window.open(data.upload.attachment.content_url); // corrupt file
}, function(response) {
console.log("Failed to upload file to Zendesk.");
console.log(response);
});
function base64ToBlob(byteString) {
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ab], {type: 'application/pdf'});
return blob;
};
I learned that the Zendesk app framework uses a jQuery AJAX wrapper for requests and the arraybuffer type is unsupported, so the file was getting corrupted. The app framework team has fixed the issue.

Saving a PDF returned by service

I'm using FileSaver.js and Blob.js into an Angular JS application to save a PDF returned by a REST service (which returns an array of bytes representing the file).
var headers = {headers: {"Authorization":"Bearer "+token, "Accept":"application/pdf"}};
$http.get(URL, headers)
.success(function (data) {
var blob = new Blob([data], {type: 'application/pdf'});
saveAs(blob, 'contract.pdf');
});
the file gets saved with the right type and the number of pages is correct, but it's totally blank.
Opening it with an editor, it turned out the it contains only the first part of the data returned by the server, like it's truncated.
Thank everyone for helping out!
$http.get probably isn't handling binary data correctly. Try $http({method: "GET", url: URL, responseType: "arraybuffer", ...}) (see angularjs) to get a binary object you can put in for data.
You can also use responseType: "blob" so you don't even have to create var blob, but I think that responseType has less browser support.
Adding a response type to the config argument worked for me. Try:
var config = { responseType: 'blob', headers: {"Authorization":"Bearer "+token,
"Accept":"application/pdf"}};
$http.get(URL, config)
.success(function (data) {
var blob = new Blob([data], {type: 'application/pdf'});
saveAs(blob, 'contract.pdf');
});

Categories