PDF 生成模板编辑器
开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。
ComPDF React Native SDK 提供图片提取接口,用于从当前 PDF 文档中导出嵌入图片。你可以提取整个文档中的图片,也可以只提取指定页面中的图片。
图片提取接口位于 CPDFDocument:
extractImages(
directoryPath: string,
pages?: Array<number> | null
): Promise<CPDFExtractImageResult>;参数说明:
| 参数 | 说明 |
|---|---|
directoryPath | 图片输出目录。SDK 会直接将图片写入该目录;如果目录不存在,会尝试创建目录 |
pages | 可选页面索引列表,从 0 开始。传入 null、空数组或不传时,表示提取全部页面图片 |
返回值为 CPDFExtractImageResult:
type CPDFExtractImageResult = {
success: boolean;
count: number;
directoryPath: string;
imagePaths: string[];
};字段说明:
| 字段 | 说明 |
|---|---|
success | 原生图片提取调用是否成功完成 |
count | 提取完成后在 directoryPath 中扫描到的图片文件数量 |
directoryPath | 图片输出目录,即调用时传入的目录路径 |
imagePaths | 提取完成后在 directoryPath 中扫描到的图片文件完整路径列表 |
directoryPath 表示调用方指定的实际输出目录。SDK 不会在该目录下自动创建额外子目录,也不会清空目录。
如果你希望 imagePaths 只包含本次提取生成的图片,请在调用前传入一个新的空目录,或由你的业务代码自行清理目录。
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 会尝试提取文档中全部页面的图片。
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 开始。
const result = await pdfReaderRef.current?._pdfDocument.extractImages(
outputDir,
[0, 2]
);
console.log("Extracted image count:", result?.count ?? 0);上面示例会提取第 1 页和第 3 页中的图片。
如果传入无效页面索引,例如负数或大于等于页数的索引,接口会返回平台错误。
在阅读器页面中,可以通过 CPDFReaderView 实例的 _pdfDocument 调用相同接口。
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,可以在展示前做一次转换。
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>
);
}下面示例演示如何在已加载的阅读器中创建独立输出目录、提取图片,并返回提取结果。
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 必须是本地可写目录路径,不是单个图片文件路径。directoryPath,不会自动创建额外子目录,也不会清空目录。pages 使用从 0 开始的页面索引。CPDFReaderView,请在文档加载完成后调用。success === true、count === 0、imagePaths.length === 0。CPDFExtractImageResult 统一结果结构。