Created
February 22, 2017 16:20
-
-
Save sketchytech/b5667638277a36c1f420aab0510f7618 to your computer and use it in GitHub Desktop.
Swift 3: PDF text search on macOS returns page labels (numbers) as strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
import Quartz | |
enum SearchType: Int { | |
case CaseInsensitiveSearch = 1, LiteralSearch, BackwardsSearch, AnchoredSearch, NumericSearch | |
} | |
extension PDFDocument { | |
func pages(withString str:String, searchType type:SearchType) -> [String] { | |
let selec = self.findString(str, withOptions: type.rawValue) | |
var arrayOfPages = [String]() | |
for s in selec { | |
for p in s.pages { | |
let pageIndex = self.index(for:p) | |
let page = self.page(at:pageIndex) | |
if let label = page?.label { | |
arrayOfPages.append(label) | |
} | |
} | |
} | |
return arrayOfPages | |
} | |
} | |
guard let url = Bundle.main.url(forResource: "myPDF", withExtension: "pdf") else { | |
fatalError() | |
} | |
let pdf = PDFDocument(url: url) | |
pdf?.pages(withString: "Your search text here", searchType: .CaseInsensitiveSearch) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment