Skip to content
DemoAPI ReferenceFAQ

PDF Generation Template Editor

Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.

View on GitHub
React Native Guides Background

Document Background ​

Starting with 3.2.0, ComPDF React Native SDK supports setting solid-color or image backgrounds for selected pages, as well as reading and clearing the configuration. Backgrounds appear behind page content and can provide a consistent document appearance.

Set a Color Background ​

The reader in these examples has finished loading its document. pages contains zero-based page indexes.

ts
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('Failed to update the background');
  if (!await reader.save()) throw new Error('Failed to save the document');
}

Set an Image Background ​

ts
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('Failed to update the background');
  if (!await reader.save()) throw new Error('Failed to save the document');
}

imagePath must be an accessible local image path. opacity ranges from 0 to 1, scale must be greater than 0, and rotation specifies clockwise rotation from 0 to 360 degrees. Horizontal alignment accepts left, center, or right; vertical alignment accepts top, center, or bottom. Offsets use PDF points.

Read and Clear ​

ts
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('Failed to clear the background');
  if (!await reader.save()) throw new Error('Failed to save the document');
}

getBackground() returns null when no background exists. Reading an image background cannot recover its original imagePath, and the returned page range may be empty. Specify the target pages and local image path when updating it again instead of writing the returned object back unchanged. Save after updating or clearing, and handle false results and rejected Promises.