views:

452

answers:

1

I have a PDF file that I want to draw in outline form. I want to draw the first several pages on the document each in their own UIImage to use on a button so that when clicked, the main display will navigate to the clicked page.

However, CGContextDrawPDFPage seems to be using copious amounts of memory when attempting to draw the page. Even though the image is only supposed to be around 100px tall, the application crashes while drawing one page in particular, which according to Instruments, allocates about 13 MB of memory just for the one page.

Here's the code for drawing:

//Note: This is always called in a background thread, but the autorelease pool is setup elsewhere
+ (void) drawPage:(CGPDFPageRef)m_page inRect:(CGRect)rect inContext:(CGContextRef) g { 
    CGPDFBox box = kCGPDFMediaBox;
    CGAffineTransform t = CGPDFPageGetDrawingTransform(m_page, box, rect, 0,YES);
    CGRect pageRect = CGPDFPageGetBoxRect(m_page, box);

    //Start the drawing
    CGContextSaveGState(g);

    //Clip to our bounding box
    CGContextClipToRect(g, pageRect);   

    //Now we have to flip the origin to top-left instead of bottom left
    //First: flip y-axix
    CGContextScaleCTM(g, 1, -1);
    //Second: move origin
    CGContextTranslateCTM(g, 0, -rect.size.height);

    //Now apply the transform to draw the page within the rect
    CGContextConcatCTM(g, t);

    //Finally, draw the page
    //The important bit.  Commenting out the following line "fixes" the crashing issue.
    CGContextDrawPDFPage(g, m_page);

    CGContextRestoreGState(g);
}

Is there a better way to draw this image that doesn't take up huge amounts of memory?

A: 

Take a look at my code for a PDF image slicer on github:

http://github.com/luciuskwok/Maps-Slicer

There should be enough memory on the device that a 13 MB allocation isn't going to kill the app. Are you draining the autorelease pool each time you render a PDF? You might also want to cache the rendering into a UIImage so that it doesn't have to render it every time it's displayed.

lucius
Well, the problem isn't going to be fixed by chaching the result, since it crashes when trying to draw the very first image. And considering that drawing the image isn't the only thing happening at the time (it is also using a UIWebView to display the full PDF file), 13 MB may simply be too much.
Ed Marty
Hi Ed Marty,Did you get any solution for your problem.I am also facing the same issue.if you found any sol please share with me.Thank you
chaitanya