How to get the location of an ink signature for digital signing
If you want to digitally sign a document that doesn’t yet contain a SignatureFormField, you can add one at the location of an ink signature. To get the location of an ink signature, you have three options.
Finding an already added ink signature
@Overridepublic void onDocumentLoaded(@NonNull PdfDocument document) { // `getAllAnnotationsOfType()` is a suspend function. `runBlocking()` waits for it to finish, // so run it on a worker thread. new Thread(() -> { try { List<? extends Annotation> inkAnnotations = BuildersKt.runBlocking( EmptyCoroutineContext.INSTANCE, (scope, continuation) -> document.getAnnotationProvider() .getAllAnnotationsOfType(EnumSet.of(AnnotationType.INK), continuation));
// This will return the first ink signature found in the document. for (Annotation inkAnnotation : inkAnnotations) { if (inkAnnotation.isSignature()) { runOnUiThread(() -> digitallySignAtLocation(inkAnnotation.getBoundingBox())); break; } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }).start();}For other ways to call suspend functions from Java, see calling asynchronous APIs from Java.
Finding an ink signature that was just added
@Overridepublic void onDocumentLoaded(@NonNull PdfDocument document) { super.onDocumentLoaded(document); document.getAnnotationProvider().addOnAnnotationUpdatedListener(new AnnotationProvider.OnAnnotationUpdatedListener() { @Override public void onAnnotationCreated(@NonNull Annotation annotation) { if (annotation instanceof InkAnnotation && ((InkAnnotation) annotation).isSignature()) { // This will be called when the user adds a new ink signature. digitallySignAtLocation(annotation.getBoundingBox()); } }
@Override public void onAnnotationUpdated(@NonNull Annotation annotation) {
}
@Override public void onAnnotationRemoved(@NonNull Annotation annotation) {
}
@Override public void onAnnotationZOrderChanged(int pageIndex, @NonNull List<Annotation> oldOrder, @NonNull List<Annotation> newOrder) {
} });}Finding an ink signature that the user selected
@Overridepublic void onDocumentLoaded(@NonNull PdfDocument document) { super.onDocumentLoaded(document); getPdfFragment().addOnAnnotationSelectedListener(new AnnotationManager.OnAnnotationSelectedListener() { @Override public boolean onPrepareAnnotationSelection(@NonNull AnnotationSelectionController controller, @NonNull Annotation annotation, boolean annotationCreated) { // You can return `false` to prevent the default annotation selection from happening. return true; }
@Override public void onAnnotationSelected(@NonNull Annotation annotation, boolean annotationCreated) { if (annotation instanceof InkAnnotation && ((InkAnnotation) annotation).isSignature()) { // This will be called when the user selects an ink signature. digitallySignAtLocation(annotation.getBoundingBox()); } } });}See here for information on how to create digital signatures.