Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...