How to convert pdf to UInt8Array

how to convert pdf to base64 to UInt8Array I also search this on google but can’t get any proper solution

What is your use case, do you want to download a PDF and store it inside your File System?

yes I want to download PDF store in the data directory and display it using pdfjs,
and I download it successfully but cant display it
if i use this function to covert it into UInt8Array
in base64 I pass path of downloaded PDF file

base64ToUint8Array(base64) {
var raw = atob(base64);
var uint8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
console.log(“data…”, JSON.stringify(uint8Array));
return uint8Array;
}

I got the error: ERROR DOMException: Failed to execute ‘atob’ on ‘Window’: The string to be decoded is not correctly encoded.

It might be the case that the binary data you get beck from your API is not working with that function. Just recently I had the same trouble, in the end this function worked for me:

function base64ToArrayBuffer(data) {
	var input = data.substring(data.indexOf(',') + 1);
	var binaryString = window.atob(input);
	var binaryLen = binaryString.length;
	var bytes = new Uint8Array(binaryLen);
	for (var i = 0; i < binaryLen; i++) {
		var ascii = binaryString.charCodeAt(i);
		bytes[i] = ascii;
	}
	return bytes;
};

I then stored it by using the function above and converting that data to a blob:

var arrBuffer = base64ToArrayBuffer(data);
var blob = new Blob([arrBuffer], { type: type });

Finally write the file using writeFile() with the blob as data!

1 Like

Thnx @saimon
in writeFile() you give path of dataDirectory or path of assets folder ??

You can use whatever you like, the most basic example would be:

let path = this.file.dataDirectory;

this.file.writeFile(path, fileName, blob).then(res => {
    // File is stored
  }, err => {
    console.log('error: ', err);
  });

ok thnx @saimon :slight_smile: