Converting PDF to Base64 in React Native with Document Picker
Problem: You're working on a React Native app where you need to upload a PDF file to your backend. However, you need to convert the PDF into Base64 encoding before sending it. This can be a tricky task, as React Native doesn't have built-in functionality for direct PDF manipulation.
Solution: This article will guide you through the process of converting a PDF file to Base64 using the popular react-native-document-picker
library. We'll break down the steps and provide a clear code example to help you get started.
Understanding the Process
- Document Picker: The
react-native-document-picker
library simplifies selecting a PDF file from the user's device. - File Reading: Once selected, the PDF needs to be read into memory as raw data.
- Base64 Encoding: We'll use JavaScript's
atob()
function to convert the raw data into Base64 encoded string.
Code Implementation
import React, { useState } from 'react';
import { View, Text, Button, Alert } from 'react-native';
import DocumentPicker from 'react-native-document-picker';
const App = () => {
const [base64Data, setBase64Data] = useState(null);
const handlePickPDF = async () => {
try {
const result = await DocumentPicker.pick({
type: [DocumentPicker.types.pdf],
});
// Read the file contents
const file = await fetch(result.uri);
const fileData = await file.blob();
// Convert to Base64
const reader = new FileReader();
reader.readAsDataURL(fileData);
reader.onloadend = () => {
setBase64Data(reader.result);
};
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker
} else {
Alert.alert('Error', err.message);
}
}
};
return (
<View>
<Button title="Pick PDF" onPress={handlePickPDF} />
{base64Data && (
<Text>Base64 Data: {base64Data}</Text>
)}
</View>
);
};
export default App;
Explanation
- Import Libraries: Import the necessary components from
react-native-document-picker
and React. handlePickPDF()
Function: This function handles the file selection process:- Uses
DocumentPicker.pick()
to allow users to select a PDF file. - Uses
fetch()
to read the file contents. - Creates a
FileReader
object and callsreadAsDataURL()
to convert the file to Base64. - Sets the
base64Data
state with the result of the conversion.
- Uses
- Displaying the Base64 Data: The
base64Data
is rendered within the UI if available.
Additional Notes
- Error Handling: The code includes error handling to catch cancellation and other potential errors.
- Backend Integration: Once you have the Base64 encoded data, you can send it to your backend server using an API call.
- Library Installation: Install
react-native-document-picker
using:
and follow the library's installation instructions.npm install react-native-document-picker
Conclusion
Converting a PDF to Base64 in React Native can be achieved with the help of react-native-document-picker
. This simple code example provides a basic implementation, but you can extend it to suit your specific application needs. Remember to always handle potential errors and ensure your backend API can process the Base64 encoded data.
Resources:
react-native-document-picker
Documentation: https://www.npmjs.com/package/react-native-document-picker- MDN:
FileReader
Object: https://developer.mozilla.org/en-US/docs/Web/API/FileReader - MDN:
atob()
Function: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/atob