Drawing a PDF Right-Side-Up in CGContext

Posted by Carter Allen on Stack Overflow See other posts from Stack Overflow or by Carter Allen
Published on 2010-03-17T02:37:34Z Indexed on 2010/03/17 2:41 UTC
Read the original article Hit count: 535

I'm overriding the drawRect: method in a custom UIView, and I'm doing some custom drawing. All was going well, until I needed to draw a PDF resource (a vector glyph, to be precise) into the context. First I retrieve the PDF from a file:

NSURL *pdfURL = [NSURL fileURLWithPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"CardKit.bundle/A.pdf"]];
CGPDFDocumentRef pdfDoc = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDoc, 1);

Then I create a box with the same dimensions as the loaded PDF:

CGRect box = CGPDFPageGetBoxRect(pdfPage, kCGPDFArtBox);

Then I save my graphics state, so that I don't screw anything up:

CGContextSaveGState(context);

And then I perform a scale+translate of the CTM, theoretically flipping the whole context:

CGContextScaleCTM(context, 1.0, -1.0);
CGContextTranslateCTM(context, 0.0, rect.size.height);

I then scale the PDF so that it fits into the view properly:

CGContextScaleCTM(context, rect.size.width/box.size.width, rect.size.height/box.size.height);

And finally, I draw the PDF and restore the graphics state:

CGContextDrawPDFPage(context, pdfPage);
CGContextRestoreGState(context);

The issue is that there is nothing visible drawn. All this code should theoretically draw the PDF glyph into the view, right?

If I remove the scale+translate used to flip the context, it draws perfectly: it just draws upside-down.

Any ideas?

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about iphone-sdk