To add a PDF download feature in your Ionic 6 application using Capacitor, the steps are largely similar for both iOS and Android, with the primary difference being the permissions required for each platform. Below is a detailed guide tailored specifically for iOS, but keep in mind that about 80% of the steps are identical to those for Android, with adjustments mainly in the permissions section.
Step 1: Install Required Plugins
First, ensure that you have the required plugins installed in your Ionic project. If you haven’t done so already, run the following commands:
npm install @capacitor/filesystem
ionic cap sync
This installs the Capacitor Filesystem plugin, which allows you to read and write files on the device.
Step 2: Update Main.ts
Next, you need to import the Filesystem plugin in your main.ts
file and add it to your providers array:
// Import the Filesystem plugin
import { Filesystem, Directory } from ‘@capacitor/filesystem’;
// Add it to your providers array
providers: [
File,
],
Step 3: Save PDF Data
If you have base64 encoded PDF data, you can use the following method to save it:
// param 1 is your base64 content
// param 2 is custom file name
// Call this method where you want to trigger save PDF event
this.savePdf(resultData.reportPDF, 'sample-report.pdf');
// Method to save PDF
// fileName : only file file name
async savePdf(base64String: string, fileName: string) {
try {
// Remove prefix if present
const base64Data = base64String.startsWith('data:application/pdf;base64,')
? base64String.split(',')[1]
: base64String;
// Write the file to the application's data directory
const result = await Filesystem.writeFile({
path: '<< folder name >>'+fileName,
data: base64Data,
directory: Directory.Documents,
recursive: true,
});
console.log('File saved at:', result.uri);
// Downloaded file url will be folder/sample-report.pdf
this.downloadedFileURL = '<< folder name >>/'+fileName;
this.openPdfFile();
} catch (error) {
console.error('Error saving file:', error);
throw error;
}
}
This method handles saving a base64 encoded PDF to the device’s Documents directory.
Step 4: Install File Opener Plugin
To open the saved PDF file, you’ll need an additional plugin. Install it using:
npm install @awesome-cordova-plugins/file-opener
npm install cordova-plugin-file-opener2
ionic cap sync
Step 5: Update Main.ts for File Opener
Import the FileOpener plugin and add it to your providers:
// Import FileOpener plugin
import { FileOpener } from '@awesome-cordova-plugins/file-opener/ngx';
// Add it to your providers array
providers: [
FileOpener,
],
Step 6: Open Local Downloaded File
You can now implement a method to open the downloaded PDF file:
async openPdfFile() {
try {
const filePath = await Filesystem.getUri({
path: this.downloadedFileURL,
directory: Directory.Documents,
});
console.log('Opening file at:', filePath.uri);
this.fileOpener.open(filePath.uri, 'application/pdf')
.then(() => console.log('File opened successfully'))
.catch((error) => console.error('Error opening file:', error));
} catch (error) {
console.error('Error fetching file URI:', error);
}
}
This method retrieves the URI of the saved PDF and opens it using the default PDF viewer on the device.
Step 7: List All Downloaded Files
If you want to get a list of all downloaded files in a specific folder, implement this method:
async listAllDownloadedFiles() {
try {
const result = await Filesystem.readdir({
path: '<< folder name >>', // Specify your folder name here
directory: Directory.Documents,
});
console.log('Files in provided folder:', result.files);
return result.files; // Returns an array of file names
} catch (error) {
console.error('Error reading folder:', error);
throw error;
}
}
This function reads all files from a specified directory within the Documents folder.
Step 8: Add Permissions for iOS
For iOS applications, you need to add a usage description in your Info.plist
file:
<key>NSDocumentsUsageDescription</key>
<string>App needs access to documents for audio processing.</string>
This informs users why your app requires access to their documents.
By following these steps, you can successfully implement a feature in your Ionic application that allows users to download and view PDF files. This enhances user experience by providing easy access to important documents directly within your app.
Learn more Ionic 6 Made Easy: Implementing PDF Downloads with Capacitor