To update your PDFGenerator.js component to use the legal text from LegalText.js, you'll need to restructure how the legal text is managed. Instead of having the legal text hardcoded within PDFGenerator.js, you can centralize it by exporting the text from LegalText.js and then importing it into PDFGenerator.js. This approach ensures consistency and makes maintenance easier, especially if the legal text needs to be updated in the future.
Here's a step-by-step guide to achieve this:
- Modify
LegalText.js to Export the Legal Text as a String
- Update
PDFGenerator.js to Import and Use the Legal Text
1. Modify LegalText.js to Export the Legal Text as a String
First, you'll need to adjust your LegalText.js component to export the legal text as a separate string. This allows other components, like PDFGenerator.js, to access the same legal text without duplication.
Updated LegalText.js
// components/LegalText.js
import React from 'react';
import { ScrollView, Text, StyleSheet } from 'react-native';
// Export the legal text as a constant
export const LEGAL_TEXT = `
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.
`;
// Define the LegalText component that displays the legal text
const LegalText = () => {
return (
<ScrollView style={styles.container}>
<Text style={styles.text}>
{LEGAL_TEXT}
</Text>
</ScrollView>
);
};
const styles = StyleSheet.create({
container: {
padding: 20,
},
text: {
fontSize: 16,
lineHeight: 22, // Added for better readability
},
});
export default LegalText;
Explanation
-
Exporting LEGAL_TEXT: By exporting LEGAL_TEXT, other components can import and use the same legal text, ensuring consistency across your application.
-
Using LEGAL_TEXT in the Component: The LegalText component now uses the exported LEGAL_TEXT to display the content within a ScrollView.
2. Update PDFGenerator.js to Import and Use the Legal Text
Now that LEGAL_TEXT is exported from LegalText.js, you can import it into PDFGenerator.js and use it when generating the PDF.
Updated PDFGenerator.js
// components/PDFGenerator.js
import React, { useContext, useState } from 'react';
import {
StyleSheet,
View,
Button,
Alert,
TouchableOpacity,
Text,
ActivityIndicator,
Platform,
} from 'react-native';
import * as Print from 'expo-print';
import * as FileSystem from 'expo-file-system';
import { StorageAccessFramework } from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import { MediaContext } from '../context/MediaContext';
import { Ionicons } from '@expo/vector-icons';
// Import the legal text from LegalText.js
import { LEGAL_TEXT } from './LegalText';
const PDFGenerator = () => {
const { media } = useContext(MediaContext);
const [pdfUri, setPdfUri] = useState(null); // State to store PDF URI
const [isGenerating, setIsGenerating] = useState(false); // State for Activity Indicator
const generatePDF = async () => {
setIsGenerating(true); // Start Activity Indicator
// 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>${LEGAL_TEXT}</p>
${mediaHtml}
</body>
</html>
`;
try {
// Generate PDF from HTML
const { uri } = await Print.printToFileAsync({ html: htmlContent });
console.log('PDF generated at:', uri);
let destinationUri = '';
if (Platform.OS === 'android') {
// Use StorageAccessFramework to request directory permissions
const permissions = await StorageAccessFramework.requestDirectoryPermissionsAsync();
if (!permissions.granted) {
Alert.alert(
'Permission Required',
'Storage permission is needed to save the PDF.'
);
setIsGenerating(false);
return;
}
// Define the filename
const filename = `ConsentDocument_${Date.now()}.pdf`;
try {
// Create a new file in the selected directory
const fileUri = await StorageAccessFramework.createFileAsync(
permissions.directoryUri,
filename,
'application/pdf'
);
console.log('File created at:', fileUri);
// Read the generated PDF file
const pdfData = await FileSystem.readAsStringAsync(uri, {
encoding: FileSystem.EncodingType.Base64,
});
// Write the PDF data to the new file
await FileSystem.writeAsStringAsync(fileUri, pdfData, {
encoding: FileSystem.EncodingType.Base64,
});
destinationUri = fileUri;
setPdfUri(destinationUri);
Alert.alert(
'Success',
'PDF has been saved successfully!'
);
} catch (e) {
console.error('Error saving PDF:', e);
Alert.alert('Error', 'Failed to save PDF: ' + e.message);
}
} else {
// For iOS and other platforms, use Sharing
const filename = `ConsentDocument_${Date.now()}.pdf`;
const destinationPath = `${FileSystem.documentDirectory}${filename}`;
console.log('Destination Path:', destinationPath);
// Move the PDF to the desired location
await FileSystem.moveAsync({
from: uri,
to: destinationPath,
});
destinationUri = destinationPath;
setPdfUri(destinationUri);
if (await Sharing.isAvailableAsync()) {
await Sharing.shareAsync(destinationUri);
} else {
Alert.alert(
'Success',
'PDF has been saved to your Documents directory.'
);
}
}
} catch (error) {
Alert.alert('Error', 'Failed to generate PDF: ' + error.message);
console.error('Error generating PDF:', error);
}
setIsGenerating(false); // Stop Activity Indicator
};
const openDownloadLocation = async () => {
if (!pdfUri) {
Alert.alert('No PDF', 'Please generate the PDF first.');
return;
}
try {
if (Platform.OS === 'android') {
// Inform the user to check the selected directory
Alert.alert(
'Download Complete',
'The PDF has been saved successfully. You can access it using any file manager app.'
);
} else if (Platform.OS === 'ios') {
// Use the sharing sheet to open the PDF
if (await Sharing.isAvailableAsync()) {
await Sharing.shareAsync(pdfUri);
} else {
Alert.alert(
'Sharing Not Available',
'Cannot share the PDF on this device.'
);
}
} else {
Alert.alert('Unsupported Platform', 'This feature is not supported on your device.');
}
} catch (error) {
Alert.alert('Error', 'Cannot open the PDF. Please try again.');
console.error('Error opening PDF:', error);
}
};
return (
<View style={styles.container}>
<View style={styles.section}>
<Button title="Download PDF" onPress={generatePDF} disabled={isGenerating} />
</View>
{isGenerating && <ActivityIndicator size="large" color="#0000ff" />}
{pdfUri && (
<TouchableOpacity style={styles.iconContainer} onPress={openDownloadLocation}>
<Ionicons name="folder-open" size={40} color="#4CAF50" />
<Text style={styles.iconText}>Open Download Location</Text>
</TouchableOpacity>
)}
</View>
);
};
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;
Explanation
-
Importing LEGAL_TEXT:
import { LEGAL_TEXT } from './LegalText';
This line imports the LEGAL_TEXT string from LegalText.js. Ensure that the path './LegalText' correctly points to the location of your LegalText.js file relative to PDFGenerator.js.
-
Using LEGAL_TEXT in HTML Content:
<p>${LEGAL_TEXT}</p>
This line injects the legal text into the HTML content that will be converted into a PDF. By using template literals, the legal text is seamlessly integrated into the HTML structure.
-
Removing the Local legalText Constant:
The original legalText constant within PDFGenerator.js has been removed to avoid redundancy and ensure that the component uses the centralized legal text from LegalText.js.
-
No Changes Needed Elsewhere:
The rest of the component remains unchanged, continuing to handle PDF generation, saving, and sharing as before.
Additional Recommendations
-
Centralizing Legal Text:
If your application uses the legal text in multiple places, consider creating a separate module (e.g., legalText.js) that exports the text. This approach enhances reusability and maintainability.
// components/legalText.js
export const LEGAL_TEXT = `
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.
`;
Then, both LegalText.js and PDFGenerator.js can import LEGAL_TEXT from this module.
-
Handling Large Texts:
For extensive legal documents, consider fetching the text from an external source or storing it in a more manageable format (e.g., Markdown or HTML) to simplify formatting and updates.
-
Localization:
If your application needs to support multiple languages, structure your legal text to accommodate localization libraries like i18n-js or react-intl.
-
Error Handling:
Ensure that adequate error handling is in place, especially when dealing with file system operations and user permissions. This ensures a smoother user experience.
-
User Experience:
- Loading Indicators: You've already included an
ActivityIndicator to inform users when the PDF is being generated. Consider adding more user feedback mechanisms if the process might take longer.
- Confirmation Dialogs: After successfully generating and saving the PDF, providing users with options to view, share, or perform other actions can enhance usability.
By following these steps, your PDFGenerator.js component will effectively utilize the legal text from LegalText.js, promoting code reuse and maintainability across your application.