RAPDFViewController.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. //
  2. // RAPDFViewController.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 "RAPDFViewController.h"
  9. #import "RAUtils.h"
  10. #import "const.h"
  11. #import "AppDelegate.h"
  12. #import "PDFUtils.h"
  13. #import "TextUtils.h"
  14. @interface RAPDFViewController ()
  15. @end
  16. @implementation RAPDFViewController
  17. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
  18. {
  19. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  20. if (self) {
  21. // Custom initialization
  22. }
  23. return self;
  24. }
  25. - (void)setFilename:(NSString *)filename {
  26. _filename = [TextUtils legalFilename:filename];
  27. }
  28. - (void)viewDidLoad
  29. {
  30. NSLog(@"pdf viewer loaded");
  31. [super viewDidLoad];
  32. // Do any additional setup after loading the view.
  33. UIRefreshControl *ref = [[UIRefreshControl alloc]init];
  34. ref.tag = 200 ;
  35. ref.attributedTitle = [[NSAttributedString alloc]initWithString:@"drag to refresh"];
  36. ref.tintColor = [UIColor colorWithRed:0.10 green:0.68 blue:0.94 alpha:0.7];
  37. // ref.hidden = true;
  38. [ref addTarget:self action:@selector(changeCell) forControlEvents:UIControlEventValueChanged];
  39. [self.webView.scrollView addSubview:ref];
  40. self.webView.dataDetectorTypes=UIDataDetectorTypeAll;
  41. // self.btnsave.tintColor = UIColorFromRGB(0x996633);
  42. if(self.defaultStyle)
  43. {
  44. self.btnshare =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction
  45. target:self
  46. action:@selector( onActionClick:)];
  47. self.btnPrint =[[UIBarButtonItem alloc] initWithTitle:@"Print"
  48. style:UIBarButtonItemStylePlain
  49. target:self
  50. action:@selector( onPrintClick:)];
  51. NSMutableArray * items = [[NSMutableArray alloc]init];
  52. [items addObject:self.btnshare];
  53. [items addObject:self.btnPrint];
  54. self.navigationItem.rightBarButtonItems =items;
  55. if (self.navigationController.viewControllers[0]==self )
  56. {
  57. UIBarButtonItem *closeButton =nil;
  58. closeButton=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"close"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  59. style:UIBarButtonItemStylePlain
  60. target:self
  61. action:@selector( onCloseClick:)];
  62. //[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Close", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onCloseClick:)];
  63. // closeButton.title = @"Close";
  64. self.navigationItem.leftBarButtonItem = closeButton;
  65. }
  66. }
  67. else
  68. {
  69. UIBarButtonItem *closeButton =nil;
  70. closeButton=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  71. style:UIBarButtonItemStylePlain
  72. target:self
  73. action:@selector( onBackClick:)];
  74. //[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Close", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onCloseClick:)];
  75. // closeButton.title = @"Close";
  76. self.navigationItem.leftBarButtonItem = closeButton;
  77. self.btnshare = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"share"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  78. style:UIBarButtonItemStylePlain
  79. target:self
  80. action:@selector(onActionClick:)];//[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Edit", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onOpenOrderClick:)];
  81. // self.btnshare.tintColor = UIColorFromRGB(0x996633);
  82. self.btnemail =[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"mail"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  83. style:UIBarButtonItemStylePlain
  84. target:self
  85. action:@selector(onEmailClick:)];// [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Commit", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onCommitOrderClick:)];
  86. // self.btnemail.tintColor = UIColorFromRGB(0x996633);
  87. // self.btnSend = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Email", nil) style:UIBarButtonItemStylePlain target:self action:@selector(onSendMailClick:)];
  88. self.btnsave = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"save"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  89. style:UIBarButtonItemStylePlain
  90. target:self
  91. action:@selector(onSaveClick:)];
  92. UIBarButtonItem *fixedItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
  93. fixedItem.width = 20.0f;
  94. NSMutableArray * items = [[NSMutableArray alloc]init];
  95. [items addObject:self.btnshare];
  96. [items addObject:fixedItem];
  97. [items addObject:self.btnemail];
  98. if(self.canSave)
  99. {
  100. [items addObject:fixedItem];
  101. [items addObject:self.btnsave];
  102. }
  103. self.navigationItem.rightBarButtonItems=items;
  104. self.btnshare.enabled =false;
  105. self.btnemail.enabled =false;
  106. self.btnsave.enabled =false;
  107. }
  108. // self.url=@"http://192.168.1.3:8080/npd/test.pdf";
  109. // NSURL* url = [NSURL URLWithString:self.url];
  110. //
  111. // NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:2000];
  112. //
  113. //
  114. // [self.webView loadRequest:request];
  115. [self loadcontent];
  116. }
  117. - (void)onBackClick:(UIButton *)sender {
  118. [self.navigationController popViewControllerAnimated:FALSE];
  119. }
  120. - (void)onCloseClick:(UIButton *)sender {
  121. [self dismissViewControllerAnimated:false completion:nil];
  122. //[self.navigationController popViewControllerAnimated:FALSE];
  123. }
  124. -(void)ReloadData
  125. {
  126. // Count ++ ;
  127. // [mytabelview reloadData];
  128. UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
  129. [reF endRefreshing];
  130. [self loadcontent];
  131. }
  132. - (void)copyTmpLocalFile:(NSString *)localPath {
  133. NSString *path = NSTemporaryDirectory();
  134. NSString *filePath = [path stringByAppendingPathComponent:self.filename];
  135. NSFileManager *fileManager = [NSFileManager defaultManager];
  136. if ([fileManager fileExistsAtPath:filePath]) { // 文件存在就不会拷贝
  137. [fileManager removeItemAtPath:filePath error:nil];
  138. }
  139. [fileManager copyItemAtPath:localPath toPath:filePath error:nil];
  140. self.url = filePath;
  141. }
  142. -(void) loadcontent
  143. {
  144. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Loading..."];
  145. self.mum.hidden=false;
  146. if(self.isLocalfile)
  147. {
  148. /*
  149. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  150. NSString *cachefolder = [paths objectAtIndex:0];
  151. NSString *pdfFolder = [cachefolder stringByAppendingPathComponent:@"pdf_cache"];
  152. self.url = [pdfFolder stringByAppendingPathComponent:self.url];
  153. */
  154. self.content= [NSData dataWithContentsOfFile:self.url];
  155. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  156. if (self.filename.length <= 0) {
  157. self.filename=[self.url lastPathComponent];
  158. } else {
  159. [self copyTmpLocalFile:self.url];
  160. }
  161. self.btnshare.enabled =true;
  162. self.btnemail.enabled =true;
  163. self.btnsave.enabled =true;
  164. // if(self.onLoadSuccess)
  165. // self.onLoadSuccess(self.url);
  166. //
  167. // if(self.autoPrint)
  168. // [self startAirPrintWithData:self.content];
  169. // NSLog(@"put file to webview");
  170. // [self.webView loadData:self.content MIMEType:@"application/pdf" textEncodingName:nil baseURL:nil];
  171. NSURL *url = [NSURL fileURLWithPath:self.url];
  172. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  173. [self.webView loadRequest:request];
  174. }
  175. else
  176. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  177. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60*5];
  178. //设置请求方式为get
  179. [request setHTTPMethod:@"GET"];
  180. //添加用户会话id
  181. [request addValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
  182. //连接发送请求
  183. NSHTTPURLResponse* urlResponse = nil;
  184. NSError *error = nil;
  185. self.content= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  186. if(self.filename.length<=0)
  187. self.filename = [urlResponse suggestedFilename];
  188. dispatch_async(dispatch_get_main_queue(), ^{
  189. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  190. [[self navigationController] setNavigationBarHidden:self.hidenavi animated:NO];
  191. self.navigationItem.title = self.save_name;
  192. UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
  193. // self.content=nil;
  194. if(self.content!=nil&&self.content.length>0)
  195. {
  196. [reF removeFromSuperview];
  197. // NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  198. NSString *path = NSTemporaryDirectory();
  199. NSString *filePath = [path stringByAppendingPathComponent:self.filename];
  200. // NSError *error = nil;
  201. // BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
  202. // NSAssert(bo,@"创建目录失败");
  203. if (self.cachePath.length) {
  204. filePath = self.cachePath;
  205. }
  206. [self.content writeToFile:filePath atomically:YES];
  207. self.url = filePath;
  208. self.isLocalfile = true;
  209. self.btnshare.enabled =true;
  210. self.btnemail.enabled =true;
  211. self.btnsave.enabled =true;
  212. NSURL *url = [NSURL fileURLWithPath:filePath];
  213. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  214. [self.webView loadRequest:request];
  215. // int a=0;
  216. }
  217. else
  218. {
  219. [RAUtils message_alert:nil title:@"Open PDF Failed" controller:self];
  220. if(self.autoPrint)
  221. [self.navigationController popViewControllerAnimated:true];
  222. // self.content = [self.url dataUsingEncoding:NSUTF8StringEncoding];
  223. }
  224. ;
  225. // DebugLog(@"%@",[[NSString alloc] initWithData:self.content encoding:NSASCIIStringEncoding]);
  226. //
  227. // DebugLog(urlResponse.MIMEType);
  228. // [self.webView loadData:self.content MIMEType:urlResponse.MIMEType textEncodingName:nil baseURL:nil];
  229. });
  230. });
  231. }
  232. -(void)changeCell
  233. {
  234. UIRefreshControl *reF = (UIRefreshControl *)[self.view viewWithTag:200];
  235. reF.attributedTitle = [[NSAttributedString alloc]initWithString:@"refreshing"];
  236. if ([self respondsToSelector:@selector(ReloadData)])
  237. [self performSelector:@selector(ReloadData) withObject:nil afterDelay:1];
  238. // DebugLog(@"refresh!!!!!!!!");
  239. }
  240. - (void)didReceiveMemoryWarning
  241. {
  242. [super didReceiveMemoryWarning];
  243. // Dispose of any resources that can be recreated.
  244. }
  245. -(void) viewWillAppear:(BOOL)animated
  246. {
  247. [super viewWillAppear:animated];
  248. [[self navigationController] setNavigationBarHidden:self.hidenavi animated:NO];
  249. }
  250. - (IBAction)onPrintClick:(id)sender {
  251. // UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"preparing print..."];
  252. UIPrintInteractionController* airPrinterController=[UIPrintInteractionController sharedPrintController];
  253. UIPrintInfo *printInfo = [UIPrintInfo printInfo];
  254. printInfo.outputType = UIPrintInfoOutputGeneral;
  255. printInfo.orientation = UIPrintInfoOrientationPortrait;
  256. printInfo.jobName = @"CoolVisitAirPrint";
  257. airPrinterController.printInfo = printInfo;
  258. airPrinterController.printingItem = self.content;
  259. airPrinterController.delegate = self;
  260. airPrinterController.showsNumberOfCopies=true;
  261. airPrinterController.showsPageRange = true;
  262. airPrinterController.showsPaperSelectionForLoadedPapers=true;
  263. [airPrinterController presentFromBarButtonItem:self.btnPrint
  264. animated:YES
  265. completionHandler:
  266. ^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
  267. }
  268. ];
  269. //
  270. // void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
  271. // if(completed && error)
  272. // DebugLog(@"Printing failed due to error in domain %@ with error code %lu. Localized description: %@, and failure reason: %@", error.domain, (long)error.code, error.localizedDescription, error.localizedFailureReason);
  273. // };
  274. //
  275. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  276. //
  277. // UIPrinter *airPrinter = [UIPrinter printerWithURL:[NSURL URLWithString:appDelegate.printerURL] ];///*self.printer;*/
  278. //
  279. //
  280. //
  281. //
  282. // [[UIPrinter printerWithURL:[NSURL URLWithString:appDelegate.printerURL]] contactPrinter:^(BOOL available)
  283. // {
  284. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  285. //
  286. // if (available&& appDelegate.printerURL.length>0)
  287. // {
  288. //
  289. //
  290. // [airPrinterController printToPrinter:airPrinter completionHandler:completionHandler];
  291. // DebugLog(@"AIRPRINTER AVAILABLE");
  292. // }
  293. // else
  294. // {
  295. //
  296. // [airPrinterController presentFromRect:CGRectMake(0, 0, 300, 500) inView:self.view animated:YES completionHandler:
  297. //
  298. //
  299. //
  300. // // [printPicker presentAnimated:YES completionHandler:
  301. // ^(UIPrintInteractionController *printerController, BOOL userDidSelect, NSError *error)
  302. // {
  303. // if (userDidSelect)
  304. // {
  305. // NSString* sid= printerController.printInfo.printerID;
  306. // UIPrintPaper*paper= printerController.printPaper;
  307. //
  308. // }
  309. // }];
  310. //
  311. //
  312. // DebugLog(@"AIRPRINTER NOT AVAILABLE");
  313. //
  314. //
  315. //
  316. //// if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
  317. //// {
  318. //// UIPrinterPickerController *printPicker = [UIPrinterPickerController printerPickerControllerWithInitiallySelectedPrinter:nil];
  319. //// // [printPicker presentFromBarButtonItem:self.btnSubmitOrder animated:yes completionHandler:
  320. ////
  321. ////
  322. ////
  323. //// [ printPicker presentFromBarButtonItem:self.btnPrint animated:YES completionHandler:
  324. ////
  325. ////
  326. //// // [printPicker presentFromRect:CGRectMake(0, 0, 300, 500) inView:self.view animated:YES completionHandler:
  327. ////
  328. ////
  329. ////
  330. //// // [printPicker presentAnimated:YES completionHandler:
  331. //// ^(UIPrinterPickerController *printerPicker, BOOL userDidSelect, NSError *error)
  332. //// {
  333. //// if (userDidSelect)
  334. //// {
  335. //// //User selected the item in the UIPrinterPickerController and got the printer details.
  336. ////
  337. //// [UIPrinterPickerController printerPickerControllerWithInitiallySelectedPrinter:printerPicker.selectedPrinter];
  338. ////
  339. //// //Here you will get the printer and printer details.ie,
  340. //// // printerPicker.selectedPrinter, printerPicker.selectedPrinter.displayName, printerPicker.selectedPrinter.URL etc. So you can display the printer name in your label text or button title.
  341. ////
  342. ////
  343. ////
  344. ////
  345. //// appDelegate.printerURL =printerPicker.selectedPrinter.URL.absoluteString;
  346. ////
  347. //// [self startAirPrintWithData:self.content];
  348. ////
  349. //// }
  350. //// else
  351. //// {
  352. ////
  353. ////
  354. //// // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  355. //// // if([appDelegate.mode isEqualToString:@"Trade Show Mode"]&& appDelegate.submit_order_logout)
  356. //// // {
  357. //// //
  358. //// // [((MainViewController*)appDelegate.main_vc) Loginout:false];
  359. //// // }
  360. //// // [self prepareReturn:nil];
  361. ////
  362. //// //[self.navigationController popViewControllerAnimated:true];
  363. //// }
  364. //// }];
  365. //// }
  366. // }
  367. // }];
  368. //
  369. }
  370. - (IBAction)onActionClick:(id)sender {
  371. //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  372. // NSString *filePath = nil;
  373. // if(!self.isLocalfile)
  374. // {
  375. // NSString *path = NSTemporaryDirectory();
  376. // NSString* filename =self.filename;
  377. //
  378. // filePath= [path stringByAppendingPathComponent:filename];
  379. //
  380. // }
  381. // else
  382. // filePath = self.url;
  383. [self openFile:self.url];
  384. }
  385. - (IBAction)onSaveClick:(id)sender {
  386. //UIAlertControllerStyle两种类型UIAlertControllerStyleAlert类似UIAlertView
  387. //UIAlertControllerStyleActionSheet类似UIActionSheet
  388. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Save pdf" message:nil preferredStyle:UIAlertControllerStyleAlert];
  389. //block代码块取代了delegate
  390. [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  391. textField.text = self.save_name;
  392. }];
  393. UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  394. UITextField *name = alertControl.textFields.firstObject;
  395. if(name.text.length==0)
  396. {
  397. [RAUtils message_alert:@"Cannot save without name. Save canceled." title:@"Name is missing" controller:self];
  398. }
  399. else
  400. {
  401. self.save_name = name.text;
  402. self.btnsave.enabled =false;
  403. // NSMutableDictionary * info =
  404. if(self.onSavePDF)
  405. self.onSavePDF(self.save_name,self.filename);
  406. }
  407. }];
  408. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  409. DebugLog(@"Cancel");
  410. }];
  411. [alertControl addAction:actionOne];
  412. [alertControl addAction:alertthree];
  413. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  414. [self presentViewController:alertControl animated:YES completion:nil];
  415. }
  416. - (IBAction)onEmailClick:(id)sender {
  417. //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  418. // NSString *path = NSTemporaryDirectory();
  419. NSString* filename =self.filename;
  420. // NSString *filePath = [path stringByAppendingPathComponent:filename];
  421. NSString *filePath = self.url;
  422. MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
  423. if(mc==nil)
  424. {
  425. //[RAUtils message_alert:@"You must create an email account first." title:@"Send Email" controller:self];
  426. return;
  427. }
  428. mc.mailComposeDelegate = self;
  429. [mc setSubject:self.mail_subject];
  430. [mc setToRecipients:self.mail_to];
  431. if(self.mail_content==nil)
  432. self.mail_content=@"";
  433. NSString* htmlbody = [NSString stringWithFormat:@"<html><p>%@</p></html>",self.mail_content];
  434. [mc setMessageBody:htmlbody
  435. isHTML:YES];
  436. NSData *data = [NSData dataWithContentsOfFile:filePath];
  437. // if(self.attachment_name.length>0)
  438. // filename = self.attachment_name;
  439. [mc addAttachmentData:data mimeType:@"application/pdf" fileName:filename];
  440. [self presentModalViewController:mc animated:YES];
  441. return;
  442. }
  443. -(void)openFile: (NSString *) file_url {
  444. NSURL *file_URL = [NSURL fileURLWithPath:file_url];
  445. if (file_URL != nil) {
  446. if (self.fileInteractionController == nil) {
  447. //_fileInteractionController = [[UIDocumentInteractionController alloc] init];
  448. _fileInteractionController = [UIDocumentInteractionController interactionControllerWithURL:file_URL];
  449. _fileInteractionController.delegate = self;
  450. // [_fileInteractionController retain];//不适用ARC,记得RETAIN 使用ARC注释这一行
  451. }
  452. else
  453. {
  454. self.fileInteractionController.URL = file_URL;
  455. }
  456. // [self.fileInteractionController presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
  457. [self.fileInteractionController setName:self.mail_subject];
  458. // [self.fileInteractionController setAnnotation:<#(id _Nullable)#>;
  459. [self.fileInteractionController presentOptionsMenuFromBarButtonItem:self.btnshare animated:YES];
  460. // [self.fileInteractionController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  461. // [self.fileInteractionController presentPreviewAnimated:YES];
  462. }
  463. }
  464. //- (void) sendEmail:(NSString *)to cc:(NSString*)cc subject:(NSString*)subject body:(NSString*)body
  465. //{
  466. // NSString* str = [NSString stringWithFormat:@"mailto:%@?cc=%@&subject=%@&body=%@",
  467. // to, cc, subject, body];
  468. // str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  469. //
  470. // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
  471. //
  472. //
  473. //}
  474. #pragma mark methods for the UIDocumentInteractionControllerDelegate
  475. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  476. {
  477. // if (controller == self.fileInteractionController) {
  478. // self.fileInteractionController = nil;
  479. // }
  480. }
  481. - (void)previewDocumentWithURL:(NSURL*)url
  482. {
  483. UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:url];
  484. preview.delegate = self;
  485. [preview presentPreviewAnimated:YES];
  486. }
  487. - (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller
  488. {
  489. }
  490. - (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
  491. return self;
  492. }
  493. - (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
  494. return self.view.frame;
  495. }
  496. - (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
  497. return self.view;
  498. }
  499. - (void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(nullable NSString *)application // bundle ID
  500. {
  501. }
  502. #pragma mark - web view delegate
  503. - (void)webViewDidFinishLoad:(UIWebView *)webView
  504. {
  505. self.mum.hidden=true;
  506. if(self.onLoadSuccess)
  507. self.onLoadSuccess(self.url);
  508. if(self.autoPrint)
  509. [self startAirPrintWithData:self.content];
  510. }
  511. - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
  512. {
  513. }
  514. #pragma mark -MFMailComposeViewControllerDelegate delegate
  515. - (void)mailComposeController:(MFMailComposeViewController*)controller
  516. didFinishWithResult:(MFMailComposeResult)result
  517. error:(NSError*)error {
  518. switch (result)
  519. {
  520. case MFMailComposeResultCancelled:
  521. DebugLog(@"Mail send canceled...");
  522. break;
  523. case MFMailComposeResultSaved:
  524. DebugLog(@"Mail saved...");
  525. break;
  526. case MFMailComposeResultSent:
  527. DebugLog(@"Mail sent...");
  528. break;
  529. case MFMailComposeResultFailed:
  530. DebugLog(@"Mail send errored: %@...", [error localizedDescription]);
  531. break;
  532. default:
  533. break;
  534. }
  535. [self dismissModalViewControllerAnimated:YES];
  536. }
  537. /*
  538. #pragma mark - Navigation
  539. In a storyboard-based application, you will often want to do a little preparation before navigation
  540. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  541. {
  542. Get the new view controller using [segue destinationViewController].
  543. Pass the selected object to the new view controller.
  544. }
  545. */
  546. - (void)startAirPrintWithData:(id )data
  547. {
  548. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"preparing print..."];
  549. UIPrintInteractionController* airPrinterController=[UIPrintInteractionController sharedPrintController];
  550. UIPrintInfo *printInfo = [UIPrintInfo printInfo];
  551. printInfo.outputType = UIPrintInfoOutputGeneral;
  552. printInfo.orientation = UIPrintInfoOrientationPortrait;
  553. printInfo.jobName = @"CoolVisitAirPrint";
  554. airPrinterController.printInfo = printInfo;
  555. airPrinterController.printingItem = data;
  556. airPrinterController.delegate = self;
  557. airPrinterController.showsNumberOfCopies=true;
  558. airPrinterController.showsPageRange = true;
  559. airPrinterController.showsPaperSelectionForLoadedPapers=true;
  560. void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
  561. if(completed && error)
  562. DebugLog(@"Printing failed due to error in domain %@ with error code %lu. Localized description: %@, and failure reason: %@", error.domain, (long)error.code, error.localizedDescription, error.localizedFailureReason);
  563. };
  564. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  565. UIPrinter *airPrinter = [UIPrinter printerWithURL:[NSURL URLWithString:appDelegate.printerURL] ];///*self.printer;*/
  566. [[UIPrinter printerWithURL:[NSURL URLWithString:appDelegate.printerURL]] contactPrinter:^(BOOL available)
  567. {
  568. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  569. if (available&& appDelegate.printerURL.length>0)
  570. {
  571. [airPrinterController printToPrinter:airPrinter completionHandler:completionHandler];
  572. DebugLog(@"AIRPRINTER AVAILABLE");
  573. }
  574. else
  575. {
  576. // [airPrinterController presentFromRect:CGRectMake(0, 0, 300, 500) inView:self.view animated:YES completionHandler:
  577. //
  578. //
  579. //
  580. // // [printPicker presentAnimated:YES completionHandler:
  581. // ^(UIPrintInteractionController *printerController, BOOL userDidSelect, NSError *error)
  582. // {
  583. // if (userDidSelect)
  584. // {
  585. // NSString* sid= printerController.printInfo.printerID;
  586. // UIPrintPaper*paper= printerController.printPaper;
  587. //
  588. // }
  589. // }];
  590. DebugLog(@"AIRPRINTER NOT AVAILABLE");
  591. if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
  592. {
  593. UIPrinterPickerController *printPicker = [UIPrinterPickerController printerPickerControllerWithInitiallySelectedPrinter:nil];
  594. // [printPicker presentFromBarButtonItem:self.btnSubmitOrder animated:yes completionHandler:
  595. [ printPicker presentFromBarButtonItem:self.btnshare animated:YES completionHandler:
  596. // [printPicker presentFromRect:CGRectMake(0, 0, 300, 500) inView:self.view animated:YES completionHandler:
  597. // [printPicker presentAnimated:YES completionHandler:
  598. ^(UIPrinterPickerController *printerPicker, BOOL userDidSelect, NSError *error)
  599. {
  600. if (userDidSelect)
  601. {
  602. //User selected the item in the UIPrinterPickerController and got the printer details.
  603. [UIPrinterPickerController printerPickerControllerWithInitiallySelectedPrinter:printerPicker.selectedPrinter];
  604. //Here you will get the printer and printer details.ie,
  605. // printerPicker.selectedPrinter, printerPicker.selectedPrinter.displayName, printerPicker.selectedPrinter.URL etc. So you can display the printer name in your label text or button title.
  606. appDelegate.printerURL =printerPicker.selectedPrinter.URL.absoluteString;
  607. [self startAirPrintWithData:data];
  608. }
  609. else
  610. {
  611. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  612. // if([appDelegate.mode isEqualToString:@"Trade Show Mode"]&& appDelegate.submit_order_logout)
  613. // {
  614. //
  615. // [((MainViewController*)appDelegate.main_vc) Loginout:false];
  616. // }
  617. // [self prepareReturn:nil];
  618. //[self.navigationController popViewControllerAnimated:true];
  619. }
  620. }];
  621. }
  622. }
  623. }];
  624. }
  625. #pragma mark - UIPrintInteractionControllerDelegate
  626. - (UIPrintPaper *)printInteractionController:(UIPrintInteractionController *)printInteractionController choosePaper:(NSArray<UIPrintPaper *> *)paperList
  627. {
  628. ;
  629. // (int) width = 29700
  630. // Printing description of (*( (int *)0x7caa3a40)):
  631. // (int) height = 42000
  632. //设置纸张大小
  633. CGSize paperSize=[PDFUtils QueryPDFSizeFromData:self.content];
  634. for(UIPrintPaper* paper in paperList)
  635. {
  636. if (CGSizeEqualToSize(paper.paperSize, paperSize))
  637. return paper;
  638. }
  639. UIPrintPaper * pp=[[UIPrintPaper alloc] init];
  640. // CGSize paperSize = CGSizeMake(612, 792);
  641. UIPrintPaper * p=[UIPrintPaper bestPaperForPageSize:paperSize withPapersFromArray:paperList];
  642. return p;
  643. }
  644. - (void)printInteractionControllerWillPresentPrinterOptions:(UIPrintInteractionController *)printInteractionController
  645. {
  646. }
  647. - (void)printInteractionControllerDidPresentPrinterOptions:(UIPrintInteractionController *)printInteractionController
  648. {
  649. }
  650. - (void)printInteractionControllerWillDismissPrinterOptions:(UIPrintInteractionController *)printInteractionController
  651. {
  652. }
  653. - (void)printInteractionControllerDidDismissPrinterOptions:(UIPrintInteractionController *)printInteractionController
  654. {
  655. }
  656. - (void)printInteractionControllerWillStartJob:(UIPrintInteractionController *)printInteractionController
  657. {
  658. }
  659. - (void)printInteractionControllerDidFinishJob:(UIPrintInteractionController *)printInteractionController
  660. {
  661. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  662. // if([appDelegate.mode isEqualToString:@"Trade Show Mode"]&& appDelegate.submit_order_logout)
  663. // {
  664. //
  665. // [((MainViewController*)appDelegate.main_vc) Loginout:false];
  666. // }
  667. //
  668. // [self prepareReturn:nil];
  669. if(self.autoPrint)
  670. [self.navigationController popViewControllerAnimated:true];
  671. }
  672. @end