0

I'm using a webservice to get a base64 string and I need to show that document to the user as a PDF.

var charactersArray = atob(base64String);
var byteNumbers = new ArrayBuffer(charactersArray.length);

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

var byteArray = new Uint8Array(byteNumbers);

var file = new File([byteArray], "file.pdf", {
    type: "application/pdf",
});

I'm then using this "file" to create a url with

var url = URL.createObjectURL(file);

I'm opening this url in a button with the ng-click directive, but I'm getting loading the PDF.

2 Answers 2

2

You need to write the character codes to the byteArray rather than the ArrayBuffer

var charactersArray = atob(base64String);
var len = charactersArray.length;
var byteNumbers = new ArrayBuffer(len);

var byteArray = new Uint8Array(byteNumbers);

for (var i = 0; i < len; i++) {
    byteArray[i] = charactersArray.charCodeAt(i);
}

var file = new File([byteArray], "file.pdf", {
    type: "application/pdf",
});
Sign up to request clarification or add additional context in comments.

Comments

2

I recently work on a project like this and had the same issue. I used the base64-arraybuffer NPM library to convert a base64 string to a byte array.

It's a JS library so it needs to be imported like this after it's installed:

import * as buffer from 'base64-arraybuffer';

The object URL is created like this:

var byteArray = buffer.decode(base64String);
var file = new Blob([byteArray], {type: 'application/pdf'});
var pdfUrl = URL.createObjectURL(file);

I hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.