0

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);
  • Why not use https://mozilla.github.io/pdf.js/? – Donal Jun 09 '15 at 17:21
  • If all you are doing on the browser side is save the file, can't you just let the browser do it by pointing it to the document's URI? On the server you can then serve up the file in binary with the appropriate content-disposition setting. – Santosh Jun 10 '15 at 07:41

1 Answers1

0

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.

Community
  • 1
  • 1