Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotate PDF within iPhone SDK

I have managed to implement a very basic PDF viewer within my application, but was wondering if it was possible to add annotations to the PDF. I have looked through the SDK docs, but not found anything. I have 2 questions really:

  1. Is it possible to do this?
  2. What is the best approach to take?
  3. Is there a framework or library that I can include to assist with this?

Thanks.

like image 779
Jack Avatar asked Feb 22 '10 18:02

Jack


2 Answers

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);
}
like image 103
Obliquely Avatar answered Oct 21 '22 03:10

Obliquely


I am working in the stuff and created a GitHub project. Please check it out here.

like image 32
lazyprogram Avatar answered Oct 21 '22 05:10

lazyprogram