import React, { useContext } from 'react';
import { StyleSheet, View, Button, Alert } from 'react-native';
import * as Print from 'expo-print';
import * as Sharing from 'expo-sharing';
import { MediaContext } from '../context/MediaContext';
const generatePDF = async () => {
// Create HTML content for PDF
let mediaHtml = '';
code
if (media.photo) {
mediaHtml += `<h2>Captured Photo</h2><img src="${media.photo}" style="width:100%; height:auto;" />`;
}
if (media.video) {
// Note: Embedding video in PDF is not widely supported
mediaHtml += `<h2>Recorded Video</h2>
<p>Video recorded at: <a href="${media.video}">Download Video</a></p>`;
}
if (media.audio) {
// Note: Embedding audio in PDF is not widely supported
mediaHtml += `<h2>Recorded Voice</h2>
<p>Audio recorded at: <a href="${media.audio}">Download Audio</a></p>`;
}
const htmlContent = `
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
h1 { text-align: center; }
img { max-width: 100%; height: auto; }
a { color: blue; text-decoration: none; }
</style>
</head>
<body>
<h1>Consent Document</h1>
<p>${legalText}</p>
${mediaHtml}
</body>
</html>
`;
try {
// Generate PDF from HTML
const { uri } = await Print.printToFileAsync({ html: htmlContent });
// Share or download the PDF
await Sharing.shareAsync(uri);
} catch (error) {
Alert.alert('Error', 'Failed to generate PDF: ' + error.message);
}
};
return (
);
};
// --- Legal Text (Should be imported or passed as a prop) ---
const legalText = `YOUR LEGAL TEXT GOES HERE...
Assistant
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel turpis at quam aliquet lobortis. Integer sit amet ligula vitae justo commodo fermentum. Donec vitae massa a augue blandit porttitor. Proin id purus nec justo mollis finibus sit amet at justo. Mauris ac sem vitae nisl interdum interdum.`;
const styles = StyleSheet.create({
section: {
marginBottom: 30,
backgroundColor: '#ffffff',
padding: 15,
borderRadius: 10,
elevation: 2, // For Android
shadowColor: '#000', // For iOS
shadowOffset: { width: 0, height: 2 }, // For iOS
shadowOpacity: 0.25, // For iOS
shadowRadius: 3.84, // For iOS
alignItems: 'center',
},
});
export default PDFGenerator;
how come it goes to sharing. I just want to download the pdf not share it. Also once downloaded there should be an icon that takes you to where it was downloaded
To modify your PDFGenerator component to download the PDF locally instead of sharing it, and to provide an icon that opens the downloaded PDF, you can follow these steps:
Remove the Sharing Functionality: Eliminate the Sharing.shareAsync part since you don't want to share the PDF.
Save the PDF Locally: Use Expo's FileSystem to save the generated PDF to the device's local storage.
Display an Icon to Open the PDF: Add an icon (e.g., a button) that, when pressed, opens the saved PDF using the device's default PDF viewer.
Here's how you can implement these changes:
1. Install Necessary Dependencies
Make sure you have the following Expo packages installed:
bash
expo install expo-file-system expo-file-viewer
expo-file-system: For handling file operations.
expo-file-viewer: To open the PDF using the device's default viewer.
2. Update PDFGenerator.js
Below is the updated code with detailed comments explaining each part:
javascript
// components/PDFGenerator.js
import React, { useContext, useState } from 'react';
import { StyleSheet, View, Button, Alert, TouchableOpacity, Text } from 'react-native';
import * as Print from 'expo-print';
import * as FileSystem from 'expo-file-system';
import FileViewer from 'expo-file-viewer';
import { MediaContext } from '../context/MediaContext';
import { Ionicons } from '@expo/vector-icons'; // For the icon
const PDFGenerator = () => {
const { media } = useContext(MediaContext);
const [pdfUri, setPdfUri] = useState(null); // State to store PDF URI
const generatePDF = async () => {
// Create HTML content for PDF
let mediaHtml = '';
if (media.photo) {
mediaHtml += `<h2>Captured Photo</h2><img src="${media.photo}" style="width:100%; height:auto;" />`;
}
if (media.video) {
// Note: Embedding video in PDF is not widely supported
mediaHtml += `<h2>Recorded Video</h2>
<p>Video recorded at: <a href="${media.video}">Download Video</a></p>`;
}
if (media.audio) {
// Note: Embedding audio in PDF is not widely supported
mediaHtml += `<h2>Recorded Voice</h2>
<p>Audio recorded at: <a href="${media.audio}">Download Audio</a></p>`;
}
const htmlContent = `
<html>
<head>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
h1 { text-align: center; }
img { max-width: 100%; height: auto; }
a { color: blue; text-decoration: none; }
</style>
</head>
<body>
<h1>Consent Document</h1>
<p>${legalText}</p>
${mediaHtml}
</body>
</html>
`;
try {
// Generate PDF from HTML
const { uri } = await Print.printToFileAsync({ html: htmlContent });
// Define a path to save the PDF
const pdfPath = FileSystem.documentDirectory + 'ConsentDocument.pdf';
// Move the PDF to the desired location
await FileSystem.moveAsync({
from: uri,
to: pdfPath,
});
// Update state with the new PDF URI
setPdfUri(pdfPath);
Alert.alert('Success', 'PDF has been downloaded successfully!');
} catch (error) {
Alert.alert('Error', 'Failed to generate PDF: ' + error.message);
}
};
const openPDF = async () => {
if (!pdfUri) {
Alert.alert('No PDF', 'Please generate the PDF first.');
return;
}
try {
const supported = await FileViewer.viewFile(pdfUri);
if (!supported) {
Alert.alert('Error', 'Cannot open the PDF file.');
}
} catch (error) {
Alert.alert('Error', 'Failed to open PDF: ' + error.message);
}
};
return (
<View style={styles.container}>
<View style={styles.section}>
<Button title="Download PDF" onPress={generatePDF} />
</View>
{pdfUri && (
<TouchableOpacity style={styles.iconContainer} onPress={openPDF}>
<Ionicons name="document-text" size={40} color="#4CAF50" />
<Text style={styles.iconText}>Open PDF</Text>
</TouchableOpacity>
)}
</View>
);
};
// --- Legal Text (Should be imported or passed as a prop) ---
const legalText = `YOUR LEGAL TEXT GOES HERE...
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vel turpis at quam aliquet lobortis. Integer sit amet ligula vitae justo commodo fermentum. Donec vitae massa a augue blandit porttitor. Proin id purus nec justo mollis finibus sit amet at justo. Mauris ac sem vitae nisl interdum interdum.`;
const styles = StyleSheet.create({
container: {
padding: 20,
},
section: {
marginBottom: 30,
backgroundColor: '#ffffff',
padding: 15,
borderRadius: 10,
elevation: 2, // For Android
shadowColor: '#000', // For iOS
shadowOffset: { width: 0, height: 2 }, // For iOS
shadowOpacity: 0.25, // For iOS
shadowRadius: 3.84, // For iOS
alignItems: 'center',
},
iconContainer: {
flexDirection: 'row',
alignItems: 'center',
marginTop: 10,
padding: 10,
backgroundColor: '#e0f7fa',
borderRadius: 10,
},
iconText: {
marginLeft: 10,
fontSize: 16,
color: '#00796b',
},
});
export default PDFGenerator;
3. Explanation of Changes
State Management:
Added a pdfUri state to keep track of the downloaded PDF's URI.
Generating and Saving the PDF:
After generating the PDF using Print.printToFileAsync, the PDF is moved to the app's document directory using FileSystem.moveAsync.
The new URI (pdfPath) is stored in the pdfUri state.
Displaying the Open PDF Icon:
Once the PDF is downloaded (pdfUri is set), an icon with a label "Open PDF" appears.
The icon is created using Ionicons from @expo/vector-icons. If you haven't installed this package, you can install it using:
bash
expo install @expo/vector-icons
You can customize the icon and styling as per your preference.
Opening the PDF:
The openPDF function uses expo-file-viewer to open the PDF with the device's default PDF viewer.
It checks if pdfUri is available before attempting to open the PDF.
4. Additional Considerations
Permissions:
On Android, ensure you have the necessary permissions to read and write to the device's storage. Expo handles most of these permissions automatically, but if you encounter issues, you may need to adjust your app.json or request permissions explicitly.
Handling Existing Files:
This implementation overwrites the PDF each time you generate a new one. If you want to keep multiple versions, consider naming the files uniquely (e.g., appending a timestamp).
User Feedback:
Alerts are used to notify the user about the success or failure of actions. You can enhance the user experience by adding loading indicators or more detailed messages.
Error Handling:
Ensure you handle all possible errors, especially related to file operations and viewer support on different devices.
5. Final Thoughts
By following the above steps, your PDFGenerator component will allow users to download the generated PDF locally and access it through an intuitive icon within the app. This approach ensures that the PDF is stored securely within the app's directory and provides a seamless user experience for accessing the downloaded document.