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)
}
final String wordToSearch = "secret";
final TextSearch textSearch = new TextSearch(document, configuration);
final List<SearchResult> searchResults = textSearch.performSearch(wordToSearch);

for (SearchResult searchResult : searchResults) {
    final RedactionAnnotation redaction = new RedactionAnnotation(searchResult.pageIndex, searchResult.textBlock.pageRects);
    redaction.setColor(Color.BLACK);
    redaction.setFillColor(Color.BLACK);
    redaction.setOutlineColor(Color.YELLOW);
    redaction.setOverlayText("REDACTED");

    document.getAnnotationProvider().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))
final File outputFile;
final PdfDocument document;
final PdfProcessorTask processorTask = PdfProcessorTask.fromDocument(document)
    .applyRedactions();

PdfProcessor.processDocument(processorTask, outputFile);
final PdfDocument 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)
final DocumentSaveOptions documentSaveOptions = new DocumentSaveOptions(null, null, false, null);
documentSaveOptions.setApplyRedactions(true);
document.saveIfModified(documentSaveOptions);