Search and Redact PDFs on iOS
PSPDFKit 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.
First, you’ll have to loop through all the pages in the document to find the search term and mark the matching strings for redaction. To get the text in the document, you’ll need to use TextParser
, which you can access via the Document
’s textParserForPage(at:)
(opens in a new tab) method:
let fileURL = Bundle.main.url(forResource: "Document", withExtension: "pdf")!let document = Document(url: fileURL)
let wordToRedact = "Personal"
for pageIndex in 0..<document.pageCount { if let textParser = document.textParserForPage(at: pageIndex) { textParser.words.forEach { word in // Redact all the words that contain the search term. if word.stringValue.range(of: wordToRedact!) != nil { // Create a redaction annotation for each URL and add it to the document. let redactionRect = word.frame let redaction = RedactionAnnotation() redaction.boundingBox = redactionRect redaction.rects = [redactionRect] redaction.color = .orange redaction.fillColor = .black redaction.overlayText = "REDACTED" redaction.pageIndex = pageIndex document.add(annotations: [redaction]) } }}
And finally, create a new PDF file for the redacted document by applying redactions using the Processor
API, instantiate a Document
object, and present it in a PDFViewController
, like so:
// Use Processor to create the newly redacted document.let processorConfiguration = Processor.Configuration(document: document)!
// Apply redactions to permanently redact URLs from the document.processorConfiguration.applyRedactions()
let processor = Processor(configuration: processorConfiguration, securityOptions: nil)try? processor.write(toFileURL: redactedDocumentURL)
// Instantiate the redacted document and present it.let redactedDocument = Document(url: redactedDocumentURL)let pdfController = PDFViewController(document: redactedDocument)present(UINavigationController(rootViewController: pdfController), animated: true)
For more details about redacting a document using regular expressions, refer to SearchAndRedactTextExample.swift
(opens in a new tab) in the PSPDFKit Catalog(opens in a new tab) app.