Add Image Watermark
ComPDF supports two ways to add image watermarks:
Programmatic Approach
Use createImageWatermark with document.createWatermark to create an image watermark. This method is suitable for adding an image watermark from a local image path without opening the watermark dialog.
import {
CPDFReaderView,
createImageWatermark,
} from "@compdfkit_pdf_sdk/react_native";
const pdfReaderRef = useRef<CPDFReaderView>(null);
const addImageWatermark = async (imagePath: string) => {
const result = await pdfReaderRef.current?._pdfDocument.createWatermark(
createImageWatermark({
imagePath,
pages: [0, 1, 2, 3],
scale: 0.5,
rotation: 45,
opacity: 1,
horizontalAlignment: "center",
verticalAlignment: "center",
})
);
console.log("Add image watermark result:", result);
};For programmatic image watermark creation, imagePath must be a local image file path accessible by the app.
UI Popup Approach
ComPDF React Native SDK also supports adding image watermarks through a UI dialog. You can configure default watermark styles, such as image source, opacity, and rotation angle, in CPDFConfiguration.
// Set default image watermark style in configuration
ComPDFKit.getDefaultConfig({
global: {
watermark: {
types: ['text', 'image'],
image: 'ic_logo',
opacity: 120,
rotation: -45
}
}
});
// Open the add watermark dialog via API
await pdfReaderRef.current?.showAddWatermarkView({
types: ['text', 'image'],
image: 'ic_logo',
opacity: 120,
rotation: -45,
opacity: 255,
});To customize the default image, you need to handle it differently on Android and iOS.
Android
- Add the image file to your resource directory:
android/app/src/main/res/drawable/ic_logo.png- Reference the image by its filename without extension in your code:
image: 'ic_logo'iOS
- Import the image file into your project through Xcode.
<img src="./screenshots/guides_rn_3.7.4_1.png" alt="guides_rn_3.7.4_1" style="zoom:50%;" />- Reference the image by its filename without extension in your code:
image: 'ic_logo'Alternative Approach
You can also copy the image to the device’s local storage and pass its file path directly:
// Assume imagePath is the local file path of the image
const imagePath = 'data/user/0/com.compdfkit.reactnative.example/cache/temp/ic_logo.png';
await pdfReaderRef.current?.showAddWatermarkView({
types: ['text', 'image'],
image: imagePath,
opacity: 120,
rotation: -45,
opacity: 255,
});