How to Build Pdf File from Binary String Returned from a Web-Service Using JavaScript

Download PDF from binary string in Javascript

The binary string arrives at the corrupted front, so I decided to convert it to base64 on the back end and send it like this, but that's because I have autonomy from the back end, I don't know how it would be resolved for a non-public api and other cases.

failed to dowload pdf from binary string returned from a web-service

[https://stackoverflow.com/questions/49134555/wrong-encoding-on-javascript-blob-when-fetching-file-from-server]

PDF files are really sensitive in terms of encoding. You need to make sure that the encoding is not changed in the process of retrieving the PDF binary data.

By default axios uses JSON as response type, so you need to specify the configuration entry:

axios.get(url, {responseType: "arraybuffer"}) ...

Create and Download PDF file from binary string with JS/TS

Scenario

You want the file to be downloaded when the user clicks the link.

Solution 1-

Directly put the link in <a> tag.

Cons- Error message can not be shown on the screen if something went wrong.

So it leads to the next solution.

Solution 2-

Hit the URL as an API and download the file if you get the success message.
For this, I use File-server.js

**Don't forget to set the {responseType: 'blob'}, while making the request

http.get<string>(`${baseUrl}/${id}.pdf`, {responseType: 'blob'})

as we don't want the response with Content-Type: application/json

sample code:

import FileSaver from 'file-saver';

downloadPdf() {
var blob = new Blob([data], {type: "application/pdf"});
FileSaver.saveAs(blob, "filename");
}

C#: Display PDF in a new tab from byte[] returned by Web Service

AJAX IS NOT NEEDED:

    <a href="Services/ProofOfDeliveryData.asmx/RetrieveSPODData?id=<%=TransportationDocument != null ? TransportationDocument.BusinessID.ToString() : String.Empty %>" Target="_blank">
<img alt="SPOD" src="images/icons/adobe_acrobat_icon.png">
</a>

Just make so the link will directly goes to the web service and it is working wonder.



Related Topics



Leave a reply



Submit