ChandreSh Viradia
ChandreSh Viradia

Reputation: 1

How to set font color and style for PDF using core text?

If I create a PDF using core text framework, it will not allow me to set color and font style. Is there any problem with "core text" framework?

I am using below code for setting color :

CGContextRef    currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, 1.0, 0.0, 0.0, 1.0);  //This is not working.

Upvotes: 0

Views: 1209

Answers (2)

Richard Pick
Richard Pick

Reputation: 1

You can create color object like this:

UIColor *colour = [UIColor colorWithRed:0 green:1 blue:0 alpha:0];

And fill colour:

CGContextSetFillColorWithColor(ctx, colour.CGColor);

If you are not using ARC, you need to retain and release color appropriately.

Upvotes: 0

Dhruvik
Dhruvik

Reputation: 982

Try below code, in this code i've changed my font style and size with CTFontRef

+(void)drawText:(NSString*)textToDraw inFrame:(CGRect)frameRect
{
    CFStringRef stringRef = ( CFStringRef)textToDraw;

    CGColorSpaceCreateWithName(stringRef);

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]
                                         initWithString:textToDraw];
    CTFontRef helveticaBold;
    helveticaBold = CTFontCreateWithName(CFSTR("Helvetica-Bold"), 24.0, NULL);
    [string addAttribute:(id)kCTFontAttributeName
                   value:(id)helveticaBold
                   range:NSMakeRange(0, [string length])];
    [string addAttribute:(id)kCTForegroundColorAttributeName
                   value:(id)[UIColor whiteColor].CGColor
                   range:NSMakeRange(0, [string length])];

    CTFramesetterRef framesetter =    CTFramesetterCreateWithAttributedString((CFAttributedStringRef)string);

    CGMutablePathRef framePath = CGPathCreateMutable();

    CGPathAddRect(framePath, NULL, frameRect);
    CFRange currentRange = CFRangeMake(0, 0);
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
    CGPathRelease(framePath);

    CGContextRef    currentContext = UIGraphicsGetCurrentContext();

    CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);

    CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2);

    CGContextScaleCTM(currentContext, 1.0, -1.0);

    CTFrameDraw(frameRef, currentContext);

    CGContextScaleCTM(currentContext, 1.0, -1.0);

    CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2);

    CFRelease(frameRef);
    CFRelease(string);
    CFRelease(framesetter);
}

you can follow this Link also Example

Hope this helps you, Happy Coding

Upvotes: 3

Related Questions