使用iOS上的Core Graphics在PDF中嵌入超链接

Fab*_*oni 4 pdf core-graphics hyperlink ios

我正在尝试做一个非常简单的事情:在PDF文件中写一个可以被用户实际点击的URL.

我确信使用libharu可以完成.我正在寻找的是使用Core Graphics做同样的事情,因为我在我的应用程序中已有的整个代码已经在使用这些方法.

==编辑==

我想我找到了一些东西:UIGraphicsSetPDFContextURLForRect但我不能让它发挥作用.

我正在使用类似的东西:

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

但是,rect不可点击.

Fab*_*oni 12

好的,我设法弄清楚它为什么不起作用.

核心图形上下文在页面左下角的原点意义上是"反转的",而UIKit的原点位于左上角.

这是我提出的方法:

- (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);
}
Run Code Online (Sandbox Code Playgroud)

这种方法的作用是:

  • 获取当前上下文并将转换应用于提供的rect,以便获得一个矩形,当标记该框时,UIGraphicsSetPDFContextURLForRect它会将其标记为可点击
  • xformRect使用上述方法将新的rect()标记为可点击
  • 保存当前上下文,以便以后执行的任何操作(颜色,大小,属性等等)都不会在当前上下文中保持持久性
  • 在提供的rect中绘制文本(现在使用UIKit坐标系)
  • 恢复上下文GState

  • 好工作fabiano (2认同)