Transfer PDF in JSON From ASP.NET to AngularJS Using Base64 Not Producing Same File

885 Views Asked by At

I encoded a PDF file as Base64 and assign it to a property of my model object in ASP.NET WEB API which gets transferred as JSON. The response comes back to my client AngularJS application and the file is saved as I expect. The file size is one and 1/3 larger and the special accent characters are showing as two different characters and I receive a message from Adobe Reader that the embedded font doesn't open, but the PDF does open.

I suspect the problem is with the atob() decoding on the JavaScript side or with the encoding of the web page. I tried using utf-8, utf-16 and utf-32 for the web page with no difference on the result.

ASP.NET code:

byte[] document = File.ReadAllBytes(publishDocument.Path);
publishDocument.Document = Convert.ToBase64String(document, 0, document.Length);

JavaScript:

var content = atob(data.document);
var blob = new Blob([content], {
       type: "application/pdf"
});
saveAs(blob, data.name);
1

There are 1 best solutions below

0
On

I found the answer here: Save base64 string as PDF at client side with JavaScript

I replace the built-in atob and Blob function with this one:

function b64toBlob(b64Data, contentType) {
contentType = contentType || '';
var sliceSize = 512;
b64Data = b64Data.replace(/^[^,]+,/, '');
b64Data = b64Data.replace(/\s/g, '');
var byteCharacters = window.atob(b64Data);
var byteArrays = [];

for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    var slice = byteCharacters.slice(offset, offset + sliceSize);

    var byteNumbers = new Array(slice.length);
    for (var i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
    }

    var byteArray = new Uint8Array(byteNumbers);

    byteArrays.push(byteArray);
}

var blob = new Blob(byteArrays, {type: contentType});
return blob;

For some reason, the .NET Base64 and the JavaScript Base64 are not the same.