Rendering annotations on Android
Render individual Annotation objects into Bitmap(opens in a new tab) instances with Nutrient’s synchronous or asynchronous rendering methods.
Initialize Nutrient with your license before loading a document. For setup instructions, refer to the integrating Nutrient guide.
Loading a document
Load the document with PdfDocumentLoader before rendering its annotations. For supported sources, refer to the using an activity guide.
The following example opens an app asset with PdfDocumentLoader.openDocument() and a file:///android_asset URI:
// Use this `Uri` format to access files inside your app's assets.val documentUri = Uri.parse("file:///android_asset/shopping-center-plan.pdf")
// This synchronously opens the document. To keep your app UI responsive, either// don't run this on the main thread, or call the suspend function `openDocumentAsync()`// from a coroutine instead.val document: PdfDocument = PdfDocumentLoader.openDocument(context, documentUri)// Use this `Uri` format to access files inside your app's assets.final Uri documentUri = Uri.parse("file:///android_asset/shopping-center-plan.pdf");
// This synchronously opens the document. To keep your app UI responsive,// don't run this on the main thread.final PdfDocument document = PdfDocumentLoader.openDocument(context, documentUri);PdfDocumentLoader.openDocument() throws an exception if loading fails. Wrap the call in try/catch to handle errors.
Retrieving annotations
Retrieve the PdfDocument’s AnnotationProvider with document.getAnnotationProvider(). Query annotations by page number or type:
// `getAllAnnotationsOfType()` is a suspend function, so call it from a coroutine.lifecycleScope.launch { // Retrieves all ink annotations of the document. val inkAnnotations = document .annotationProvider .getAllAnnotationsOfType(EnumSet.of(AnnotationType.INK))}import kotlin.coroutines.EmptyCoroutineContext;import kotlinx.coroutines.BuildersKt;
// Retrieves all ink annotations of the document.// `getAllAnnotationsOfType()` is a suspend function. `runBlocking()` waits for it to finish,// so only call this on a worker thread.try { final List<? extends Annotation> inkAnnotations = BuildersKt.runBlocking( EmptyCoroutineContext.INSTANCE, (scope, continuation) -> document.getAnnotationProvider() .getAllAnnotationsOfType(EnumSet.of(AnnotationType.INK), continuation));} catch (InterruptedException e) { Thread.currentThread().interrupt();}Java can’t call suspend functions directly. See calling asynchronous APIs from Java for the options.
To retrieve all annotations, pass AnnotationProvider#ALL_ANNOTATION_TYPES to getAllAnnotationsOfType().
Rendering annotations
Use Annotation’s renderToBitmap() method for synchronous rendering or its renderToBitmapAsync() suspend function for asynchronous rendering.
Preparing a Bitmap
Create a target Bitmap(opens in a new tab) with Bitmap.createBitmap()(opens in a new tab). Use Bitmap.Config.ARGB_8888(opens in a new tab) to preserve transparent regions:
// Create a bitmap with an alpha channel so that transparent parts// of the annotation are properly displayed.val bitmap = Bitmap.createBitmap( bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888)// Create a bitmap with an alpha channel so that transparent parts// of the annotation are properly displayed.final Bitmap bitmap = Bitmap.createBitmap( bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);Rendering stretches the annotation to fill the bitmap. To preserve its proportions, create a bitmap with the annotation’s aspect ratio.
Calculating the Bitmap size
Calculate the bitmap size from the annotation’s bounding box. Retrieve the box with annotation.getBoundingBox():
// The annotation has a size, which can be calculated from its bounding box.val annotationWidth = annotation.boundingBox.width()val annotationHeight = -annotation.boundingBox.height()
// Create a bitmap with a width of 300 pixels. The height of the bitmap is derived// by proportionally fitting the annotation into the width of the bitmap.val bitmapWidth = 300val heightFactor = bitmapWidth / annotationWidthval bitmapHeight = (annotationHeight * heightFactor).toInt()// The annotation has a size, which can be calculated from its bounding box.final float annotationWidth = annotation.getBoundingBox().width();final float annotationHeight = -annotation.getBoundingBox().height();
// Create a bitmap with a width of 300 pixels. The height of the bitmap is derived// by proportionally fitting the annotation into the width of the bitmap.final int bitmapWidth = 300;final float heightFactor = bitmapWidth / annotationWidth;final int bitmapHeight = (int) (annotationHeight * heightFactor);PDF coordinates have the opposite vertical direction from Android coordinates. Negate the returned height()(opens in a new tab) to get a positive height. For details, refer to the PDF coordinates guide.
Synchronous rendering
Pass the prepared bitmap to renderToBitmap() to render synchronously:
// This is the bitmap you already prepared (see explanation above).annotation.renderToBitmap(bitmap)// This is the bitmap you already prepared (see explanation above).annotation.renderToBitmap(bitmap);annotation.renderToBitmap() blocks until rendering completes. Don’t call it on the main thread. Use asynchronous rendering instead.
Asynchronous rendering
Use renderToBitmapAsync() to avoid blocking the calling thread. Call this suspend function from a coroutine, which can run on the main thread. It returns the Bitmap(opens in a new tab) when rendering completes. From Java, call renderToBitmap() on a worker thread instead:
val annotationRendering = lifecycleScope.launch { try { val renderedBitmap = annotation.renderToBitmapAsync(bitmap) // Rendering is done. Use your bitmap here. } catch (e: CancellationException) { throw e } catch (e: Exception) { // There was an error while rendering. }}
// If you ever need to cancel the async render operation, use this.annotationRendering.cancel()// `renderToBitmap()` blocks until rendering is done, so run it on a worker thread.new Thread(() -> { try { annotation.renderToBitmap(bitmap); // Rendering is done. Use your bitmap here. } catch (Exception e) { // There was an error while rendering. }}).start();Rendering runs in a coroutine. To cancel rendering, call cancel() on the Job that launch returns.
Providing an annotation render configuration
Both rendering methods accept AnnotationRenderConfiguration. Create the configuration with its Builder:
val config = AnnotationRenderConfiguration.Builder() .toGrayscale(true) .build()
// Renders the annotation to the bitmap in grayscale.annotation.renderToBitmap(bitmap, config)final AnnotationRenderConfiguration config = new AnnotationRenderConfiguration.Builder() .toGrayscale(true) .build();
// Renders the annotation to the bitmap in grayscale.annotation.renderToBitmap(bitmap, config);Available render options
The Builder supports these options:
- Invert annotation colors with
invertColors(). - Render in grayscale with
toGrayscale(). - Set form field highlight colors with
formHighlightColor(). - Set selected form item colors with
formItemHighlightColor(). - Set required field border colors with
formRequiredFieldBorderColor().