title: High quality UIImage from PDF
body: <p>I'm converting a PDF page into a UIImage. While doing so, I lose the image quality. Need help in getting high quality images.</p>
  
  <p><strong>Code to generate UIImage</strong></p>
  
  <pre><code>-(UIImage *)imageForPage:(int)pageNumber {
      CGPDFPageRef pdfPageRef = [self pdfReferenceForPage:pageNumber];
  
      CGSize pageSize = [self sizeOfPage:pageNumber];
  
      //UIGraphicsBeginImageContext(pageSize);
  
      UIGraphicsBeginImageContextWithOptions(pageSize, NO, 0.0);
  
      CGContextRef context = UIGraphicsGetCurrentContext();
      CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
  
      CGContextTranslateCTM(context, 0.0, pageSize.height);
      CGContextScaleCTM(context, 1.0, -1.0);
      CGContextSaveGState(context);
  
      CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(pdfPageRef, kCGPDFCropBox, CGRectMake(0, 0, pageSize.width, pageSize.height), 0, true);
      CGContextConcatCTM(context, pdfTransform);
  
      CGContextDrawPDFPage(context, pdfPageRef);
      CGContextRestoreGState(context);
  
      UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
  
      return resultingImage;
  }
  
  
  - (void)saveImage {
         UIImage *image = [self imageForPage:1];
         [UIImageJPEGRepresentation(image, 1.0) writeToFile:filePath atomically:YES];
  }
  </code></pre>
  
  <p><strong>Image comparison</strong></p>
  
  <p><em>Original PDF</em>
  <img src="https://i.stack.imgur.com/M6N3v.png" alt="Original PDF"></p>
  
  <hr>
  
  <p><em>Image from PDF</em>
  <img src="https://i.stack.imgur.com/XE9aG.png" alt="Image from PDF"></p>
  
  <h2>----------</h2>
  
  <p><strong>EDIT: CODE WITH CHANGES</strong></p>
  
  <pre><code>float dpi = 100.0 / 72.0;
  
  CGPDFPageRef pdfPageRef = [self pdfReferenceForPage:pageNumber];
  
  CGSize pageSize = [self sizeOfPage:pageNumber];
  pageSize.width = pageSize.width * dpi;
  pageSize.height = pageSize.height * dpi;
  
  UIGraphicsBeginImageContext(pageSize);
  
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
  CGContextTranslateCTM(context, 0.0, pageSize.height);
  CGContextScaleCTM(context, dpi, -dpi);
  CGContextSaveGState(context);
  //CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(pdfPageRef, kCGPDFCropBox, CGRectMake(0, 0, pageSize.width, pageSize.height), 0, true);
  //CGContextConcatCTM(context, pdfTransform);
  CGContextDrawPDFPage(context, pdfPageRef);
  CGContextRestoreGState(context);
  
  UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  
  return resultingImage;
  </code></pre>