Poor quality of CFGPDF rendered in bitmap context

373 views Asked by At

Is there a way to render a PDF page into bitmap context without losing quality?

Here is my code:

-(UIImage *)imageForPage:(int)pageNumber sized:(CGSize)size{

    CGPDFDocumentRef _document  = [self CreatePDFDocumentRef:filePath];
    CGPDFPageRef page = CGPDFDocumentGetPage (_document, pageNumber);


    CGRect pageRect = CGPDFPageGetBoxRect(page,kCGPDFTrimBox);
    CGSize pageSize = pageRect.size;
    pageSize = MEDSizeScaleAspectFit(pageSize, size);

    UIGraphicsBeginImageContextWithOptions(pageSize, NO, 0.0);

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGContextSetRenderingIntent(context, kCGRenderingIntentDefault);

    CGContextTranslateCTM(context, 0.0, pageSize.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSaveGState(context);

    CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFTrimBox, CGRectMake(0, 0, pageSize.width, pageSize.height), 0, true);
    CGContextConcatCTM(context, pdfTransform);
    CGContextDrawPDFPage(context, page);
    CGContextRestoreGState(context);

    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGPDFDocumentRelease (_document);
    return resultingImage;
}


CGSize MEDSizeScaleAspectFit(CGSize size, CGSize maxSize) {
    CGFloat originalAspectRatio = size.width / size.height;
    CGFloat maxAspectRatio = maxSize.width / maxSize.height;
    CGSize newSize = maxSize;
    // The largest dimension will be the `maxSize`, and then we need to scale
    // the other dimension down relative to it, while maintaining the aspect
    // ratio.
    if (originalAspectRatio > maxAspectRatio) {
        newSize.height = maxSize.width / originalAspectRatio;
    } else {
        newSize.width = maxSize.height * originalAspectRatio;
    }

    return newSize;
}

Rendered Page

1

There are 1 answers

0
Putz1103 On BEST ANSWER

Make sure the image you are creating is as close to equal to the size it will be displayed. That will create an image that is the most visually accurate to display.