在iOS或Cocoa上寻找如何使用UIGraphicsSetPDFContextURLForRect

时间:2012-09-16 22:58:41

标签: ios cocoa pdf hyperlink

我正在玩iOS上操作PDF(显示但也主要是生成)。

我希望嵌入充当“外部”链接的矩形区域(http://host.tld/path/file等网址)。

您知道在哪里可以找到如何使用UIGraphicsSetPDFContextURLForRect函数的示例吗?我在互联网上绝对没有找到任何东西。

如果我理解得很好,唯一的要求就是当前的图形上下文应该是PDF“type”,我认为我尊重这一点,因为上游我称之为UIGraphicsPushContext为什么我的PDF上下文作为参数(这无论如何都需要像drawAtPoint:我也成功使用了。)

我认为这不重要,但以防万一我指定这不会发生在一个View子类的drawRect:。

你很明确地说我“完全错了”。图形环境非常复杂,在iOS中很丰富,我认为现在还没有超过1%或2%的同化。

提前谢谢。

2 个答案:

答案 0 :(得分:5)

你是对的,要求是当前的图形上下文是PDF上下文。您可以推送它(UIGraphicsPushContext)使其处于活动状态,也可以像这样创建上下文:

UIGraphicsBeginPDFContextToFile(path, CGRectMake(0, 0, 612, 792), nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
// ...
UIGraphicsSetPDFContextURLForRect(url, rect);
// ... 
UIGraphicsEndPDFContext(); 

UIGraphicsSetPDFContextURLForRect有两个参数:第一个是你想要链接的URL,第二个是当前页面上代表链接区域的矩形。 例如,此行将创建指向页面左下角网址的链接,链接大小为72 * 72点:

UIGraphicsSetPDFContextURLForRect(url, CGRectMake(0, 0, 72, 72));

此方法实际上是在PDF文件中创建链接注释。链接本身没有视觉外观,您必须知道它在那里,或者如果您将鼠标移动到查看器中的PDF页面上,您可能会偶然发现它。因此,您通常在页面上绘制/写入内容(例如,单击此处),然后在文本上方设置链接区域。

更新 - 工作代码片段:

- (void) makePdf {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfFile = [documentsDirectory stringByAppendingPathComponent:@"uigraphics.pdf"];

    UIGraphicsBeginPDFContextToFile(pdfFile, CGRectMake(0, 0, 612, 792), nil);
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);

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

    UIGraphicsEndPDFContext();
}

答案 1 :(得分:4)

我希望这会对你有帮助。

UIGraphicsBeginPDFContextToFile( pdfFilePath, CGRectZero, nil );

CGRect windowFrame = CGRectMake( 0, 0, 596, 842 );
UIGraphicsBeginPDFPageWithInfo( windowFrame, nil );

NSURL *url = [NSURL URLWithString:@"http://www.google.com"];

CGRect textFrame = CGRectMake( 10, 10, 200, 20 );
CGRect linkFrame = textFrame;
linkFrame.origin.y = windowFrame.size.height - linkFrame.origin.y - linkFrame.size.height;
UIGraphicsSetPDFContextURLForRect( url, linkFrame );

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:textFrame];

UIGraphicsEndPDFContext();