@friedrich.fschr/epub-parser
Version:
An epub parser which can extract chapter contents from an epub file
209 lines (155 loc) • 5.95 kB
Markdown
# Using the EPUB Parser in React Native
This guide explains how to use the `@lingo-reader/epub-parser` package in a React Native application.
## Installation
First, install the package and its dependencies:
```bash
npm install @lingo-reader/epub-parser jszip
# or with yarn
yarn add @lingo-reader/epub-parser jszip
```
## Basic Usage
### 1. Loading an EPUB file
To use the EPUB parser in React Native, you first need to get the file data in a format that the parser can use. Here are a few ways to do this:
#### From the device's file system using a library like react-native-fs:
```typescript
import RNFS from "react-native-fs";
import { initEpubFile, createFileFromData } from "@lingo-reader/epub-parser";
async function loadEpubFromFilesystem(filePath: string) {
// Read the file as base64
const base64 = await RNFS.readFile(filePath, "base64");
// Convert base64 to Uint8Array
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
// Create a File-like object
const fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
const file = createFileFromData(fileName, bytes);
// Initialize the EPUB parser
return await initEpubFile(file);
}
```
#### From app assets (bundled with your app) using Expo:
```typescript
import { Asset } from "expo-asset";
import * as FileSystem from "expo-file-system";
import { initEpubFile, createFileFromData } from "@lingo-reader/epub-parser";
async function loadEpubFromAssets() {
// Load the asset
const asset = Asset.fromModule(require("../assets/book.epub"));
await asset.downloadAsync();
// Read the file from the filesystem
const fileUri = asset.localUri || "";
const base64 = await FileSystem.readAsStringAsync(fileUri, {
encoding: "base64",
});
// Convert base64 to Uint8Array
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
// Create a File-like object
const file = createFileFromData("book.epub", bytes);
// Initialize the EPUB parser
return await initEpubFile(file);
}
```
### 2. Using the EPUB Parser
Once you have loaded the EPUB file, you can use the parser API just like you would in a web or Node.js environment:
```typescript
// Get book metadata
const metadata = epub.getMetadata();
console.log(`Title: ${metadata.title}`);
console.log(`Author: ${metadata.creator?.[0]?.text || "Unknown"}`);
// Get the chapter list (spine)
const spine = epub.getSpine();
// Load a specific chapter
const chapterId = spine[0].id;
const chapter = await epub.loadChapter(chapterId);
// The chapter object contains:
// - html: The chapter content as an HTML string
// - css: An array of CSS styles for the chapter
```
### 3. Handling Resources (Images, etc.)
In React Native, resources like images are handled differently than in a web browser. The EPUB parser uses a custom resource scheme (`resource://id`) for referencing resources:
```typescript
import { getResourceData } from "@lingo-reader/epub-parser";
import { Image } from "react-native";
function EpubImage({ src }) {
// Only process resource:// URLs
if (!src.startsWith("resource://")) {
return null;
}
// Get the resource data
const resourceData = getResourceData(src);
if (!resourceData) {
return null;
}
// Convert Uint8Array to base64
let binary = "";
const bytes = resourceData.data;
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
const base64 = btoa(binary);
// Create a data URI for the Image component
const uri = `data:${resourceData.type};base64,${base64}`;
return (
<Image
source={{ uri }}
style={{ width: "100%", height: 200 }}
resizeMode="contain"
/>
);
}
```
### 4. Rendering EPUB Content
For rendering HTML content in React Native, you can use libraries like `react-native-render-html`:
```typescript
import HTML from "react-native-render-html";
function EpubChapterRenderer({ chapter }) {
const renderers = {
img: (htmlAttribs, children, convertedCSSStyles, passProps) => {
return <EpubImage src={htmlAttribs.src} />;
},
};
return (
<HTML
source={{ html: chapter.html }}
renderers={renderers}
contentWidth={/* your screen width */}
/>
);
}
```
### 5. Cleaning Up
When you're done with an EPUB file, make sure to clean up resources:
```typescript
// Clean up when the component unmounts
useEffect(() => {
return () => {
if (epub) {
epub.destroy();
}
};
}, [epub]);
```
## Complete Example
See the `examples/ReactNativeExample.tsx` file for a complete example of how to use the EPUB parser in a React Native application.
## Troubleshooting
### File Loading Issues
If you're having trouble loading EPUB files:
1. Make sure you have the correct permissions to access files on the device
2. Check that the file path is correct
3. Verify that the file is a valid EPUB (not corrupted or protected by DRM)
### Rendering Issues
If the content doesn't render correctly:
1. Try using different HTML rendering libraries like `react-native-webview` if `react-native-render-html` doesn't work well for your content
2. For complex EPUBs with advanced CSS, you might need to implement additional CSS handling
3. Remember that some EPUB features might not be fully supported in React Native
## Performance Tips
1. Cache loaded chapters to avoid re-parsing them
2. Consider lazy-loading chapters as needed rather than loading the entire book at once
3. For large books, implement pagination or virtualization to only render visible content