Creating a PDF document

Discussion in 'iOS Programming' started by idelovski, Jul 3, 2009.

  1. idelovski macrumors regular

    Joined:
    Sep 11, 2008
    #1
    I am trying to create a pdf document with CGPDFContextCreateWithURL(). Everything seems ok from the code, but final pdf contains only rectangles and other graphics, but no text at all. The code is basically something like this:
    Code:
    CGContextRef  pdfContxt = CGPDFContextCreateWithURL ((CFURLRef)theUrl, &mediaBox, nil);
    
    CGContextBeginPage (pdfContxt, NULL);
    CGContextSaveGState (pdfContxt);
    
    CGContextClipToRect (pdfContxt, mediaBox);
    
    CGContextSetLineWidth (pdfContxt, 1.);
    CGContextSetFillColorWithColor (pdfContxt, [UIColor blackColor].CGColor);   // text color
    CGContextSetStrokeColorWithColor (pdfContxt, [UIColor redColor].CGColor);
    
    [@"Hello world!" drawInRect:textRect withFont:[UIFont italicSystemFontOfSize:24.] lineBreakMode:UILineBreakModeClip];
    
    CGContextAddRect (pdfContxt, textRect);
    CGContextDrawPath (pdfContxt, kCGPathStroke);
    
    CGContextRestoreGState (pdfContxt);
    CGContextEndPage (pdfContxt);
    CGContextRelease (pdfContxt);
    
    When I open the resulting pdf file, it has only the red rectangle, but no text. I am still on SDK 2.2.1.
     
  2. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    I'm guessing you need to set that context as the current one after you CGContextSaveGState. Try using UIGraphicsPushContext() and then call UIGraphicsPopContext() right before you restore the gstate.
     
  3. idelovski thread starter macrumors regular

    Joined:
    Sep 11, 2008
    #3
    Thanks. This did it.

    I have suspected something like this might be the problem, but I had trouble finding the right information. For example, I found this NSGraphicsContext Reference that says:

    "Graphics contexts are maintained on a stack. You push a graphics context onto the stack by sending it a saveGraphicsState message, and pop it off the stack by sending it a restoreGraphicsState message. By sending restoreGraphicsState to an NSGraphicsContext object you remove it from the stack, and the next graphics context on the stack becomes the current graphics context."

    But, that is describing the Mac OS Cocoa class.

    Somehow I thought CGContextSaveGState() and CGContextRestoreGState() are doing the same on the iPhone, but obviously I was wrong and I had no idea what is replacing functionality of NSGraphicsContext class on the iPhone.
     

Share This Page