Skip to content
DemoFAQ

PDF Generation Template Editor

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

View on GitHub
Flutter Guides Background

Document Background ​

Starting with 3.2.0, ComPDF Flutter SDK supports color and image backgrounds. A background is part of the PDF document and is configured separately from the reader's display theme.

In these examples, document is an opened CPDFDocument.

dart
import 'package:compdfkit_flutter/document/cpdf_background.dart';
import 'package:flutter/material.dart';

Set a Color Background ​

dart
final pageCount = await document.getPageCount();
final pages = List<int>.generate(pageCount, (index) => index);
final success = await document.updateBackground(
  CPDFBackground.color(
    pages: pages,
    color: Colors.amber,
    opacity: 0.2,
    allowView: true,
    allowPrint: true,
  ),
);
if (success) {
  await document.save();
}

Set an Image Background ​

Use a readable local image path for imagePath. In this example, pages contains the target page indexes.

dart
final success = await document.updateBackground(
  CPDFBackground.image(
    pages: pages,
    imagePath: '/path/to/background.png',
    opacity: 0.35,
    scale: 1.0,
    rotation: 0,
  ),
);
if (success) {
  await document.save();
}
ParameterDescription
pagesA nonempty list of zero-based page indexes
opacityOpacity from 0 to 1
scaleScale factor, greater than 0
rotationRotation angle from 0 to 360 degrees
horizontalAlignment, verticalAlignmentHorizontal and vertical alignment; centered by default
horizontalOffset, verticalOffsetHorizontal and vertical offsets
allowView, allowPrintWhether to display the background when viewing or printing; both default to true

Read and Update a Background ​

dart
final background = await document.getBackground();
if (background != null) {
  debugPrint('Type: ${background.type.name}');
  debugPrint('Opacity: ${background.opacity}');
}

The result is null when there is no background. The source image path cannot be recovered from an existing PDF image background, so the returned imagePath is null. Provide the local image path again when updating an image background. The returned pages may be empty; explicitly specify the target pages when updating.

To change a background, construct a new CPDFBackground and call updateBackground() again.

Clear the Background ​

dart
final cleared = await document.clearBackground();
if (cleared) {
  await document.save();
}

Call save() or saveAs() to persist all changes to a file.