2

NSStringテキストをPDFに描画する必要があるプロジェクトに取り組んでいます。PDF形式のテキストを単色で描くことができます。特定の文字列をPDFで検索し、別の色でマークできる検索方法を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

1 に答える 1

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

これは道順を示すためのもので、役立つ場合があります。太字とすべてに属性付きの文字列を使用しました。これが色でもうまくいくことを願っています。

ハッピーコーディング。

于 2013-03-01T07:17:50.120 に答える