문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top