PDF 生成模板编辑器
开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。
ComPDF React Native SDK 自 3.2.0 起支持为指定页面设置纯色或图片背景,并读取或清除背景配置。背景位于页面内容之后,可用于统一文档外观。
以下示例中的阅读器已完成文档加载,pages 为从 0 开始的页面索引。
import { CPDFReaderView } from '@compdfkit_pdf_sdk/react_native';
async function setColorBackground(reader: CPDFReaderView) {
const success = await reader._pdfDocument.updateBackground({
pages: [0], type: 'color', color: '#FFF3E0', opacity: 0.5,
allowView: true, allowPrint: true,
});
if (!success) throw new Error('更新背景失败');
if (!await reader.save()) throw new Error('保存文档失败');
}import { CPDFReaderView } from '@compdfkit_pdf_sdk/react_native';
async function setImageBackground(reader: CPDFReaderView, imagePath: string) {
const success = await reader._pdfDocument.updateBackground({
pages: [0], type: 'image', imagePath,
opacity: 0.4, scale: 0.8, rotation: 45,
horizontalAlignment: 'center', verticalAlignment: 'center',
horizontalOffset: 0, verticalOffset: 0,
allowView: true, allowPrint: true,
});
if (!success) throw new Error('更新背景失败');
if (!await reader.save()) throw new Error('保存文档失败');
}imagePath 使用可访问的本地图片路径。opacity 范围为 0–1,scale 必须大于 0,rotation 为 0–360 度的顺时针旋转角度。水平对齐支持 left、center、right,垂直对齐支持 top、center、bottom;偏移量以 PDF 点计。
import { CPDFReaderView } from '@compdfkit_pdf_sdk/react_native';
async function clearBackground(reader: CPDFReaderView) {
const document = reader._pdfDocument;
const current = await document.getBackground();
if (current === null) return;
if (!await document.clearBackground()) throw new Error('清除背景失败');
if (!await reader.save()) throw new Error('保存文档失败');
}getBackground() 在没有背景时返回 null。从文档读取的图片背景不能恢复原始 imagePath,页面范围也可能为空;再次更新时需明确指定目标页面和本地图片路径,不应直接回写读取结果。更新和清除操作后保存文档,并处理 false 或 Promise 拒绝。