PDFViewController.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Loading..."];
  95. self.mum.hidden=false;
  96. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  97. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60*5];
  98. //设置请求方式为get
  99. [request setHTTPMethod:@"GET"];
  100. //添加用户会话id
  101. [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
  102. //连接发送请求
  103. NSHTTPURLResponse* urlResponse = nil;
  104. NSError *error = [[NSError alloc] init];
  105. self.content= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  106. self.filename = [urlResponse suggestedFilename];
  107. dispatch_async(dispatch_get_main_queue(), ^{
  108. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  109. self.navigationItem.title = self.save_name;
  110. UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
  111. // self.content=nil;
  112. if(self.content!=nil&&self.content.length>0)
  113. {
  114. [reF removeFromSuperview];
  115. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  116. NSString *path = NSTemporaryDirectory();
  117. NSString *filePath = [path stringByAppendingPathComponent:self.filename];
  118. // NSError *error = [[NSError alloc] init];
  119. // BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
  120. // NSAssert(bo,@"创建目录失败");
  121. [self.content writeToFile:filePath atomically:YES];
  122. self.btnshare.enabled =true;
  123. self.btnemail.enabled =true;
  124. self.btnsave.enabled =true;
  125. if(self.onLoadSuccess)
  126. self.onLoadSuccess(self.url);
  127. // int a=0;
  128. }
  129. else
  130. {
  131. [RAUtils message_alert:nil title:@"Open PDF Failed" controller:self];
  132. // self.content = [self.url dataUsingEncoding:NSUTF8StringEncoding];
  133. }
  134. ;
  135. // NSLog(@"%@",[[NSString alloc] initWithData:self.content encoding:NSASCIIStringEncoding]);
  136. //
  137. [self.webView loadData:self.content MIMEType:urlResponse.MIMEType textEncodingName:nil baseURL:nil];
  138. });
  139. });
  140. }
  141. -(void)changeCell
  142. {
  143. UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
  144. reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"refreshing"];
  145. if ([self respondsToSelector:@selector(ReloadData)])
  146. [self performSelector:@selector(ReloadData) withObject:nil afterDelay:1];
  147. // DebugLog(@"refresh!!!!!!!!");
  148. }
  149. - (void)didReceiveMemoryWarning
  150. {
  151. [super didReceiveMemoryWarning];
  152. // Dispose of any resources that can be recreated.
  153. }
  154. - (IBAction)onActionClick:(id)sender {
  155. //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  156. NSString *path = NSTemporaryDirectory();
  157. NSString* filename =self.filename;
  158. NSString *filePath = [path stringByAppendingPathComponent:filename];
  159. [self openFile:filePath];
  160. }
  161. - (IBAction)onSaveClick:(id)sender {
  162. //UIAlertControllerStyle两种类型UIAlertControllerStyleAlert类似UIAlertView
  163. //UIAlertControllerStyleActionSheet类似UIActionSheet
  164. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Save pdf" message:nil preferredStyle:UIAlertControllerStyleAlert];
  165. //block代码块取代了delegate
  166. [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  167. textField.text = self.save_name;
  168. }];
  169. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  170. UITextField *name = alertControl.textFields.firstObject;
  171. if(name.text.length==0)
  172. {
  173. [RAUtils message_alert:@"Cannot save without name. Save canceled." title:@"Name is missing" controller:self];
  174. }
  175. else
  176. {
  177. self.save_name = name.text;
  178. self.btnsave.enabled =false;
  179. // NSMutableDictionary * info =
  180. if(self.onSavePDF)
  181. self.onSavePDF(self.save_name,self.filename);
  182. }
  183. }];
  184. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  185. NSLog(@"Cancel");
  186. }];
  187. [alertControl addAction:actionOne];
  188. [alertControl addAction:alertthree];
  189. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  190. [self presentViewController:alertControl animated:YES completion:nil];
  191. }
  192. - (IBAction)onEmailClick:(id)sender {
  193. //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  194. NSString *path = NSTemporaryDirectory();
  195. NSString* filename =self.filename;
  196. NSString *filePath = [path stringByAppendingPathComponent:filename];
  197. MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
  198. mc.mailComposeDelegate = self;
  199. [mc setSubject:self.mail_subject];
  200. [mc setToRecipients:self.mail_to];
  201. if(self.mail_content==nil)
  202. self.mail_content=@"";
  203. NSString* htmlbody = [NSString stringWithFormat:@"<html><p>%@</p></html>",self.mail_content];
  204. [mc setMessageBody:htmlbody
  205. isHTML:YES];
  206. NSData *data = [NSData dataWithContentsOfFile:filePath];
  207. if(self.attachment_name.length>0)
  208. filename = self.attachment_name;
  209. [mc addAttachmentData:data mimeType:@"application/pdf" fileName:filename];
  210. [self presentModalViewController:mc animated:YES];
  211. return;
  212. }
  213. -(void)openFile: (NSString *) file_url {
  214. NSURL *file_URL = [NSURL fileURLWithPath:file_url];
  215. if (file_URL != nil) {
  216. if (self.fileInteractionController == nil) {
  217. //_fileInteractionController = [[UIDocumentInteractionController alloc] init];
  218. _fileInteractionController = [UIDocumentInteractionController interactionControllerWithURL:file_URL];
  219. _fileInteractionController.delegate = self;
  220. // [_fileInteractionController retain];//不适用ARC,记得RETAIN 使用ARC注释这一行
  221. }
  222. else
  223. {
  224. self.fileInteractionController.URL = file_URL;
  225. }
  226. // [self.fileInteractionController presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
  227. [self.fileInteractionController setName:self.mail_subject];
  228. // [self.fileInteractionController setAnnotation:<#(id _Nullable)#>;
  229. [self.fileInteractionController presentOptionsMenuFromBarButtonItem:self.btnshare animated:YES];
  230. // [self.fileInteractionController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  231. // [self.fileInteractionController presentPreviewAnimated:YES];
  232. }
  233. }
  234. - (void) sendEmail:(NSString *)to cc:(NSString*)cc subject:(NSString*)subject body:(NSString*)body
  235. {
  236. NSString* str = [NSString stringWithFormat:@"mailto:%@?cc=%@&subject=%@&body=%@",
  237. to, cc, subject, body];
  238. str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  239. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
  240. }
  241. #pragma mark methods for the UIDocumentInteractionControllerDelegate
  242. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  243. {
  244. // if (controller == self.fileInteractionController) {
  245. // self.fileInteractionController = nil;
  246. // }
  247. }
  248. - (void)previewDocumentWithURL:(NSURL*)url
  249. {
  250. UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:url];
  251. preview.delegate = self;
  252. [preview presentPreviewAnimated:YES];
  253. }
  254. - (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller
  255. {
  256. }
  257. - (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
  258. return self;
  259. }
  260. - (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
  261. return self.view.frame;
  262. }
  263. - (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
  264. return self.view;
  265. }
  266. - (void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(nullable NSString *)application // bundle ID
  267. {
  268. }
  269. #pragma mark - web view delegate
  270. - (void)webViewDidFinishLoad:(UIWebView *)webView
  271. {
  272. self.mum.hidden=true;
  273. }
  274. #pragma mark -MFMailComposeViewControllerDelegate delegate
  275. - (void)mailComposeController:(MFMailComposeViewController*)controller
  276. didFinishWithResult:(MFMailComposeResult)result
  277. error:(NSError*)error {
  278. switch (result)
  279. {
  280. case MFMailComposeResultCancelled:
  281. NSLog(@"Mail send canceled...");
  282. break;
  283. case MFMailComposeResultSaved:
  284. NSLog(@"Mail saved...");
  285. break;
  286. case MFMailComposeResultSent:
  287. NSLog(@"Mail sent...");
  288. break;
  289. case MFMailComposeResultFailed:
  290. NSLog(@"Mail send errored: %@...", [error localizedDescription]);
  291. break;
  292. default:
  293. break;
  294. }
  295. [self dismissModalViewControllerAnimated:YES];
  296. }
  297. /*
  298. #pragma mark - Navigation
  299. // In a storyboard-based application, you will often want to do a little preparation before navigation
  300. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  301. {
  302. // Get the new view controller using [segue destinationViewController].
  303. // Pass the selected object to the new view controller.
  304. }
  305. */
  306. @end