Anwer Solangi
Anwer Solangi

Reputation: 327

Search and highlight text of current text in PDFKit Swift

I'm working on a React Native app that displays PDFs using a custom NativeModule written in Swift. The module successfully renders PDFs from a provided file URL. But, I'm struggling with a feature to highlight specific text within the PDF.

I'm passing text to highlight, startOffset and endOffset, and Page No. from React Native to the NativeModule using the Bridge. The offsets are obtained from page.string, and due to which offsets might not always translate accurately to rectangle selection due to variations in font styles and layouts:\n I tried the below approach by searching from various platforms, but did not helped me.

  @objc
  func highlightText(_ pageNumber: Int, startOffset: Int, endOffset: Int, searchText: String, changeType: String) {
      guard let page = pdfView.document?.page(at: pageNumber - 1) else {
          print("Failed to get PDF page for page \(pageNumber)")
          return
      }
    // Create a PDFSelection based on the offsets
    let startIndex = searchText.index(searchText.startIndex, offsetBy: startOffset)
    let endIndex = searchText.index(searchText.startIndex, offsetBy: endOffset)
    let range = NSRange(startIndex..<endIndex, in: searchText)
    let selection = page.selection(for: range)!
    
    // Get the bounding box of the selection
    let boundingBox = selection.bounds(for: page)
    
    // Create a highlight annotation and add it to the page
    let highlight = PDFAnnotation(bounds: boundingBox, forType: .highlight, withProperties: nil)
    highlight.color = UIColor.yellow.withAlphaComponent(0.5) // Adjust highlight color and opacity
    page.addAnnotation(highlight)
  }

I tried the below approaches:

  1. Tried something like document.findString, but it takes time and memory, and sometimes kill the App.
  2. Tried getting CGRect from offsets, but can't get these also.

I want a solution, where I just wanted to highlight the text on the Page Number.

Upvotes: 0

Views: 113

Answers (0)

Related Questions