Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGContext pdf page aspect fit

I am displaying a pdf page on the CGContext using the code

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
    CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0);
    CGContextFillRect(ctx, layer.bounds);
    CGContextTranslateCTM(ctx, 0.0, layer.bounds.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    CGContextConcatCTM(ctx, CGPDFPageGetDrawingTransform(myPageRef, kCGPDFBleedBox, layer.bounds, 0, true));
    CGContextDrawPDFPage(ctx, myPageRef);
}

The problem is that the pdf page is getting drawn on the center of the page leaving border on all four sides. Is there any way to make the page fit to screen.

like image 609
Anil Sivadas Avatar asked Oct 11 '10 17:10

Anil Sivadas


3 Answers

To expand on Tia's answer; the built-in method CGPDFPageGetDrawingTransform will scale down but not up. If you want to scale up then you need to work out your own transform by comparing the results of CGPDFGetBoxRect to your content area. Typing extemporaneously:

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
    CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0);
    CGContextFillRect(ctx, layer.bounds);
    CGContextTranslateCTM(ctx, 0.0, layer.bounds.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);

    CGRect cropBox = CGPDFGetBoxRect(myPageRef, kCGPDFCropBox);
    CGRect targetRect = layer.bounds;
    CGFloat xScale = targetRect.size.width / cropBox.size.width;
    CGFloat yScale = targetRect.size.height / cropBox.size.height;
    CGFloat scaleToApply = xScale < yScale ? xScale : yScale;
    CGContextConcatCTM(ctx, CGAffineTransformMakeScale(scaleToApply, scaleToApply)); 

    CGContextDrawPDFPage(ctx, myPageRef);
}

So: work out how much you'd have to scale the document by for it to occupy the entire width of the view, how much to occupy the entire height and then actually scale by the lesser of those two values.

like image 60
Tommy Avatar answered Nov 16 '22 17:11

Tommy


The CGPDFPageGetDrawingTransform just will not return scale-up transformation if the PDF page rectangle is smaller than the rect parameter.

like image 35
tia Avatar answered Nov 16 '22 17:11

tia


Cursory reading of your code suggests the use of kCGPDFBleedBox should be replaced by another setting, perhaps kCGPDFMediaBox. See here for more information.

like image 1
fbrereto Avatar answered Nov 16 '22 15:11

fbrereto