Extract Images
ComPDF React Native SDK provides an image extraction API for exporting embedded images from the current PDF document. You can extract images from the whole document or from specific pages.
API Overview
The image extraction API is available on CPDFDocument:
extractImages(
directoryPath: string,
pages?: Array<number> | null
): Promise<CPDFExtractImageResult>;Parameter description:
| Parameter | Description |
|---|---|
directoryPath | Output directory for extracted images. The SDK writes images directly to this directory. If the directory does not exist, the SDK attempts to create it |
pages | Optional zero-based page indexes. null, an empty array, or an omitted value means extracting images from all pages |
The return value is CPDFExtractImageResult:
type CPDFExtractImageResult = {
success: boolean;
count: number;
directoryPath: string;
imagePaths: string[];
};Field description:
| Field | Description |
|---|---|
success | Whether the native image extraction call completed successfully |
count | Number of image files found in directoryPath after extraction |
directoryPath | Output directory for images, the same directory path passed to the API |
imagePaths | Full paths of image files found in directoryPath after extraction |
Output Directory Semantics
directoryPath is the actual output directory specified by the caller. The SDK does not automatically create an extra subdirectory inside it and does not clear the directory.
If you want imagePaths to contain only images generated by the current extraction call, pass a new empty directory or clean the directory in your own business logic before calling the API.
import RNFS from "react-native-fs";
async function createImageOutputDirectory() {
const tempRoot =
RNFS.TemporaryDirectoryPath ?? RNFS.CachesDirectoryPath ?? RNFS.DocumentDirectoryPath;
const outputDir = `${tempRoot}/extracted_images_${Date.now()}`;
if (await RNFS.exists(outputDir)) {
await RNFS.unlink(outputDir);
}
await RNFS.mkdir(outputDir);
return outputDir;
}If you reuse an existing directory, the returned imagePaths may include image files that were already in that directory.
Extract Images From All Pages
When pages is not provided, the SDK attempts to extract images from all pages in the document.
import { useRef } from "react";
import { Button } from "react-native";
import RNFS from "react-native-fs";
import { CPDFReaderView } from "@compdfkit_pdf_sdk/react_native";
export default function ExtractAllImagesExample() {
const pdfReaderRef = useRef<CPDFReaderView>(null);
const extractAllImages = async () => {
const document = pdfReaderRef.current?._pdfDocument;
if (!document) {
return;
}
const tempRoot =
RNFS.TemporaryDirectoryPath ?? RNFS.CachesDirectoryPath ?? RNFS.DocumentDirectoryPath;
const outputDir = `${tempRoot}/extracted_images_${Date.now()}`;
await RNFS.mkdir(outputDir);
const result = await document.extractImages(outputDir);
if (result.success) {
console.log("Image count:", result.count);
result.imagePaths.forEach((imagePath) => {
console.log("Image path:", imagePath);
});
} else {
console.log("Extract images failed.");
}
};
return (
<>
<CPDFReaderView
ref={pdfReaderRef}
document="file:///path/to/sample.pdf"
style={{ flex: 1 }}
/>
<Button title="Extract Images" onPress={extractAllImages} />
</>
);
}Extract Images From Specific Pages
Use the pages parameter to extract images from specific pages only. Page indexes are zero-based.
const result = await pdfReaderRef.current?._pdfDocument.extractImages(
outputDir,
[0, 2]
);
console.log("Extracted image count:", result?.count ?? 0);The example above extracts images from page 1 and page 3.
If an invalid page index is passed, such as a negative index or an index greater than or equal to the page count, the API returns a platform error.
Use With CPDFReaderView
In a reader page, call the same API through the _pdfDocument property of a CPDFReaderView instance.
async function extractImagesFromReader(reader: CPDFReaderView) {
const tempRoot =
RNFS.TemporaryDirectoryPath ?? RNFS.CachesDirectoryPath ?? RNFS.DocumentDirectoryPath;
const outputDir = `${tempRoot}/reader_extracted_images_${Date.now()}`;
await RNFS.mkdir(outputDir);
const result = await reader._pdfDocument.extractImages(outputDir);
console.log("Output directory:", result.directoryPath);
console.log("Image count:", result.count);
}This is useful when you want to provide image extraction from a custom reader toolbar, menu, or page action.
Display Extracted Images
imagePaths contains local image file paths. React Native's Image component usually needs a file:// URI, so convert the path before rendering it.
import { Image, ScrollView, View } from "react-native";
function toFileUri(path: string) {
return path.startsWith("file://") ? path : `file://${path}`;
}
function ExtractedImageGrid({ imagePaths }: { imagePaths: string[] }) {
return (
<ScrollView contentContainerStyle={{ flexDirection: "row", flexWrap: "wrap", gap: 10 }}>
{imagePaths.map((imagePath) => (
<View
key={imagePath}
style={{ width: 148, height: 148, padding: 6, borderWidth: 1 }}
>
<Image
source={{ uri: toFileUri(imagePath) }}
style={{ width: "100%", height: "100%" }}
resizeMode="contain"
/>
</View>
))}
</ScrollView>
);
}Complete Example
The following example creates a new empty output directory from a loaded reader, extracts images, and returns the result.
import RNFS from "react-native-fs";
import { CPDFReaderView } from "@compdfkit_pdf_sdk/react_native";
export async function extractPdfImages(reader: CPDFReaderView) {
const tempRoot =
RNFS.TemporaryDirectoryPath ?? RNFS.CachesDirectoryPath ?? RNFS.DocumentDirectoryPath;
const outputDir = `${tempRoot}/extract_images_${Date.now()}`;
await RNFS.mkdir(outputDir);
const result = await reader._pdfDocument.extractImages(outputDir);
if (!result.success) {
throw new Error("Extract images failed.");
}
console.log("Output directory:", result.directoryPath);
console.log("Image count:", result.count);
return result.imagePaths;
}Notes
directoryPathmust be a writable local directory path, not a single image file path.- The SDK uses
directoryPathdirectly. It does not automatically create an extra subdirectory and does not clear the directory. - If you need only the images generated by the current extraction call, pass a new empty directory.
pagesuses zero-based page indexes.- The image extraction API requires a mounted
CPDFReaderView. Call it after the document has loaded. - If the PDF contains no embedded images, the result may be
success === true,count === 0, andimagePaths.length === 0. - The image format is determined by the PDF embedded image data and the native SDK. Extracted files may be JPEG, PNG, or another supported format.
- Android and iOS have different native return values. The React Native API uses
CPDFExtractImageResultto provide a unified result structure.