I am using Ionic React with Capacitor 7
I am unable to download receipt after it is generated in pdf format.
Sharing Receipt seems to work fine for both iOS and Android.
But I cannot download it.
const downloadReceipt = async () => {
setIsGeneratingPDF(true);
try {
const pdf = await generateReceiptPDF();
if (!pdf) {
throw new Error('PDF generation failed');
}
const fileName = `receipt_${id}_${Date.now()}.pdf`; // Unique file name
const folderPath = 'Receipts'; // Subfolder for organization
const fullPath = `${folderPath}/${fileName}`;
// Convert to Blob
const pdfBlob = new Blob([pdf.output('blob')], { type: 'application/pdf' });
const pdfBase64 = await blobToBase64(pdfBlob);
// Define directory based on platform (use Documents for better compatibility)
const directory = Directory.Documents;
// Request permissions for Android
if (Capacitor.getPlatform() === 'android') {
await requestPermissions();
}
// Ensure directory exists
await ensureDirectoryExists(directory, folderPath);
// Delete file if it exists
await deleteIfExists(directory, fullPath);
// Write the file
await Filesystem.writeFile({
path: fullPath,
data: pdfBase64,
directory,
});
console.log('File written successfully');
const fileUri = await Filesystem.getUri({
path: fullPath,
directory,
});
if (Capacitor.getPlatform() === 'ios') {
// Use Share API on iOS to allow the user to download or share the file
await Share.share({
title: `Receipt #${id}`,
text: `Dear ${user?.name} ${user?.last_name}, here is your receipt #${id}!`,
url: fileUri.uri,
dialogTitle: 'Share Receipt',
});
} else if (Capacitor.getPlatform() === 'android') {
// Open PDF File on Android
// await Browser.open({ url: fileUri.uri });
} else {
// For web, trigger direct download
pdf.save(fileName);
}
setToastMessage('Receipt downloaded successfully!');
setToastColor('success');
setShowToast(true);
} catch (error) {
console.error('Error downloading receipt:', error);
setToastMessage('Failed to download receipt. Please try again.');
setToastColor('danger');
setShowToast(true);
} finally {
setIsGeneratingPDF(false);
}
};```