Home > Back-end >  How to find and highlight a string in a pdf displayed in a WKWebView?
How to find and highlight a string in a pdf displayed in a WKWebView?

Time:10-27

I have an iOS app where I can display html and pdf-files. I try to implement a find-in-page functionality which is available since iOS14 (find(_:configuration:completionHandler:)).

Here is my implementation:

  private func searchInPage(forward: Bool) {
    ktWebView.select(nil)
    searchIsAtTop = false
    searchIsAtEnd = false
    
    let searchConfig = WKFindConfiguration()
    searchConfig.backwards = !forward
    searchConfig.caseSensitive = false
    searchConfig.wraps = false
    ktWebView.find(searchString, configuration: searchConfig, completionHandler: { result in
      // https://stackoverflow.com/questions/64193691/ios-wkwebview-findstring-not-selecting-and-scrolling
      guard result.matchFound else {
        if forward { searchIsAtEnd = true }
        else { searchIsAtTop = true }
        return
      }
      ktWebView.evaluateJavaScript("window.getSelection().getRangeAt(0).getBoundingClientRect().top") { offset, _ in
        guard let offset = offset as? CGFloat else { return }
        ktWebView.scrollView.scrollRectToVisible(
          .init(x: 0, y: offset   ktWebView.scrollView.contentOffset.y,
                width: 100, height: 100), animated: true)
      }
    })
  }

With each invocation of this function the next occurrence of the searchString will be highlighted and scrolled to.

This works fine as long as the mime type of the WKWebView content is text/html. When it is application/pdf it doesn't work.

Can anyone help me with a solution to find a string in a pdf document displayed in a WKWebView?

Thanks, Clemens

I have no clue how to approach this problem. Any help is appreciated.

CodePudding user response:

Are you sure your PDF file has text, maybe it was converted from text to vector!

CodePudding user response:

It working for text files, maybe need to copy text from PDF and render it as a text / string, found some example: Can't copy text from PDF which created with iOS Swift

  • Related