Guides
图片提取
ComPDF React Native SDK 提供图片提取接口,用于从当前 PDF 文档中导出嵌入图片。你可以提取整个文档中的图片,也可以只提取指定页面中的图片。
API 概览
图片提取接口位于 CPDFDocument:
ts
extractImages(
directoryPath: string,
pages?: Array<number> | null
): Promise<CPDFExtractImageResult>;参数说明:
| 参数 | 说明 |
|---|---|
directoryPath | 图片输出目录。SDK 会直接将图片写入该目录;如果目录不存在,会尝试创建目录 |
pages | 可选页面索引列表,从 0 开始。传入 null、空数组或不传时,表示提取全部页面图片 |
返回值为 CPDFExtractImageResult:
ts
type CPDFExtractImageResult = {
success: boolean;
count: number;
directoryPath: string;
imagePaths: string[];
};字段说明:
| 字段 | 说明 |
|---|---|
success | 原生图片提取调用是否成功完成 |
count | 提取完成后在 directoryPath 中扫描到的图片文件数量 |
directoryPath | 图片输出目录,即调用时传入的目录路径 |
imagePaths | 提取完成后在 directoryPath 中扫描到的图片文件完整路径列表 |
输出目录语义
directoryPath 表示调用方指定的实际输出目录。SDK 不会在该目录下自动创建额外子目录,也不会清空目录。
如果你希望 imagePaths 只包含本次提取生成的图片,请在调用前传入一个新的空目录,或由你的业务代码自行清理目录。
tsx
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;
}如果复用已有目录,返回的 imagePaths 可能包含目录中已存在的图片文件。
提取全部页面图片
不传 pages 时,SDK 会尝试提取文档中全部页面的图片。
tsx
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} />
</>
);
}提取指定页面图片
通过 pages 参数可以只提取指定页面的图片。页面索引从 0 开始。
tsx
const result = await pdfReaderRef.current?._pdfDocument.extractImages(
outputDir,
[0, 2]
);
console.log("Extracted image count:", result?.count ?? 0);上面示例会提取第 1 页和第 3 页中的图片。
如果传入无效页面索引,例如负数或大于等于页数的索引,接口会返回平台错误。
在 CPDFReaderView 中使用
在阅读器页面中,可以通过 CPDFReaderView 实例的 _pdfDocument 调用相同接口。
tsx
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);
}这个方式适用于在自定义阅读器工具栏、菜单或页面操作中提供图片提取能力。
展示提取后的图片
imagePaths 返回的是本地图片文件路径。React Native 的 Image 组件通常需要 file:// URI,可以在展示前做一次转换。
tsx
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>
);
}完整示例
下面示例演示如何在已加载的阅读器中创建独立输出目录、提取图片,并返回提取结果。
tsx
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;
}注意事项
directoryPath必须是本地可写目录路径,不是单个图片文件路径。- SDK 会直接使用
directoryPath,不会自动创建额外子目录,也不会清空目录。 - 如果需要只获取本次提取结果,请传入新的空目录。
pages使用从 0 开始的页面索引。- 图片提取接口依赖已挂载的
CPDFReaderView,请在文档加载完成后调用。 - PDF 中没有嵌入图片时,可能返回
success === true、count === 0、imagePaths.length === 0。 - 图片格式由 PDF 内部图片数据和原生 SDK 决定,可能是 JPEG、PNG 或其他支持格式。
- Android 与 iOS 的原生返回值不同,React Native API 使用
CPDFExtractImageResult统一结果结构。