生成PDF时不显示NSAttributedString

时间:2014-01-14 00:38:22

标签: ios pdf nsattributedstring underline

这曾经工作过,现在,它突然停止了工作:

对于iOS 7 iPad应用程序,我使用

生成PDF
UIGraphicsBeginPDFContextToFile(pdfPathWithFileName, CGRectZero, nil);
...
UIGraphicsEndPDFContext();

在该代码块中,以下方法用于呈现带下划线的文本,但最近,它只是停止工作,并且根本不呈现传递给该方法的任何文本:

+(void)drawUnderlinedText:(NSString *)text withFont:(UIFont *)font andColor:(UIColor *)color andLocationX:(int)locationX andLocationY:(int)locationY andTextAreaWidth:(int)textWidth andTextAreaHeight:(int)textHeight{

    NSDictionary *attributesDict;
    NSMutableAttributedString *attString;

    attributesDict = @{NSForegroundColorAttributeName : color, NSFontAttributeName : font, NSUnderlineStyleAttributeName : [NSNumber numberWithInt:NSUnderlineStyleSingle]};
    attString = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDict];

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGRect rect = CGRectMake(locationX, locationY, textWidth, textHeight);
    [attString drawInRect:rect];
}

关于绘制到PDF上下文,我在网上找不到任何内容。有postsand here)提到有关标签的问题。但是在生成PDF文件时似乎没有解决我的问题...

请帮忙!

1 个答案:

答案 0 :(得分:2)

由于这是iOS中的一个错误,我决定使用here中的解决方法,只需在上下文中绘制一条线(参见代码中的注释):

+(void)drawUnderlinedText:(NSString *)text withFont:(UIFont *)font andColor:(UIColor *)color andLocationX:(int)locationX andLocationY:(int)locationY andTextAreaWidth:(int)textWidth andTextAreaHeight:(int)textHeight{

    NSDictionary *attributesDict;
    NSMutableAttributedString *attString;

    // Commented out until iOS bug is resolved:    
    //attributesDict = @{NSUnderlineStyleAttributeName : [NSNumber numberWithInt:NSUnderlineStyleSingle], NSForegroundColorAttributeName : color, NSFontAttributeName : font};
    attributesDict = @{NSForegroundColorAttributeName : color, NSFontAttributeName : font};
    attString = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDict];

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGRect rect = CGRectMake(locationX, locationY, textWidth, textHeight);

    // Temporary Solution to NSUnderlineStyleAttributeName - Bug:
    CGContextSetStrokeColorWithColor(context, color.CGColor);
    CGContextSetLineWidth(context, 1.0f);

    CGSize tmpSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(200, 9999)];

    CGContextMoveToPoint(context, locationX, locationY + tmpSize.height - 1);
    CGContextAddLineToPoint(context, locationX + tmpSize.width, locationY + tmpSize.height - 1);

    CGContextStrokePath(context);
    // End Temporary Solution

    [attString drawInRect:rect];
}