I have some pdf's in my application and am using PdfKit in swift. Now i want to highlight all the hyperlinks in a pdf document. I tried using PDFAnnotationSubtype.highlight and PDFAnnotationSubtype.link but in both cases i could not achieve my goal.
For PDFAnnotationSubtype.highlight - on click of links i could not add action to it.
For PDFAnnotationSubtype.link - i could not set color or background color to links.
Here is my code please correct me if am missing something here.
//here i get my pdf from document directory
let filePAth = (self.getDirectoryPath() as NSString).appendingPathComponent(webURLString)
let fileURL = URL(fileURLWithPath: filePAth)
let document = PDFDocument(url: fileURL)
self.pdfView.displayMode = .twoUpContinuous
self.pdfView.displayDirection = .horizontal
pdfView.usePageViewController(true, withViewOptions: [UIPageViewController.OptionsKey.interPageSpacing: 0])
//here is the hack
//i am getting annotation
let count = document?.pageCount
for i in 0 ..< count! {
let page = document?.page(at: i)
let annotationArray = page1?.annotations
for annotationObj in annotationArray! {
if annotationObj.type! == "Link" {
//case 1: highlights hyperlinks links but
//added action does not work
let annotation = PDFAnnotation(bounds: obj.bounds, forType: PDFAnnotationSubtype.highlight, withProperties: nil)
annotation.color = UIColor.red
annotation.isHighlighted = true
// highlights all the hyperlinks with red color
// but added action does not work here
let url = URL(string: "http://google.com/")
annotation.action = PDFActionURL(url: url!)
page?.addAnnotation(annotation)
//case 2: does not highlights hyperlinks links with red
//color but added action works
let annotation = PDFAnnotation(bounds: obj.bounds, forType: PDFAnnotationSubtype.link, withProperties: nil)
// no effect
annotation.color = UIColor.red
annotation.isHighlighted = true
// does not highlight all the hyperlinks with red
// but added action works here
let url = URL(string: "http://google.com/")
annotation.action = PDFActionURL(url: url!)
page?.addAnnotation(annotation)
}
}
}
I am able out find the way. can anyone suggest somethings? Image is result of case 1 mentioned in the code.
Even it is not a proper solution, though it is a hack.
Step 1 - Create link annotation and add existing annotation action to new link annotation.
let linkAnnotation = PDFAnnotation(bounds: obj.bounds, forType: PDFAnnotationSubtype.link, withProperties: nil)
linkAnnotation.action = obj.annotation
Step 2 - Add new link annotation to page after your highlighted annotation.
page?.addAnnotation(linkAnnotation)
Try and let me know if this works for you.