PDFKit Highlight Annotation: quadrilateralPoints

2020-07-27 05:23发布

问题:

I want to add highlight annotation into pdf file by using PDFKit. And I use this below code to add it.

PDFPage* page = [self.pdfView.document pageAtIndex:0];
PDFAnnotation* annotation = [[PDFAnnotation alloc] initWithBounds:CGRectMake(206, 600, 60, 59) forType:PDFAnnotationSubtypeHighlight withProperties:nil];
annotation.color = UIColor.blueColor;
[page addAnnotation:annotation];

But it just highlight one rectangle, I want to highlight multiple lines text. I have found one question/answer Wrong highlight annotation on apple PDFKit

But it is not what I want, it will add many highlight annotations, I just want to add one annotation. And I learn that the key-value QuadPoints can do this. But it doesn't work when I add the below code, even can't render the annotation.

NSArray<NSValue *> *quadrilateralPoints = [[NSArray alloc] initWithObjects:
                                           [NSValue valueWithCGPoint:CGPointMake(206.0f, 659.0f)],
                                           [NSValue valueWithCGPoint:CGPointMake(266.0f, 659.0f)],
                                           [NSValue valueWithCGPoint:CGPointMake(206.0f, 600.0f)],
                                           [NSValue valueWithCGPoint:CGPointMake(266.0f, 600.0f)],
                                           nil];

annotation.quadrilateralPoints = quadrilateralPoints;

So now I want to know how to implement it? or how to use quadrilateralPoints ?

回答1:

I have found the answer: below code works

NSArray<NSValue *> *quadrilateralPoints = [[NSArray alloc] initWithObjects:
                                       [NSValue valueWithCGPoint:CGPointMake(206.0 - 206, 659.0 - 600)],
                                       [NSValue valueWithCGPoint:CGPointMake(266.0 - 206, 659.0 - 600)],
                                       [NSValue valueWithCGPoint:CGPointMake(206.0 - 206, 600.0 - 600)],
                                       [NSValue valueWithCGPoint:CGPointMake(266.0 - 206, 600.0 - 600)],
                                       nil];

annotation.quadrilateralPoints = quadrilateralPoints;

because it is based on origin bounds



回答2:

I've found that a better way of doing this is to use the .quadPoints annotationKey. This method matches the PDF spec and is not part of the PDFAnnotationUtilities.h file which is provided for legacy functions compatibility. This way doesn't require you to adjust for the bounds.

let quadPoints:[CGPoint] = [CGPoint(x:206.0, y:659.0),
                            CGPoint(x:266.0, y:659.0),
                            CGPoint(x:206.0, y:600.0),
                            CGPoint(x:266.0, y:600.0)]


annotation.setValue(quadPoints, forAnnotationKey: .quadPoints)

To complete the answer you should also use selectionsByLine function of PDFSelection to get all of the selections on a certain page and make one annotation per page as described in Wrong highlight annotation on apple PDFKit