我找到了一些代码,它从PDF文件中提取了UIImage
。它有效,但我有两个问题:
UIImageView
中的第一页。我是否必须将文件嵌入UIScrollView
才能完成? P.S。我知道UIWebView
可以显示包含某些功能的PDF页面,但我需要它作为UIImage
或至少在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;
}
答案 0 :(得分:2)
我知道我有点晚了,但我希望我可以帮助别人寻找答案。 至于提出的问题:
我担心获得更好图像质量的唯一方法是渲染更大的图像,并让UIImageView
为您调整大小。我不认为你可以设置分辨率,但使用更大的图像可能是一个不错的选择。页面渲染不会花费太长时间,图像质量会更好。 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);
答案 1 :(得分:1)
您在CGContextTranslateCTM(context, 0.0, 320);
电话中做了什么?
您应该从pdf中提取适当的指标,代码如下:
cropBox = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
rotate = CGPDFPageGetRotationAngle(page);
另外,正如您所见,pdf可能有旋转信息,因此您需要根据角度使用CGContextTranslateCTM/CGContextRotateCTM/CGContextScaleCTM
。
您还可能想要剪切CropBox
区域之外的任何内容,因为pdf具有您通常不想显示的各种viewPorts
(例如,对于打印机而言,可以进行无缝打印) - >使用CGContextClip
。
接下来,您忘记了pdf参考定义了白色背景颜色。有很多文档根本没有定义任何背景颜色 - 如果你不自己绘制白色背景,你会得到奇怪的结果 - > CGContextSetRGBFillColor
& CGContextFillRect
。