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.
3
Answers
I've solved it now by using PDFView for pdf files instead of WKWebView. A sample exemplary implementation you may find at https://github.com/cs-LA/FindInPDF.
Thanks for all your efforts to help me with this problem, Clemens
Are you sure your PDF file has text,
maybe it was converted from text to vector!
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