在iOS上使用Core Graphics在PDF中embedded超链接

我试图做一个很简单的事情:在一个PDF文件中写一个URL,用户可以真正点击它。

我知道使用libharu它可以完成。 我正在寻找的是使用核心graphics做同样的事情,因为我已经在我的应用程序中已经有了整个代码已经使用这些方法。

==编辑==

我想我find了一些东西: UIGraphicsSetPDFContextURLForRect但我不能让它工作。

我正在使用类似于:

 NSURL *url = [NSURL URLWithString:@"http://www.google.com"]; UIGraphicsSetPDFContextURLForRect( url, CGRectMake(0, 0, 100, 100)); 

虽然,矩形是不可点击的。

好吧,我设法弄清楚为什么它不工作。

核心graphics上下文在页面左下angular的原点是“反转的”,而UIKit的原点位于左上angular。

这是我想出的方法:

 - (void) drawTextLink:(NSString *) text inFrame:(CGRect) frameRect { CGContextRef context = UIGraphicsGetCurrentContext(); CGAffineTransform ctm = CGContextGetCTM(context); // Translate the origin to the bottom left. // Notice that 842 is the size of the PDF page. CGAffineTransformTranslate(ctm, 0.0, 842); // Flip the handedness of the coordinate system back to right handed. CGAffineTransformScale(ctm, 1.0, -1.0); // Convert the update rectangle to the new coordiante system. CGRect xformRect = CGRectApplyAffineTransform(frameRect, ctm); NSURL *url = [NSURL URLWithString:text]; UIGraphicsSetPDFContextURLForRect( url, xformRect ); CGContextSaveGState(context); NSDictionary *attributesDict; NSMutableAttributedString *attString; NSNumber *underline = [NSNumber numberWithInt:NSUnderlineStyleSingle]; attributesDict = @{NSUnderlineStyleAttributeName : underline, NSForegroundColorAttributeName : [UIColor blueColor]}; attString = [[NSMutableAttributedString alloc] initWithString:url.absoluteString attributes:attributesDict]; [attString drawInRect:frameRect]; CGContextRestoreGState(context); } 

这个方法做的是:

  • 获取当前的上下文,并对所提供的矩形进行转换,以获得在UIGraphicsSetPDFContextURLForRect将其标记为可点击时在标记框时工作的矩形
  • 使用上述方法将新矩形( xformRect )标记为可点击
  • 为了保存当前的上下文,所以后面所做的任何事情(颜色,大小,属性等等)都不会在当前的上下文中保持不变
  • 在提供的矩形中绘制文本(现在使用UIKit坐标系)
  • 恢复上下文GState