iPhone: CGPDFPageRef & CGPDFPageRelease memory leak and cryptic error message

Posted by carloe on Stack Overflow See other posts from Stack Overflow or by carloe
Published on 2010-04-06T21:51:14Z Indexed on 2010/04/06 21:53 UTC
Read the original article Hit count: 896

Could someone tell me why the code below outputs "missing or invalid MediaBox" in the console? The code works fine if I remove CGPDFPageRelease(page);, but then my app starts leaking like crazy.

-(CGSize)dimensionOfPageAtIndex:(int)index {
 CGPDFPageRef page = CGPDFDocumentGetPage(pdf, index);
 CGRect tempRect = CGPDFPageGetBoxRect(page, kCGPDFBleedBox);
 CGSize tempSize = CGSizeMake(tempRect.size.width, tempRect.size.height);
 CGPDFPageRelease(page);
 return tempSize;
}

I also have this code in my app, and releasing the pageref here works just fine...

-(UIImage *)pageAtIndex:(NSInteger)pageNumber withWidth:(CGFloat)width andHeight:(CGFloat)height {
 if((pageNumber>0) && (pageNumber<=pageCount)) {
  CGFloat scaleRatio; // multiplier by which the PDF Page will be scaled

  UIGraphicsBeginImageContext(CGSizeMake(width, height)); 
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGPDFPageRef page = CGPDFDocumentGetPage(pdf, pageNumber);
  CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFBleedBox);

  //Figure out the orientation of the PDF page and set the scaleRatio accordingly
  if(pageRect.size.width/pageRect.size.height < 1.0) {
   scaleRatio = height/pageRect.size.height;
  } 
  else {
   scaleRatio = width/pageRect.size.width;  
  }

  //Calculate the offset to center the image
  CGFloat xOffset = 0.0;
  CGFloat yOffset = height;
  if(pageRect.size.width*scaleRatio<width) {
   xOffset = (width/2)-(pageRect.size.width*scaleRatio/2);
  }
  else {
   yOffset = height-((height/2)-(pageRect.size.height*scaleRatio/2)); 
  }
  CGContextTranslateCTM(context, xOffset, yOffset);
  CGContextScaleCTM(context, 1.0, -1.0);
  CGContextSaveGState(context);
  CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFBleedBox, CGRectMake(0, 0, pageRect.size.width, pageRect.size.height), 0, true);
  pdfTransform = CGAffineTransformScale(pdfTransform, scaleRatio, scaleRatio);

  CGContextConcatCTM(context, pdfTransform);
  CGContextDrawPDFPage(context, page);
  CGContextRestoreGState(context);
  UIImage *tempImage = UIGraphicsGetImageFromCurrentImageContext();

  CGContextRelease(context);
  CGPDFPageRelease(page);

  return tempImage;
 }
 return NO;
}

© Stack Overflow or respective owner

Related posts about iphone

Related posts about cgpdfcontext