以编程方式在PDF文件中创建链接

时间:2012-04-12 21:36:34

标签: objective-c hyperlink pdf-generation

虽然我认为这是一个基本问题,但我找不到有效的回复。我正在通过描绘PDF上下文的路径来创建PDF文件,我希望绘图上的不同区域是外部内容的超链接(http://bla.bla)。即使是非交叉矩形的区域,我也会很开心。谁知道怎么做?

1 个答案:

答案 0 :(得分:4)

检查此问题的答案是否有效:Embed hyperlink in PDF using Core Graphics on iOS

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