3

This is ipad magazine application. We need to read PDF and convert to PNG image for thumnail. After reading PDF before conversion, which is calling CGContextDrawPDFPage, the memory goes up quickly and never free up till crash. I tried in many ways but it does not work. I really appreciate if anyone could help.

CGContextDrawPDFPage(context, aPage); //this is the memory killer

The following is the complete code:

-(UIImage *)image :(CGPDFPageRef)aPage rect:(CGRect)aRect { CGRect pdfcropBox = CGRectIntegral(CGPDFPageGetBoxRect(aPage, kCGPDFCropBox));

if ((float)pdfcropBox.size.width/(float)pdfcropBox.size.height > 
    (float)aRect.size.width/(float)aRect.size.height) //pdf width too big
{
    aRect.size.height = aRect.size.width * pdfcropBox.size.height / pdfcropBox.size.width;
}
//CGRect pdfcropBox = aRect;    

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,aRect.size.width,
                                             aRect.size.height,
                                             8,
                                             (int)aRect.size.width * 4,
                                             colorSpace, 
                                             kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

CGColorSpaceRelease(colorSpace);
colorSpace = nil;

CGPDFPageRetain(aPage);
CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(aPage,
                                                              kCGPDFCropBox,
                                                              CGRectMake(0, 0, aRect.size.width,aRect.size.height),
                                                              0, true);
CGContextSaveGState(context);
CGContextConcatCTM(context, pdfTransform);
CGContextDrawPDFPage(context, aPage);
CGPDFPageRelease (aPage);
aPage = nil;
CGContextRestoreGState(context);    
CGImageRef image = CGBitmapContextCreateImage(context);
UIImage *resultingImage =  [UIImage imageWithCGImage:image];
CGContextClearRect(context, aRect);
CGContextClearRect(context, pdfcropBox);

CGContextRelease(context);
CGImageRelease(image);
context = nil; 

NSLog(@"colorSpace :%d,aPage :%d,context :%d",[colorSpace retainCount],[aPage retainCount],[context retainCount]);
return resultingImage;

}

1 Answer 1

5

You need to release and re open the CGPDFDocument as explained here Fast and Lean PDF Viewer for iPhone / iPad / iOs - tips and hints?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.