关闭

iPhone开发之将pdf以图片形式显示

622人阅读 评论(0) 收藏 举报

当iPhone程序请求服务器并动态显示pdf的时候,如果需要将pdf首页设为此pdf的封面,则以图片形式显示pdf首页是一个不错的选择。

核心代码如下:

- (void)viewDidLoad {
	NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"test.pdf"];
	CFStringRef path = CFStringCreateWithCString(NULL, [filePath UTF8String], kCFStringEncodingUTF8);
	CFURLRef url = CFURLCreateWithFileSystemPath(NULL, path, kCFURLPOSIXPathStyle, NO);
	CFRelease(path);
	CGPDFDocumentRef myDocumentRef=CGPDFDocumentCreateWithURL(url);
	myPageRef=CGPDFDocumentGetPage(myDocumentRef, 1);
	CGRect pageRect = CGRectIntegral(CGPDFPageGetBoxRect(myPageRef, kCGPDFCropBox));
	CATiledLayer *tiledLayer = [CATiledLayer layer];
	tiledLayer.delegate = self;
	tiledLayer.tileSize = CGSizeMake(320.0, 460.0);
	tiledLayer.frame = pageRect;
	UIView *tempview = [[UIView alloc] init];
	[tempview setFrame:pageRect];
	[tempview.layer addSublayer:tiledLayer];
	[self.imgview setImage:[self imageFromView:tempview]];
	[tempview release];
    [super viewDidLoad];
}

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx{
    CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0);
    CGContextFillRect(ctx, CGContextGetClipBoundingBox(ctx));
    CGContextTranslateCTM(ctx, 0.0, layer.bounds.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    CGContextConcatCTM(ctx, CGPDFPageGetDrawingTransform(myPageRef, kCGPDFCropBox, layer.bounds, 0, true));
    CGContextDrawPDFPage(ctx, myPageRef);
}

- (UIImage*)imageFromView:(UIView*)view{
	UIGraphicsBeginImageContext([view bounds].size);
	BOOL hidden = [view isHidden];
	[view setHidden:NO];
	[view.layer renderInContext:UIGraphicsGetCurrentContext()];
	UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	[view setHidden:hidden];
	return image;
}



点击打开链接 demo地址


http://download.csdn.net/detail/ydj213/4163636


本站原创,转载请标明:来自追梦博客(http://www.wuleilei.com/)

本文地址:http://www.wuleilei.com/Blog/240


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:364575次
    • 积分:4653
    • 等级:
    • 排名:第6278名
    • 原创:52篇
    • 转载:277篇
    • 译文:2篇
    • 评论:32条