Search code examples
iospdfrenderword-wrapcore-text

iOS CoreText write to PDF and word wrapping


I'm using a slight modification of code from this excellent article from rawenderlich.com to write some text to a PDF:

-(void)drawText:(NSString*)text inFrame:(CGRect)frameRect withAttributes:(NSDictionary*)attributes
{
    CFStringRef stringRef = (__bridge CFStringRef)text;

    // Prepare the text using a Core Text Framesetter
    CFDictionaryRef attributeRef = (__bridge CFDictionaryRef)attributes;

    CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, stringRef, attributeRef);
    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.
    CGFloat offset = (frameRect.origin.y*2)+frameRect.size.height;
    CGContextTranslateCTM(currentContext, 0, offset);
    CGContextScaleCTM(currentContext, 1.0, -1.0);

    // Draw the frame.
    CTFrameDraw(frameRef, currentContext);

    CGContextScaleCTM(currentContext, 1.0, -1.0);
    CGContextTranslateCTM(currentContext, 0, -offset);

    CFRelease(frameRef);
    CFRelease(framesetter);
    CFRelease(currentText);
}

This works well, but I cannot get the text to wrap when it is greater than the width of the frame. I simply get the ellipsis (...) at the end of my 'one line' of text.

This wraps when rendering to the screen so am wondering if I'm missing something for writing to pdf and flagging it to wrap. Can anyone offer suggestions?


Solution

  • Well after some research it seems that the LineBreak mode was set to TruncateTail. As the article referenced here uses a .xib file to specify the text etc., I was setting the attributed label text to Word Wrap but only from within the attributed text inspector for that label. From what I can see, this is ignored and I had to set the Line Breaks setting to Word Wrap to get the attribute change.

    enter image description here