In my Ionic/Capacitor/Nuxt project, I am trying to download a pdf file from url and save it to phone local storage using Capacitor Filesystem/blob-writer api. On both the packages I am able to download the file but the file was not opened by the pdf reader. On further investigation I have noticed while opening the pdf file from the Android emulator local storage was blank white, but have exact number of pages to that of the original pdf file.
But, while running it on the browser everything was working fine.
This are the codes and approaches below that I have tried for Capacitor Filesystem.
const response = await fetch(pdfUrl);
const data = await response.blob(); // Convert to blob
const arrayBuffer = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = (err) => reject(err);
reader.readAsArrayBuffer(data);
});
const base64 = arrayBufferToBase64(arrayBuffer);
const result = await Filesystem.writeFile({
path: pdfName,
data: base64,
directory: Directory.Documents, // or another directory
recursive: true
});
// arrayBufferToBase64 function
function arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
Any suggestions/help will be highly appreciated.