iOS在创建PDF时添加链接

时间:2014-03-11 13:10:56

标签: ios pdf hyperlink pdf-generation

我正在iOS中使用UIGraphicsBeginPDFContextToFile创建PDF,我想在其中添加URL链接到其他页面以及其他网站。下面是代码:这里pdfObj是一个自定义类,它将文本绘制为PDF。在成功创建PDF之后,如果我单击"转到第1章"和"转到网址"

UIGraphicsBeginPDFContextToFile(documentDirectoryFilename, CGRectZero, nil);
UIGraphicsBeginPDFPage();

//Page 1
UIGraphicsAddPDFContextDestinationAtPoint(@"Chapter1", CGPointMake(0, 0));
//other draw pdf data....

//Page 2
UIGraphicsBeginPDFPage();
//other draw pdf data....
[pdfObj addHeaderText:@"Go to Chapter 1" atFrame:CGRectMake(50, 50, 200, 44)];
UIGraphicsSetPDFContextDestinationForRect(@"Chapter1", CGRectMake(50, 50, 200, 44));

[pdfObj addHeaderText:@"Go to URL" atFrame:CGRectMake(550, 550, 200, 44)];
UIGraphicsSetPDFContextURLForRect([NSURL urlWithString:@"http://www.myURL.com"], CGRectMake(550, 550, 200, 44));

UIGraphicsEndPDFContext();

请让我知道我在这里犯了什么错误

1 个答案:

答案 0 :(得分:1)

检查此问题的答案是否有效: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);
}