有一需求要把pdf中的url字串標示出來。原理是解析pdf結構,相似 xml結構。查找「Annots」的key。代碼以下。 iphone
- (void) renderPageAtIndex:(NSUInteger)index inContext:(CGContextRef)ctx inPage:(CGPDFPageRef)page{ //CGPDFPageRef page = CGPDFDocumentGetPage(pdf, i+1); CGPDFDictionaryRef pageDictionary = CGPDFPageGetDictionary(page); CGPDFArrayRef outputArray; if(!CGPDFDictionaryGetArray(pageDictionary,"Annots", &outputArray)) { return; } int arrayCount = CGPDFArrayGetCount( outputArray ); if(!arrayCount) { continue; } for( int j = 0; j <arrayCount; ++j ) { CGPDFObjectRef aDictObj; if(!CGPDFArrayGetObject(outputArray, j, &aDictObj)) { return; } CGPDFDictionaryRef annotDict; if(!CGPDFObjectGetValue(aDictObj, kCGPDFObjectTypeDictionary, &annotDict)) { return; } CGPDFDictionaryRef aDict; if(!CGPDFDictionaryGetDictionary(annotDict,"A", &aDict)) { return; } CGPDFStringRef uriStringRef; if(!CGPDFDictionaryGetString(aDict,"URI", &uriStringRef)) { return; } CGPDFArrayRef rectArray; if(!CGPDFDictionaryGetArray(annotDict,"Rect", &rectArray)) { return; } int arrayCount = CGPDFArrayGetCount( rectArray ); CGPDFReal coords[4]; for( int k = 0; k <arrayCount; ++k ) { CGPDFObjectRef rectObj; if(!CGPDFArrayGetObject(rectArray, k, &rectObj)) { return; } CGPDFReal coord; if(!CGPDFObjectGetValue(rectObj, kCGPDFObjectTypeReal, &coord)) { return; } coords[k] = coord; } char *uriString = (char *)CGPDFStringGetBytePtr(uriStringRef); NSString *uri = [NSString stringWithCString:uriString encoding:NSUTF8StringEncoding]; CGRect rect = CGRectMake(coords[0],coords[1],coords[2],coords[3]); CGPDFInteger pageRotate = 0; CGPDFDictionaryGetInteger( pageDictionary,"Rotate", &pageRotate ); CGRect pageRect = CGRectIntegral( CGPDFPageGetBoxRect( page, kCGPDFMediaBox )); if( pageRotate == 90 || pageRotate == 270 ) { CGFloat temp = pageRect.size.width; pageRect.size.width = pageRect.size.height; pageRect.size.height = temp; } rect.size.width -= rect.origin.x; rect.size.height -= rect.origin.y; CGAffineTransform trans = CGAffineTransformIdentity; trans = CGAffineTransformTranslate(trans, 0, pageRect.size.height); trans = CGAffineTransformScale(trans, 1.0, -1.0); rect = CGRectApplyAffineTransform(rect, trans); //do whatever you need with the coordinates. //e.g. you could create a button and put it on top of your page //and use it to open the URL with UIApplication's openURL NSURL *url = [NSURL URLWithString:uri]; NSLog(@"URL: %@", url); CGPDFContextSetURLForRect(ctx, (CFURLRef)url, rect); //CFRelease(url); CGContextSetFillColorWithColor(ctx, [[UIColor yellowColor] CGColor]); CGContextSetBlendMode(ctx, kCGBlendModeMultiply); CGContextSaveGState(ctx); CGContextConcatCTM(ctx, trans); CGContextFillRect(ctx, rect); CGContextRestoreGState(ctx); } }
效果以下post
另外,代碼只是處理了當前一頁。可自行修改處理整個pdf的查找標示。參考:https://ask.helplib.com/iphone/post_562254url