Skip to content
DemoSampleAPI ReferenceFAQ

PDF Generation Template Editor

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

View on GitHub
Android Guides Document modification state

Document Modification State ​

Starting with 3.2.0, use OnDocumentChangesListener to observe changes to a document's modification flag, update save controls, or decide whether to prompt before exiting.

Register a Listener ​

In the following example, document is an open CPDFDocument. Keep the listener instance so you can remove it when leaving the page or switching documents.

java
import com.compdfkit.core.document.OnDocumentChangesListener;

OnDocumentChangesListener changesListener = (changedDocument, hasChanges) -> {
    // Called on the main thread. Use hasChanges for save controls or exit prompts.
    saveButton.setEnabled(hasChanges);
};

document.addOnDocumentChangesListener(changesListener);
// Registration does not emit the current state. Initialize the UI explicitly.
saveButton.setEnabled(document.hasChanges());
kotlin
import com.compdfkit.core.document.OnDocumentChangesListener

val changesListener = OnDocumentChangesListener { _, hasChanges ->
    // Called on the main thread.
    saveButton.isEnabled = hasChanges
}

document.addOnDocumentChangesListener(changesListener)
saveButton.isEnabled = document.hasChanges()

Callback Semantics ​

BehaviorDescription
TriggerFires when the modification flag changes between false and true, not for every edit
DispatchPosted asynchronously to the main thread in transition order
ParameterhasChanges is the state at the transition; querying the document in the callback may return a later state
Duplicate registrationRegistering the same listener instance again does not add another subscription
LifecycleListeners belong to the Java document object and are not removed by closing or reloading it

A false value means the flag was cleared, which can also happen when closing the document or calling clearChanges(). Check the save method's return value or exception to determine whether saving succeeded.

The document may have closed before the callback runs. Check changedDocument.isValid() before accessing pages or other document resources.

Remove the Listener ​

Remove the listener from the original document when leaving the page, destroying its view, or switching documents:

java
document.removeOnDocumentChangesListener(changesListener);
kotlin
document.removeOnDocumentChangesListener(changesListener)

Removal cancels pending notifications for that subscription; a notification already being dispatched may complete. The document holds a strong reference to the listener, so remove it when no longer needed.

For save methods, see Save a Document.