PDF viewer events

Nutrient provides the DocumentListener interface, which allows you to hook into interesting document events like document loading, page changes, page clicks, and more. Have a look at FragmentExample or CustomLayoutExample of the Catalog app, both of which, among other examples, showcase DocumentListener usage.

Registering a document listener

Add a document listener to a PdfFragment by registering it using the addDocumentListener() method. You can register as many document listeners as you like:

fragment.addDocumentListener(myDocumentListener)

ℹ️ Note: To prevent memory leaks, PdfFragment removes all previously registered listeners inside its #onDetach method.

Unregistering a document listener

If you want to stop receiving document events on a listener, provide the listener instance to removeDocumentListener(). Performance wise, you’re encouraged to unregister the listener as soon as you don’t need it anymore, e.g. inside your activity’s onStop()(opens in a new tab) method:

fragment.removeDocumentListener(myDocumentListener)

Document events

The DocumentListener interface provides callback methods for important and interesting document events:

ℹ️ Note: All page numbers in Nutrient have a zero-based index, meaning 0 denotes the first page of a document and pageCount - 1 denotes the last document page.

Activity callbacks

PdfActivity implements DocumentListener interfaces by default, allowing you to listen for events by overriding the associated methods in your subclassed activities:

class MyActivity : PdfActivity() {
override fun onDocumentLoaded(document : PdfDocument) {
Toast.makeText(this, "Document has been loaded with ${document.pageCount} pages",
Toast.LENGTH_SHORT).show()
}
override fun onDocumentLoadFailed(exception : Throwable?) {
Toast.makeText(this, "Document loading failed!", Toast.LENGTH_SHORT).show()
exception?.printStackTrace()
}
}