iOS 创建 PDF 时添加链接

标签 ios pdf hyperlink pdf-generation

我正在 iOS 中使用 UIGraphicsBeginPDFContextToFile 创建 PDF,我想在其中添加指向其他页面以及其他网站的 URL 链接。下面是代码:这里 pdfObj 是一个自定义类,它将文本绘制为 PDF。成功创建 PDF 后,如果我单击“转到第 1 章”和“转到 URL”区域,则不会发生任何情况

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

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

最佳答案

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

关于iOS 创建 PDF 时添加链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22326745/

相关文章:

在 C 中创建排序链表

ios - UIDocument & NSFileWrapper 架构和性能

ios - AsyncDisplayKit错误(使用ASDK作为静态库)

c# - Ghostscript.NET pdf 到图像在 Windows Azure 上无法工作

ruby-on-rails - 使用 Wicked_PDF 渲染为 PDF 时 ChartKick 图表不显示

javascript - 单击 A 链接并打开多个转到不同 URL 的新窗口?

ios - 在编辑模式下使用自定义 UILabels 对 UITableView 进行分组

ios - 我有 json 响应,但它是可选的,任何人都可以告诉我如何解开可选的 json

excel - 将带有内部链接的 Excel 转换为 pdf

Javascript:包含随机数的网址