2013-03-01 21 views
2

我正在開發一個項目,我需要將一些NSString文本繪製到PDF中。我能夠以單一顏色繪製PDF文本。我想在PDF中實現搜索方法,通過它我可以搜索特定的字符串PDF並用不同的顏色標記它。如何在iOS中以PDF形式繪製多個彩色文本?

下面是我用來在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]; 

} 

也有可能從PDF檢索文本(如果它只包含文本)?

請指教。

回答

4

您需要繪製屬性字符串,而不是簡單的字符串。嘗試這個。

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

這是給你指示,可能對你有幫助。我用粗體和所有的屬性字符串。希望這也適用於顏色。

快樂編碼。

+1

感謝您的回覆。但我無法使用NSMutableAttributedString訪問其他字符串方法。比如我需要調用drawInRect方法,正如我在我的代碼中提到的那樣,它只被NSString調用。請諮詢 – 2013-03-01 07:48:06

+0

爲什麼要使用drawinrect? – DivineDesert 2013-03-01 08:53:16

+0

我想把多彩色的字符串放在PDF中。所以上面的方法代碼將單色NSString文本繪製爲PDF。 – 2013-03-01 09:29:13

相關問題