Sanchit Paurush
Sanchit Paurush

Reputation: 6152

How to draw multiple colored text in PDF in iOS?

I am working on a project where I need to draw some NSString text into PDF. I am able to draw the text in PDF in single color. I want to implement search method in PDF by which I can search a particular string the PDF and mark it with different color.

Below is the code which I am using to draw single color text in PDF.

- (void) drawText
{
    CGContextRef    currentContext = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(currentContext, 0.0, 0.0, 1.0, 1.0);


    NSString *textToDraw = pdfTextView.text;



    UIFont *font = [UIFont systemFontOfSize:14.0];



    CGSize stringSize = [textToDraw sizeWithFont:font
                               constrainedToSize:CGSizeMake(pageSize.width - 2*kBorderInset-2*kMarginInset, pageSize.height - 2*kBorderInset - 2*kMarginInset)
                                   lineBreakMode:UILineBreakModeWordWrap];

    CGRect renderingRect = CGRectMake(kBorderInset + kMarginInset, kBorderInset + kMarginInset + 50.0, pageSize.width - 2*kBorderInset - 2*kMarginInset, stringSize.height);


    [textToDraw drawInRect:renderingRect
                  withFont:font
             lineBreakMode:UILineBreakModeWordWrap
                 alignment:UITextAlignmentLeft];

}

Also is it possible to retrieve text from PDF (if it only contains text)?

Please advise.

Upvotes: 2

Views: 1493

Answers (1)

DivineDesert
DivineDesert

Reputation: 6954

You need to draw attributed string and not simple string. Try this.

CGContextSetTextMatrix(pdfContext, CGAffineTransformIdentity);
CGMutablePathRef path = CGPathCreateMutable(); 
CGRect bounds = CGRectMake(x,   y, width, height); 
CGPathAddRect(path, NULL, bounds);

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];

CTFramesetterRef framesetter =  CTFramesetterCreateWithAttributedString(string);
// Create the frame and draw it into the graphics context 
CTFrameRef frame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0, 0), path, NULL);
CFRelease(framesetter); 
CTFrameDraw(frame, pdfContext); 
CGContextTranslateCTM(pdfContext, 0, pageheight);
CGContextScaleCTM(pdfContext, 1.0, -1.0);   

This is to give you directions, may be its helpful. I used attributed string for bold and all. Hope this works for colors too.

Happy coding.

Upvotes: 4

Related Questions