Search code examples
ipaduiwebviewcore-graphicshighlightingepub

How highlight and save selected text in UIwebview using Coregraphics


How to make persistent Highlight on UIWebView (containing epub contents) so that he can view it whenever he come to that page. What I came to conclusion that I succeeded in getting the index of the selected text which I could save in database.

What I need to create a transparent rectangle sort of thing using graphics from starting to end index. But how to know the coordinates of text so that I can draw rectangle on it.


Solution

  • Inorder to make permanent highlight in epub add a span to the string you want to highlight then rewrite that HTML. Highlight would be preserved for ever

        NSString *uuid = [[NSUUID UUID] UUIDString];
    
        NSString *insertSpan = [NSString stringWithFormat:@"var range = window.getSelection().getRangeAt(0);var selectionContents   = range.extractContents();alert(selectionContents); var span                = document.createElement(\"span\");span.appendChild(selectionContents);span.setAttribute(\"class\",\"uiWebviewHighlight\");span.style.backgroundColor  = \"#99FF00\";span.setAttribute(\"id\", \"%@\");range.insertNode(span);",uuid];
       [webView stringByEvaluatingJavaScriptFromString:insertSpan];
    
        NSString *document = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"];
    
        NSData *data = [document dataUsingEncoding:NSUTF8StringEncoding];
    
       [data writeToFile:currentChapter.spinePath atomically:YES];