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
For Loop With Two Array in JavaScript
How to Iterate Through Json Nested Objects With Ngfor
Swiper Slider - Thumbs Gallery With Slidetoclickedslide Do Not Work Properly
How to Set Top and Bottom Margin in Addhtml
Label and Input Fields on the Same Line
Puppeteer Wait Until Page Is Completely Loaded
How to Make an Empty String Array in Typescript
Syntaxerror: Unexpected Token O in Json At Position 1
Detect If Html5 Video Element Is Playing
Youtube API - Failed to Execute 'Postmessage' on 'Domwindow'
How to Change the Image(Slider) One by One Every 3 Seconds in JavaScript
Vuejs Error, Invalid Prop: Type Check Failed for Prop. Expected Date, Got Number With Value
How to Change Font-Size in Vuetify Component
Array Push Is Overwriting the Existing Array
How to Convert from Google Sheet Date Number Value to JavaScript Date