将PDF转换为UIImageView

我已经find了一些代码给我一个PDF文件的UIImage 。 它有效,但我有两个问题:

  • 是否有可能实现更好的UIImage质量? (见屏幕截图)
  • 我只看到我的UIImageView的第一页。 我是否必须在UIScrollViewembedded文件才能完成?
  • 还是只渲染一个页面并使用button浏览页面会更好?

PS我知道, UIWebView可以显示具有一些function的PDF页面,但我需要它作为UIImage或至less在UIView

Bad quality Image:

质量差的图像

Code:

 -(UIImage *)image { UIGraphicsBeginImageContext(CGSizeMake(280, 320)); CGContextRef context = UIGraphicsGetCurrentContext(); CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("ls.pdf"), NULL, NULL); CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL); CGContextTranslateCTM(context, 0.0, 320); CGContextScaleCTM(context, 1.0, -1.0); CGPDFPageRef page = CGPDFDocumentGetPage(pdf, 4); CGContextSaveGState(context); CGAffineTransform pdfTransform = CGPDFPageGetDrawingTransform(page, kCGPDFCropBox, CGRectMake(0, 0, 280, 320), 0, true); CGContextConcatCTM(context, pdfTransform); CGContextDrawPDFPage(context, page); CGContextRestoreGState(context); UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return resultingImage; } 

你用CGContextTranslateCTM(context, 0.0, 320);来做什么? 呼叫?

你应该从PDF中提取适当的度量标准,代码如下:

  cropBox = CGPDFPageGetBoxRect(page, kCGPDFCropBox); rotate = CGPDFPageGetRotationAngle(page); 

另外,如您所见,pdf可能有旋转信息,因此您需要根据angular度使用CGContextTranslateCTM/CGContextRotateCTM/CGContextScaleCTM

您也可能想要裁剪CropBox区域以外的任何内容,因为pdf具有通常不想显示的各种viewPorts (例如,打印机可以无缝打印) – >使用CGContextClip

接下来,你忘记了PDF参考定义了一个白色的背景颜色。 有很多文件没有定义任何背景颜色 – 如果你自己没有绘制白色背景 – > CGContextSetRGBFillColorCGContextFillRect你会得到奇怪的结果。

我知道我在这里有点晚,但我希望我能帮助其他人寻找答案。 至于提问的问题:

  • 恐怕获得更好的图像质量的唯一方法是呈现更大的图像,并让UIImageView为您resize。 我不认为你可以设置分辨率,但使用更大的图像可能是一个不错的select。 页面渲染不会太长,图像质量会更好。 PDF文件根据缩放级别按需提供,这就是为什么他们似乎有“更好的质量”。

  • 至于渲染所有的页面,你可以得到调用CGPDFDocumentGetNumberOfPages( pdf )的文档中的页面数,并使用一个简单的for循环,你可以连接在一个单一的图像中生成的所有图像。 为了显示它,使用UIScrollVIew

  • 在我看来,这个方法比上面的要好,但是你应该试着去优化它,例如渲染当前,上一页和下一页。 为了更好的滚动过渡效果,为什么不使用水平的UIScrollView

对于更通用的渲染代码,我总是这样做:

 int rotation = CGPDFPageGetRotationAngle(page); CGContextTranslateCTM(context, 0, imageSize.height);//moves up Height CGContextScaleCTM(context, 1.0, -1.0);//flips horizontally down CGContextRotateCTM(context, -rotation*M_PI/180);//rotates the pdf CGRect placement = CGContextGetClipBoundingBox(context);//get the flip's placement CGContextTranslateCTM(context, placement.origin.x, placement.origin.y);//moves the the correct place //do all your drawings CGContextDrawPDFPage(context, page); //undo the rotations/scaling/translations CGContextTranslateCTM(context, -placement.origin.x, -placement.origin.y); CGContextRotateCTM(context, rotation*M_PI/180); CGContextScaleCTM(context, 1.0, -1.0); CGContextTranslateCTM(context, 0, -imageSize.height); 

Steipete已经提到设置白色背景:

 CGContextSetRGBFillColor(context, 1, 1, 1, 1); CGContextFillRect(context, CGRectMake(0, 0, imageSize.width, imageSize.height)); 

所以最后要记住的是在导出图像时,将质量设置为最大。 例如:

 UIImageJPEGRepresentation(image, 1);