PDFViewController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. //
  2. // PDFViewController.m
  3. // RedAnt ERP Mobile
  4. //
  5. // Created by Ray on 14-8-7.
  6. // Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "PDFViewController.h"
  9. #import "RAUtils.h"
  10. #import "const.h"
  11. @interface PDFViewController ()
  12. @end
  13. @implementation PDFViewController
  14. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  15. {
  16. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  17. if (self) {
  18. // Custom initialization
  19. }
  20. return self;
  21. }
  22. - (void)viewDidLoad
  23. {
  24. [super viewDidLoad];
  25. // Do any additional setup after loading the view.
  26. UIRefreshControl *ref = [[UIRefreshControl alloc]init];
  27. ref.tag = 200 ;
  28. ref.attributedTitle = [[NSAttributedString alloc]initWithString:@"drag to refresh"];
  29. ref.tintColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7];
  30. // ref.hidden = true;
  31. [ref addTarget:self action:@selector(changeCell) forControlEvents:UIControlEventValueChanged];
  32. [self.webView.scrollView addSubview:ref];
  33. self.webView.dataDetectorTypes=UIDataDetectorTypeAll;
  34. UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
  35. style:UIBarButtonItemStylePlain
  36. target:self
  37. action:@selector( onBackClick:)];
  38. //[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Close", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onCloseClick:)];
  39. // closeButton.title = @"Close";
  40. self.navigationItem.leftBarButtonItem = closeButton;
  41. self.btnshare = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"share"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  42. style:UIBarButtonItemStylePlain
  43. target:self
  44. action:@selector(onActionClick:)];//[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Edit", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onOpenOrderClick:)];
  45. self.btnshare.tintColor = UIColorFromRGB(0x996633);
  46. self.btnemail =[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"mail"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  47. style:UIBarButtonItemStylePlain
  48. target:self
  49. action:@selector(onEmailClick:)];// [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Commit", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onCommitOrderClick:)];
  50. self.btnemail.tintColor = UIColorFromRGB(0x996633);
  51. // self.btnSend = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Email", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onSendMailClick:)];
  52. self.btnsave = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"save"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  53. style:UIBarButtonItemStylePlain
  54. target:self
  55. action:@selector(onSaveClick:)];
  56. self.btnsave.tintColor = UIColorFromRGB(0x996633);
  57. UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
  58. fixedItem.width = 20.0f;
  59. NSMutableArray * items = [[NSMutableArray alloc]init];
  60. [items addObject:self.btnshare];
  61. [items addObject:fixedItem];
  62. [items addObject:self.btnemail];
  63. if(self.canSave)
  64. {
  65. [items addObject:fixedItem];
  66. [items addObject:self.btnsave];
  67. }
  68. self.navigationItem.rightBarButtonItems=items;
  69. self.btnshare.enabled =false;
  70. self.btnemail.enabled =false;
  71. self.btnsave.enabled =false;
  72. // self.url=@"http://192.168.1.3:8080/npd/test.pdf";
  73. // NSURL* url = [NSURL URLWithString:self.url];
  74. //
  75. // NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:2000];
  76. //
  77. //
  78. // [self.webView loadRequest:request];
  79. [self loadcontent];
  80. }
  81. - (void)onBackClick:(UIButton *)sender {
  82. [self.navigationController popViewControllerAnimated:FALSE];
  83. }
  84. -(void)ReloadData
  85. {
  86. // Count ++ ;
  87. // [mytabelview reloadData];
  88. UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
  89. [reF endRefreshing];
  90. [self loadcontent];
  91. }
  92. -(void) loadcontent
  93. {
  94. self.mum.hidden=false;
  95. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  96. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60*5];
  97. //设置请求方式为get
  98. [request setHTTPMethod:@"GET"];
  99. //添加用户会话id
  100. [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
  101. //连接发送请求
  102. NSHTTPURLResponse* urlResponse = nil;
  103. NSError *error = [[NSError alloc] init];
  104. self.content= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  105. self.filename = [urlResponse suggestedFilename];
  106. dispatch_async(dispatch_get_main_queue(), ^{
  107. self.navigationItem.title = self.save_name;
  108. UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
  109. // self.content=nil;
  110. if(self.content!=nil&&self.content.length>0)
  111. {
  112. [reF removeFromSuperview];
  113. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  114. NSString *path = NSTemporaryDirectory();
  115. NSString *filePath = [path stringByAppendingPathComponent:self.filename];
  116. // NSError *error = [[NSError alloc] init];
  117. // BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
  118. // NSAssert(bo,@"创建目录失败");
  119. [self.content writeToFile:filePath atomically:YES];
  120. self.btnshare.enabled =true;
  121. self.btnemail.enabled =true;
  122. self.btnsave.enabled =true;
  123. if(self.onLoadSuccess)
  124. self.onLoadSuccess(self.url);
  125. // int a=0;
  126. }
  127. else
  128. {
  129. [RAUtils message_alert:nil title:@"Open PDF Failed" controller:self];
  130. // self.content = [self.url dataUsingEncoding:NSUTF8StringEncoding];
  131. }
  132. ;
  133. // NSLog(@"%@",[[NSString alloc] initWithData:self.content encoding:NSASCIIStringEncoding]);
  134. //
  135. [self.webView loadData:self.content MIMEType:urlResponse.MIMEType textEncodingName:nil baseURL:nil];
  136. });
  137. });
  138. }
  139. -(void)changeCell
  140. {
  141. UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
  142. reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"refreshing"];
  143. if ([self respondsToSelector:@selector(ReloadData)])
  144. [self performSelector:@selector(ReloadData) withObject:nil afterDelay:1];
  145. // DebugLog(@"refresh!!!!!!!!");
  146. }
  147. - (void)didReceiveMemoryWarning
  148. {
  149. [super didReceiveMemoryWarning];
  150. // Dispose of any resources that can be recreated.
  151. }
  152. - (IBAction)onActionClick:(id)sender {
  153. //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  154. NSString *path = NSTemporaryDirectory();
  155. NSString* filename =self.filename;
  156. NSString *filePath = [path stringByAppendingPathComponent:filename];
  157. [self openFile:filePath];
  158. }
  159. - (IBAction)onSaveClick:(id)sender {
  160. //UIAlertControllerStyle两种类型UIAlertControllerStyleAlert类似UIAlertView
  161. //UIAlertControllerStyleActionSheet类似UIActionSheet
  162. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Save pdf" message:nil preferredStyle:UIAlertControllerStyleAlert];
  163. //block代码块取代了delegate
  164. [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  165. textField.text = self.save_name;
  166. }];
  167. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  168. UITextField *name = alertControl.textFields.firstObject;
  169. if(name.text.length==0)
  170. {
  171. [RAUtils message_alert:@"Cannot save without name. Save canceled." title:@"Name is missing" controller:self];
  172. }
  173. else
  174. {
  175. self.save_name = name.text;
  176. self.btnsave.enabled =false;
  177. // NSMutableDictionary * info =
  178. if(self.onSavePDF)
  179. self.onSavePDF(self.save_name,self.filename);
  180. }
  181. }];
  182. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  183. NSLog(@"Cancel");
  184. }];
  185. [alertControl addAction:actionOne];
  186. [alertControl addAction:alertthree];
  187. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  188. [self presentViewController:alertControl animated:YES completion:nil];
  189. }
  190. - (IBAction)onEmailClick:(id)sender {
  191. //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  192. NSString *path = NSTemporaryDirectory();
  193. NSString* filename =self.filename;
  194. NSString *filePath = [path stringByAppendingPathComponent:filename];
  195. MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
  196. mc.mailComposeDelegate = self;
  197. [mc setSubject:self.mail_subject];
  198. [mc setToRecipients:self.mail_to];
  199. if(self.mail_content==nil)
  200. self.mail_content=@"";
  201. NSString* htmlbody = [NSString stringWithFormat:@"<html><p>%@</p></html>",self.mail_content];
  202. [mc setMessageBody:htmlbody
  203. isHTML:YES];
  204. NSData *data = [NSData dataWithContentsOfFile:filePath];
  205. if(self.attachment_name.length>0)
  206. filename = self.attachment_name;
  207. [mc addAttachmentData:data mimeType:@"application/pdf" fileName:filename];
  208. [self presentModalViewController:mc animated:YES];
  209. return;
  210. }
  211. -(void)openFile: (NSString *) file_url {
  212. NSURL *file_URL = [NSURL fileURLWithPath:file_url];
  213. if (file_URL != nil) {
  214. if (self.fileInteractionController == nil) {
  215. //_fileInteractionController = [[UIDocumentInteractionController alloc] init];
  216. _fileInteractionController = [UIDocumentInteractionController interactionControllerWithURL:file_URL];
  217. _fileInteractionController.delegate = self;
  218. // [_fileInteractionController retain];//不适用ARC,记得RETAIN 使用ARC注释这一行
  219. }
  220. else
  221. {
  222. self.fileInteractionController.URL = file_URL;
  223. }
  224. // [self.fileInteractionController presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
  225. [self.fileInteractionController setName:self.mail_subject];
  226. // [self.fileInteractionController setAnnotation:<#(id _Nullable)#>;
  227. [self.fileInteractionController presentOptionsMenuFromBarButtonItem:self.btnshare animated:YES];
  228. // [self.fileInteractionController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  229. // [self.fileInteractionController presentPreviewAnimated:YES];
  230. }
  231. }
  232. - (void) sendEmail:(NSString *)to cc:(NSString*)cc subject:(NSString*)subject body:(NSString*)body
  233. {
  234. NSString* str = [NSString stringWithFormat:@"mailto:%@?cc=%@&subject=%@&body=%@",
  235. to, cc, subject, body];
  236. str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  237. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
  238. }
  239. #pragma mark methods for the UIDocumentInteractionControllerDelegate
  240. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  241. {
  242. // if (controller == self.fileInteractionController) {
  243. // self.fileInteractionController = nil;
  244. // }
  245. }
  246. - (void)previewDocumentWithURL:(NSURL*)url
  247. {
  248. UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:url];
  249. preview.delegate = self;
  250. [preview presentPreviewAnimated:YES];
  251. }
  252. - (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller
  253. {
  254. }
  255. - (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
  256. return self;
  257. }
  258. - (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
  259. return self.view.frame;
  260. }
  261. - (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
  262. return self.view;
  263. }
  264. - (void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(nullable NSString *)application // bundle ID
  265. {
  266. }
  267. #pragma mark - web view delegate
  268. - (void)webViewDidFinishLoad:(UIWebView *)webView
  269. {
  270. self.mum.hidden=true;
  271. }
  272. #pragma mark -MFMailComposeViewControllerDelegate delegate
  273. - (void)mailComposeController:(MFMailComposeViewController*)controller
  274. didFinishWithResult:(MFMailComposeResult)result
  275. error:(NSError*)error {
  276. switch (result)
  277. {
  278. case MFMailComposeResultCancelled:
  279. NSLog(@"Mail send canceled...");
  280. break;
  281. case MFMailComposeResultSaved:
  282. NSLog(@"Mail saved...");
  283. break;
  284. case MFMailComposeResultSent:
  285. NSLog(@"Mail sent...");
  286. break;
  287. case MFMailComposeResultFailed:
  288. NSLog(@"Mail send errored: %@...", [error localizedDescription]);
  289. break;
  290. default:
  291. break;
  292. }
  293. [self dismissModalViewControllerAnimated:YES];
  294. }
  295. /*
  296. #pragma mark - Navigation
  297. // In a storyboard-based application, you will often want to do a little preparation before navigation
  298. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  299. {
  300. // Get the new view controller using [segue destinationViewController].
  301. // Pass the selected object to the new view controller.
  302. }
  303. */
  304. @end