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.
ComPDF Flutter SDK provides a page copy API for duplicating a page in the current PDF document and inserting the copied page at a target position. This is useful for page reordering, template reuse, and quickly creating similar pages.
The page copy API is available on CPDFDocument:
Future<bool> copyPage({
required int pageIndex,
required int insertIndex,
});Parameter description:
| Parameter | Description |
|---|---|
pageIndex | The zero-based index of the source page to copy |
insertIndex | The zero-based insertion index for the copied page; use -1 to append to the end of the document |
Return value:
true: the page was copied and inserted successfully.false: the page index is invalid, the insertion index is invalid, or the native platform failed to copy the page.Use copyPage(pageIndex, insertIndex) to duplicate a page in the current document and insert the copy at the desired position.
final CPDFDocument document = await CPDFDocument.createInstance();
await document.open('/path/to/sample.pdf');
final bool result = await document.copyPage(
pageIndex: 0,
insertIndex: 1,
);
print('Copy page result: $result');This example copies the first page and inserts the copy before the second page.
If insertIndex is set to -1, the copied page is appended to the end of the document:
final bool result = await document.copyPage(
pageIndex: 0,
insertIndex: -1,
);When you use CPDFReaderWidget, you can call the same API through CPDFReaderWidgetController.document. After a successful copy, refresh the reader view so the new page count is reflected.
Future<void> copyCurrentPage(CPDFReaderWidgetController controller) async {
final int pageIndex = await controller.getCurrentPageIndex();
final bool result = await controller.document.copyPage(
pageIndex: pageIndex,
insertIndex: -1,
);
if (result) {
controller.reloadPages();
}
}This is a good fit for custom toolbars, page menus, or batch page operations.
The following example opens a PDF, duplicates the first page, and appends the copy to the end of the document.
import 'package:compdfkit_flutter/document/cpdf_document.dart';
Future<void> duplicateFirstPage(String filePath) async {
final CPDFDocument document = await CPDFDocument.createInstance();
await document.open(filePath);
final bool result = await document.copyPage(
pageIndex: 0,
insertIndex: -1,
);
if (!result) {
throw Exception('Copy page failed.');
}
print('Page copied successfully.');
}pageIndex must point to an existing page in the current document, otherwise the API returns false.insertIndex supports 0..pageCount; -1 means append to the end of the document.false.copyPage multiple times in the order required by your business logic.