0

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

Janusz Chudzynski
  • 2,700
  • 3
  • 33
  • 46
  • 3
    What is the size you are passing into this function and what is the size you are displaying it on screen? Those are the two biggest factors in image clarity that I have found (if you are expecting better image quality than you have). – Putz1103 Jan 07 '14 at 20:06
  • Following on from Putz1103, if you could comment on what you think is wrong with the image quality then that'd be helpful. How could what you've posted as an example be improved? – Tommy Jan 07 '14 at 20:12
  • Regarding the quality, text is blurry comparing to the original pdf file. Regarding the size, I changed the size of generated image to fit exactly its destination (1024 x 600) and I can see major improvement. It looks great now. – Janusz Chudzynski Jan 07 '14 at 20:18

1 Answers1

0

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.

Putz1103
  • 6,211
  • 1
  • 18
  • 25