PDF Generation Template Editor
Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.
Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.
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.
import 'package:compdfkit_flutter/document/cpdf_background.dart';
import 'package:flutter/material.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();
}Use a readable local image path for imagePath. In this example, pages contains the target page indexes.
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();
}| Parameter | Description |
|---|---|
pages | A nonempty list of zero-based page indexes |
opacity | Opacity from 0 to 1 |
scale | Scale factor, greater than 0 |
rotation | Rotation angle from 0 to 360 degrees |
horizontalAlignment, verticalAlignment | Horizontal and vertical alignment; centered by default |
horizontalOffset, verticalOffset | Horizontal and vertical offsets |
allowView, allowPrint | Whether to display the background when viewing or printing; both default to true |
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.
final cleared = await document.clearBackground();
if (cleared) {
await document.save();
}Call save() or saveAs() to persist all changes to a file.