OGeek|极客世界-中国程序员成长平台

标题: ios - 将 PDF 转换为 UIImageView [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 10:09
标题: ios - 将 PDF 转换为 UIImageView

我找到了一些代码,可以从 PDF 文件中获得 UIImage。它有效,但我有两个问题:

附:我知道 UIWebView 可以显示具有某些功能的 PDF 页面,但我需要它作为 UIImage 或至少在 UIView 中。

劣质图片:

Bad quality Image

代码:

-(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;
}



Best Answer-推荐答案


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

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

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);

关于ios - 将 PDF 转换为 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8490238/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4