Search and redact PDFs on Android

Nutrient Android SDK enables you to search and redact text in a PDF document. In this guide, you’ll see how to redact a search term in a document.

The process involves using the TextSearch API and then looping through the search results, adding RedactionAnnotations as you loop:

val wordToSearch = "secret"
val textSearch = TextSearch(document, configuration)
val searchResults = textSearch.performSearch(wordToSearch)
for (searchResult in searchResults) {
val redaction = RedactionAnnotation(searchResult.pageIndex, searchResult.textBlock.pageRects).apply {
color = Color.BLACK
fillColor = Color.BLACK
outlineColor = Color.YELLOW
overlayText = "REDACTED"
}
document.annotationProvider.addAnnotationToPage(redaction)
}

Finally, create a new PDF file for the redacted document by applying redactions.

You can do so using the PdfProcessor API:

val outputFile: File
val document: PdfDocument
val processorTask = PdfProcessorTask.fromDocument(document)
.applyRedactions()
PdfProcessor.processDocument(processorTask, outputFile)
val redactedDocument = PdfDocumentLoader.openDocument(context, Uri.fromFile(outputFile))

Or, you can use the DocumentSaveOptions#setApplyRedactions() option when saving the document via any of the save methods on PdfDocument.

Bear in mind that this will overwrite the existing document, removing content irreversibly:

val documentSaveOptions = DocumentSaveOptions(null, null, true, null);
documentSaveOptions.setApplyRedactions(true)
document.saveIfModified(documentSaveOptions)