I am trying to capture images from PDF and display them in my iPad application in a UIScrollView. App render the images to fullscreen (full size) when pdf page size is 1024 x 768 (standard 4:3 aspect ratio). But when the pdf page is of size 720 x 540 (same 4:3 aspect ratio but with less dimensions) I am seeing white border around the image. Below is the code snippet that i tried to capture the images.
CGPDFPageRef thePDFPageRef = CGPDFDocumentGetPage(pdfDocRef, pdfIterator);
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB(); // RGB color space
CGBitmapInfo bmi = (kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);
thumbnailWidth = 1024;
thumbnailHeight = 768;
CGContextRef context = CGBitmapContextCreate(NULL, thumbnailWidth, thumbnailHeight, 8, 0, rgb, bmi);
if (context != NULL) // Must have a valid custom CGBitmap context to draw into
{
CGRect thumbRect = CGRectMake(0.0f, 0.0f, thumbnailWidth, thumbnailHeight); // Target thumb rect
CGContextSetRGBFillColor(context, 1.0f, 1.0f, 1.0f, 1.0f);
CGContextFillRect(context, thumbRect); // White fill
CGContextConcatCTM(context, CGPDFPageGetDrawingTransform(thePDFPageRef, kCGPDFCropBox, thumbRect, 0, true)); // Fit rect
CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGContextDrawPDFPage(context, thePDFPageRef); // Render the PDF page into the custom CGBitmap context
imageRef = CGBitmapContextCreateImage(context); // Create CGImage from custom CGBitmap context
CGContextRelease(context); // Release custom CGBitmap context reference
}
CGColorSpaceRelease(rgb); // Release device RGB color space reference
CGPDFPageRelease(thePDFPageRef);
}
UIImage *image = [UIImage imageWithCGImage:imageRef scale:scale orientation:0];
How can I auto scale to full screen even when pdf page size is smaller?
I found the solution as below with scaling to rectangle.
(1) Get PDF page rectangle using
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
(2) Do scale the rectangle and apply transform to Identity Matrix
CGAffineTransform trans = CGAffineTransformIdentity;
trans = CGAffineTransformTranslate(trans, 0, pageRect.size.height);
trans = CGAffineTransformScale(trans, 1.0, -1.0);
rect = CGRectApplyAffineTransform(rect, trans);
(3) Use kCGPDFMediaBox instead of kCGPDFCropBox to avoid cropping of pdfs when size is different than standard.