objective-cios-pdfkit

How to add anotation to my pdf using objective c?


I'm fairly new to objective c and Apple's PdfKit framework and i'm unable to draw anotations on top of my pdf.

I get no errors on the console. This is my code :

PDFAnnotation  * observation = [[PDFAnnotation alloc] init];
CGRect cgRect = CGRectMake(20, 20, 120, 120);
                
observation.widgetFieldType = PDFAnnotationWidgetSubtypeButton;
observation.bounds = cgRect;
observation.shouldDisplay = true;
observation.backgroundColor = UIColor.redColor;
observation.widgetFieldType= PDFAnnotationWidgetSubtypeButton;
                
[page addAnnotation:observation];

Does someone know why my pdfanotation is not drawn on my pdf ? I'm also wondering if the PdfKit framework is fully supported on objective c as the apple's documentation for it just has examples that are made using swift.

Thank you for your help !


Solution

  • Your annotation is not drawn because you forgot to set the type. It's probably a mistake, because you're setting widgetFieldType twice. Here's the correct button widget setup:

    PDFAnnotation  *observation = [[PDFAnnotation alloc] init];
    observation.bounds = CGRectMake(20, 20, 200, 100);
    
    observation.type = PDFAnnotationSubtypeWidget;
    observation.widgetFieldType = PDFAnnotationWidgetSubtypeButton;
    observation.widgetControlType = kPDFWidgetCheckBoxControl;
    
    observation.backgroundColor = UIColor.redColor;
    [page addAnnotation:observation];
    

    To avoid future mistakes like this one, use the following initializer:

    - (instancetype)initWithBounds:(CGRect)bounds 
                           forType:(PDFAnnotationSubtype)annotationType 
                    withProperties:(NSDictionary *)properties;
    

    And change the setup code to:

    PDFAnnotation  *observation = [[PDFAnnotation alloc] initWithBounds:CGRectMake(20, 20, 200, 100)
                                                                forType:PDFAnnotationSubtypeWidget
                                                         withProperties:nil];
    observation.widgetFieldType = PDFAnnotationWidgetSubtypeButton;
    observation.widgetControlType = kPDFWidgetCheckBoxControl;
    observation.backgroundColor = UIColor.redColor;
        
    [page addAnnotation:observation];
    

    I'd highly recommend to setup appearance (like backgroundColor) as the last thing. Because all these values are modified by PDFKit when you change the type.

    Also be aware that 0, 0 is bottom/left corner (bounds).