#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)UIDocumentInteractionController *documentInteractionController;
@property (nonatomic ,assign) BOOL isAppear; //判断是否当前页面正在显示
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *mylabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
mylabel.text = @"床前明月光啥意思带式输送机开房记录圣诞节福利卡三等奖";
mylabel.textColor = [UIColor redColor];
mylabel.textAlignment = NSTextAlignmentCenter;
mylabel.numberOfLines = 0;
[self.view addSubview:mylabel];
}
- (UIImage*)imageWithUIView:(UIView*)view
{
UIGraphicsBeginImageContext(view.bounds.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[view.layer renderInContext:ctx];
UIImage* tImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return tImage;
}
#pragma mark - 预览pdf的代理方法
#pragma mark - UIDocumentInteractionController 代理方法
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
return self;
}
#pragma mark -点击预览窗口的“Done”(完成)按钮时调用
- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller
{
self.documentInteractionController = nil;
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
self.isAppear = NO;
if (self.documentInteractionController) {
self.documentInteractionController.delegate = nil;
}
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.isAppear = YES;
if (self.documentInteractionController) {
self.documentInteractionController.delegate = self;
}
}
- (IBAction)toXiaZaiPdfMethods:(id)sender {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
UIImage *hechengImage = [self imageWithUIView:self.view];
NSData *fileData = UIImageJPEGRepresentation(hechengImage,1.0f);//第二个参数为压缩倍数
//下载PDF的后续处理
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *Path = [paths objectAtIndex:0];
Path = [Path stringByAppendingPathComponent:@"合成图片.png"];
if (fileData != nil)
{
if ([fileData writeToFile:Path atomically:YES])
{
if (!self.isAppear) {
return;
}
if ( self.documentInteractionController == nil ){
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:Path]];
self.documentInteractionController.delegate = self;
}
else
{
self.documentInteractionController.URL = [NSURL fileURLWithPath:Path];
}
[self.documentInteractionController presentPreviewAnimated:YES];
}
else
{
NSLog(@"无法打开该类型的文件!");
}
}
else
{
NSLog(@"下载失败!");
}
});
}