Annotate PDF within iPhone SDK

You can do annotation by reading in a PDF page, drawing it onto a new PDF graphics context, then drawing extra content onto that graphic context. Here is some code that adds the words ‘Example annotation’ at position (100.0,100.0) to an existing PDF. The method getPDFFileName returns the path of the original PD. getTempPDFFileName returns the path of the new PDF, the one that is the original plus the annotation.

To vary the annotations, just add in more drawing code in place of the drawInRect:withFont: method. See the Drawing and Printing Guide for iOS for more on how to do that.

- (void) exampleAnnotation;
{
    NSURL* url = [NSURL fileURLWithPath:[self getPDFFileName]];

    CGPDFDocumentRef document = CGPDFDocumentCreateWithURL ((CFURLRef) url);// 2
    size_t count = CGPDFDocumentGetNumberOfPages (document);// 3

    if (count == 0)
    {
        NSLog(@"PDF needs at least one page");
        return;
    }

    CGRect paperSize = CGRectMake(0.0,0.0,595.28,841.89);

    UIGraphicsBeginPDFContextToFile([self getTempPDFFileName], paperSize, nil);

    UIGraphicsBeginPDFPageWithInfo(paperSize, nil);

    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    // flip context so page is right way up
    CGContextTranslateCTM(currentContext, 0, paperSize.size.height);
    CGContextScaleCTM(currentContext, 1.0, -1.0); 

    CGPDFPageRef page = CGPDFDocumentGetPage (document, 1); // grab page 1 of the PDF 

    CGContextDrawPDFPage (currentContext, page); // draw page 1 into graphics context

     // flip context so annotations are right way up
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    CGContextTranslateCTM(currentContext, 0, -paperSize.size.height);

    [@"Example annotation" drawInRect:CGRectMake(100.0, 100.0, 200.0, 40.0) withFont:[UIFont systemFontOfSize:18.0]];

    UIGraphicsEndPDFContext();

    CGPDFDocumentRelease (document);
}

Leave a Comment