Question

I am creating dynamic PDF from my application. In some cases i want my text to be write in PDF with desired color. how can i get that?

I am using CoreText.

Here is my code to draw text in my PDF,

+(void)drawText:(NSString*)textToDraw inFrame:(CGRect)frameRect
{
    frameRect.origin.y = frameRect.origin.y + frameRect.size.height; // New line
    CFStringRef stringRef = ( CFStringRef)textToDraw;
    CGColorSpaceCreateWithName(stringRef);
    CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, stringRef, NULL);
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
    CGMutablePathRef framePath = CGPathCreateMutable();
    CGPathAddRect(framePath, NULL, frameRect);
    // Get the frame that will do the rendering.
    CFRange currentRange = CFRangeMake(0, 0);
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
    CGPathRelease(framePath);
    // Get the graphics context.
    CGContextRef    currentContext = UIGraphicsGetCurrentContext();
    // Put the text matrix into a known state. This ensures
    // that no old scaling factors are left in place.
    CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
    // Core Text draws from the bottom-left corner up, so flip
    // the current transform prior to drawing.
    CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2);
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    // Draw the frame.
    CTFrameDraw(frameRef, currentContext);
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2);
    CFRelease(frameRef);
    //CFRelease(stringRef);
    CFRelease(framesetter);
}

Any help or suggestion will be appreciated., Thanks in advance.

Was it helpful?

Solution

If you are using coretext, try

CTFontRef font = CTFontCreateWithName((CFStringRef)@"Helvetica", 16.0f, nil);
CFAttributedStringSetAttribute(textString,CFRangeMake(0, strLength-1), kCTFontAttributeName, font);

You can also try CGContextSetFont

NSString *fontName = @"Helvetica";
CGFontRef fontRef = CGFontCreateWithFontName((__bridge CFStringRef)fontName);
CGContextSetFont(context, fontRef);
CGContextSetFontSize(context, 30);

See my question, you will get an idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top