Search code examples
iosswifthighlightios-pdfkitapple-pdfkit

How to highlight selected text in pdf using PDFKit?


I have set up a PDFViewer and would like to add a highlight functionality so that when a user selects text, they could highlight it. When you highlight text in notes, iMessages etc. you have the option to select all, copy, paste etc. How would you edit this so that you could have a highlight functionality as well? Also, how would the application save the highlighting so when a user closed and reopened the app, they would still be able to view the highlighted text? Would this involve using core data or something else? Thanks!

this is a screenshot of the default functionalities that Apple provides but I would like to add an additional highlighting functionality


Solution

  • let select = pdfView.currentSelection?.selectionsByLine()
        //assuming for single-page pdf.
        guard let page = select?.first?.pages.first else { return }
    
        select?.forEach({ selection in
            let highlight = PDFAnnotation(bounds: select.bounds(for: page), forType: .highlight, withProperties: nil)
            highlight.endLineStyle = .square
            highlight.color = UIColor.orange.withAlphaComponent(0.5)
    
            page.addAnnotation(highlight)
        })