DocumentPageViewController.m 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. //
  2. // DocumentPageViewController.m
  3. // AntsContract
  4. //
  5. // Created by Ray on 12/16/16.
  6. // Copyright © 2016 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "DocumentPageViewController.h"
  9. #import "PageViewController.h"
  10. #import "SignatureListViewController.h"
  11. #import "SignatureViewController.h"
  12. #import "PDFUtils.h"
  13. #import "ACNetwork.h"
  14. //#import "AFHTTPSessionManager.h"
  15. #import "AppDelegate.h"
  16. #import "ACNetwork.h"
  17. #import "RAUtils.h"
  18. #import "PDFViewController.h"
  19. #import "config.h"
  20. #import "AESCrypt.h"
  21. #import "CustomIOSAlertView.h"
  22. #import "ImageUtils.h"
  23. #import "PDFPage.h"
  24. #import "TextDrawable.h"
  25. #import "ImageDrawable.h"
  26. #import "RectDrawable.h"
  27. @interface DocumentPageViewController ()
  28. @end
  29. @implementation DocumentPageViewController
  30. -(NSMutableDictionary*) templateInit:(NSMutableDictionary*) template
  31. {
  32. NSString* temp = NSTemporaryDirectory();
  33. NSString* filename =[NSString stringWithFormat:@"%@.png", [[NSUUID UUID] UUIDString]];
  34. NSString* qrpath=[temp stringByAppendingPathComponent:filename];
  35. UIImage* qrimg=[RAUtils generateBarCode:self.docment_id width:300 height:44];//[QRCodeGenerator qrImageForString:order_code imageSize:240];
  36. bool bwrite=[UIImagePNGRepresentation(qrimg)writeToFile: qrpath atomically:YES];
  37. for(int i=0;i<[template[@"count"] intValue];i++)
  38. {
  39. NSMutableDictionary* page =template[[NSString stringWithFormat:@"page_%d",i]];
  40. for(int j=0;j<[page[@"count"] intValue];j++)
  41. {
  42. NSMutableDictionary* control =page[[NSString stringWithFormat:@"control_%d",j]];
  43. NSString* type = control[@"type"];
  44. NSString* field =control[@"field"];
  45. if([type isEqualToString:@"Label"])
  46. {
  47. if([field isEqualToString:@"doc_number"])
  48. {
  49. control[@"value"]= self.docment_id;
  50. }
  51. }
  52. else if([type isEqualToString:@"Image"])
  53. {
  54. NSString* name =control[@"name"];
  55. if([name isEqualToString:@"BarCode"])
  56. {
  57. if(bwrite)
  58. control[@"value"]= qrpath;
  59. }
  60. }
  61. else if([type isEqualToString:@"DatePicker"])
  62. {
  63. NSString* name =control[@"aname"];
  64. if([name isEqualToString:@"Today's Date"])
  65. {
  66. NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
  67. [formatter setDateFormat:@"MM/dd/yyyy"];
  68. NSString* date = [formatter stringFromDate:[NSDate date]] ;
  69. control[@"value"]= date;
  70. }
  71. }
  72. }
  73. }
  74. return template;
  75. }
  76. - (void)viewDidLoad {
  77. [super viewDidLoad];
  78. // self.delegate = self;
  79. // self.dataSource = self;
  80. self.signatureData= [[NSMutableDictionary alloc] init];
  81. self.document = [PDFUtils OpenPDF:self.pdfName];
  82. self.total_page = CGPDFDocumentGetNumberOfPages (self.document);
  83. self.controlTemplate = [self templateInit:[PDFUtils loadControl:self.templateName]];
  84. PageViewController* startingViewController=[self viewControllerAtIndex:0];
  85. // NSArray* viewControllers =[NSArray arrayWithObjects:page_0,nil];
  86. self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
  87. self.pageViewController.delegate = self;
  88. // PageViewController *startingViewController = [self viewControllerAtIndex:0 storyboard:self.storyboard];
  89. NSArray *viewControllers = @[startingViewController];
  90. [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
  91. self.pageViewController.dataSource = self;
  92. [self addChildViewController:self.pageViewController];
  93. [self.view addSubview:self.pageViewController.view];
  94. // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
  95. CGRect pageViewRect = self.view.bounds;
  96. if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
  97. pageViewRect = pageViewRect;//CGRectInset(pageViewRect, 40.0, 40.0);
  98. }
  99. self.pageViewController.view.frame = pageViewRect;
  100. [self.pageViewController didMoveToParentViewController:self];
  101. // Do any additional setup after loading the view.
  102. }
  103. -(void) dealloc
  104. {
  105. CFRelease(self.document);
  106. }
  107. - (void)didReceiveMemoryWarning {
  108. [super didReceiveMemoryWarning];
  109. // Dispose of any resources that can be recreated.
  110. }
  111. - (IBAction)OnCancelClicked:(id)sender {
  112. UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Are you sure cancel customer? All your entered information will lost." message:nil preferredStyle:UIAlertControllerStyleAlert];
  113. UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  114. [self.navigationController popToRootViewControllerAnimated:false];
  115. }];
  116. // [alertControl addAction:actionOne];
  117. [alertControl addAction:alertthree];
  118. UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  119. }];
  120. [alertControl addAction:alertcancel];
  121. //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  122. [self presentViewController:alertControl animated:YES completion:nil];
  123. }
  124. - (IBAction)onSignatureClicked:(id)sender {
  125. // CGRect cellrect_screen = [RAUtils relativeFrameForScreenWithView:trigger];
  126. //
  127. //
  128. // CGRect rect1=[self.view convertRect:cellrect_screen fromView:[[[UIApplication sharedApplication] delegate] window]];
  129. //
  130. // DebugLog(@"convert1 %@",NSStringFromCGRect(rect1));
  131. SignatureListViewController *signatureVC = [ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureListViewController"];
  132. signatureVC.title=@"Signatures";
  133. signatureVC.signatureData = self.signatureData;
  134. signatureVC.blk_Add = ^()
  135. {
  136. __block UIImage* signimg=nil;
  137. SignatureViewController * vc =[ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureViewController"];
  138. vc.onReturnImg = ^(UIImage* img)
  139. {
  140. signimg = img;
  141. // if(signimg!=nil)
  142. // [PDFUtils addSignature:signimg to:self.signatureData];
  143. };
  144. // orderinfoVC.url_type = URL_REMOTE;
  145. // orderinfoVC.request_url=URL_CARTDELIVERY;
  146. //
  147. // orderinfoVC.params = params;
  148. //
  149. // orderinfoVC.delegate=self;
  150. //
  151. // if(checked.count==count)
  152. // {
  153. // orderinfoVC.have_tail = true
  154. // }
  155. [self.navigationController pushViewController:vc animated:true];
  156. };
  157. // signatureVC.blk_Fill =^(NSString* file, bool fillFullDoc)
  158. // {
  159. //
  160. //
  161. // for(int i=0;i<[self.controlTemplate[@"count"] intValue];i++)
  162. // {
  163. // NSMutableDictionary* page =self.controlTemplate[[NSString stringWithFormat:@"page_%d",i]];
  164. // if(!fillFullDoc && i!=self.current_page)
  165. // continue;
  166. // for(int j=0;j<[page[@"count"] intValue];j++)
  167. // {
  168. // NSMutableDictionary* control =page[[NSString stringWithFormat:@"control_%d",j]];
  169. // NSString* type = control[@"type"];
  170. // if(![type isEqualToString:@"Signature"])
  171. // continue;
  172. //
  173. // control[@"value"]=file;
  174. //
  175. //// NSString* name = control[@"aname"];
  176. //// bool required = [control[@"required"] boolValue];
  177. ////
  178. //// if(required==false)
  179. //// continue;
  180. //// if([type isEqualToString:@"Check"])
  181. //// {
  182. //// NSArray* arr = control[@"value"];
  183. //// if(arr.count==0)
  184. //// {
  185. //// ret=false;
  186. ////
  187. //// NSString* msg=[NSString stringWithFormat:@"%u Page %d %@ is missing.",fields.count+1,i+1,name];
  188. //// if(fields.count<15)
  189. //// [fields addObject:msg];
  190. //// else
  191. //// more++;
  192. //// }
  193. ////
  194. //// }
  195. //// else if(/*[type isEqualToString:@"Signature"]||*/[type isEqualToString:@"Image"]||[type isEqualToString:@"Label"])
  196. //// {
  197. //// continue;
  198. //// }
  199. //// else
  200. //// {
  201. //// NSString* str = control[@"value"];
  202. //// if(str.length==0)
  203. //// {
  204. //// ret=false;
  205. //// NSString* msg=[NSString stringWithFormat:@"%lu Page %d %@ is missing.",fields.count+1,i+1,name];
  206. //// if(fields.count<15)
  207. //// [fields addObject:msg];
  208. //// else
  209. //// more++;
  210. //// }
  211. //// }
  212. // }
  213. // }
  214. //
  215. //
  216. // // NSString* file_name=[file lastPathComponent];
  217. ////
  218. //// NSData* img_data=[ImageUtils load_img:file];
  219. ////
  220. //// if(img_data!=nil)
  221. //// {
  222. ////
  223. //// UIImage* image=[UIImage imageWithData:img_data];
  224. //// touchImageView.image = image;
  225. ////
  226. //// long index = touchImageView.tag - CONTROL_BASE;
  227. //// self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
  228. ////
  229. //// }
  230. //
  231. // };
  232. UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:signatureVC];
  233. navi.modalPresentationStyle=UIModalPresentationPopover;
  234. UIPopoverPresentationController* popPc = navi.popoverPresentationController;
  235. popPc.permittedArrowDirections = UIPopoverArrowDirectionUp;
  236. popPc.barButtonItem = sender;
  237. popPc.delegate = nil;
  238. [self presentViewController:navi animated:true completion:nil];
  239. //// menu.selector = self.selector;
  240. ////
  241. //// menu.selectordelegate = self;
  242. //
  243. // // 1.创建一个UIPopover
  244. // UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:[[UINavigationController alloc] initWithRootViewController:menu]];
  245. //
  246. //
  247. //
  248. // UIPopoverPresentationController
  249. // // 2.设置尺寸
  250. // // popover.popoverContentSize = CGSizeMake(320, 44 * 5);
  251. //
  252. // // 3.从哪里显示出来 --> 指向item
  253. //
  254. // [popover presentPopoverFromRect:self.view.frame inView:self.view permittedArrowDirections:0 animated:YES];
  255. // // [popover presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
  256. //
  257. //// self.popover = popover;
  258. // popover pop
  259. //
  260. // [self performSegueWithIdentifier:@"selector_popover" sender:self];
  261. }
  262. -(CGRect)WindowRect2PDFRect:(CGRect)rect pdf_rect:(CGRect)pdf_rect window_size:(CGSize)window_size
  263. {
  264. CGRect pdf_expand;
  265. float offset_x = 0;
  266. float offset_y = 0;
  267. float scale =1;
  268. if(pdf_rect.size.height>=pdf_rect.size.width)
  269. {
  270. pdf_expand = CGRectMake(0, 0, pdf_rect.size.height*window_size.width/window_size.height, pdf_rect.size.height);
  271. offset_x = (pdf_expand.size.width-pdf_rect.size.width)/2;
  272. scale = pdf_rect.size.height/window_size.height;
  273. }
  274. else
  275. {
  276. pdf_expand = CGRectMake(0, 0, pdf_rect.size.width, pdf_rect.size.width*window_size.height/window_size.width);
  277. offset_y = (pdf_expand.size.height-pdf_rect.size.height)/2;
  278. scale = pdf_rect.size.width/window_size.width;
  279. }
  280. float x=rect.origin.x*scale-offset_x;
  281. float y=rect.origin.y*scale-offset_y;
  282. float width = rect.size.width*scale;
  283. float height = rect.size.height*scale;
  284. return CGRectMake(x, y, width, height);
  285. }
  286. - (IBAction)onSaveClicked:(id)sender {
  287. if([self verifyData]==false)
  288. return;
  289. NSString* pdffile = nil;
  290. NSString* zipfile = nil;
  291. // for(int l=0;l<1;l++)
  292. {
  293. pdffile = [PDFUtils SavePDF:self.controlTemplate source:self.document window_rect:CGRectMake(0, 0, 768, 960)];
  294. zipfile=[ACNetwork prepareUploadFile:pdffile json:self.controlTemplate];
  295. }
  296. __weak typeof(self) weakSelf = self;
  297. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Saving"];
  298. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  299. NSDictionary* json = nil;
  300. json = [ACNetwork save_document:zipfile];
  301. dispatch_async(dispatch_get_main_queue(), ^{
  302. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  303. // if([[logout_json valueForKey:@"result"] intValue]==2)
  304. // {
  305. // self.welcomeLabel.text=@"Not sign in";
  306. // // [sender setTitle:@"Sign in" forState:UIControlStateNormal];
  307. // [bbitem setTitle:@"Sign in"];
  308. //
  309. // self.buttonHIC.enabled = false;
  310. // self.buttonSRL.enabled = false;
  311. // self.coverView.hidden = false;
  312. // }
  313. // else
  314. // {
  315. // [RAUtils message_alert:[logout_json valueForKey:@"err_msg"] title:@"Sign out" controller:self] ;
  316. // }
  317. if([[json valueForKey:@"result"] intValue]==2)
  318. {
  319. [weakSelf.navigationController popToRootViewControllerAnimated:false];
  320. if(weakSelf.OnSave)
  321. weakSelf.OnSave(pdffile);
  322. }
  323. else
  324. {
  325. [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Save document" controller:self] ;
  326. }
  327. });
  328. });
  329. // return;
  330. // {
  331. //
  332. //
  333. // UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Saving"];
  334. //
  335. //
  336. //// self.uploadProgress.progress = 0;
  337. //
  338. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  339. //
  340. //
  341. // {
  342. //
  343. // // UIAlertView * waitalert = [[UIAlertView alloc] initWithTitle:@"wait" message:@"uploading" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  344. // // [waitalert show];
  345. //
  346. //// NSData *imageData = UIImagePNGRepresentation(self.imgview.image);
  347. //
  348. // AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  349. //
  350. //
  351. //
  352. // NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  353. //
  354. //// if(appDelegate.user!=nil)
  355. //// [params setValue:appDelegate.user forKey:@"user"];
  356. //// // if(appDelegate.contact_id!=nil)
  357. //// // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  358. //// if(appDelegate.password!=nil)
  359. //// [params setValue:appDelegate.password forKey:@"password"];
  360. //
  361. //
  362. // [params setValue:[AESCrypt AES128Encrypt:appDelegate.user key:@"usai2010"] forKey:@"user"];
  363. // [params setValue:[AESCrypt AES128Encrypt:appDelegate.password key:@"usai2010"] forKey:@"password"];
  364. //
  365. // [params setValue:@"deviceMain" forKey:@"_operate"];
  366. //
  367. //
  368. // UIDevice * dev = [UIDevice currentDevice];
  369. // NSUUID* uuid =dev.identifierForVendor;
  370. //#if TARGET_IPHONE_SIMULATOR//模拟器
  371. // [params setValue:@"simulator_uuid" forKey:@"deviceid"];
  372. //#elif TARGET_OS_IPHONE//真机
  373. // [params setValue:uuid.UUIDString forKey:@"deviceid"];
  374. //#endif
  375. //
  376. //
  377. //
  378. // NSMutableString *body=[[NSMutableString alloc]init];
  379. // //参数的集合的所有key的集合
  380. // NSArray *keys= [params allKeys];
  381. // DebugLog(@"================parms==================");
  382. // //遍历keys
  383. // for(int i=0;i<[keys count];i++)
  384. // {
  385. // //得到当前key
  386. // NSString *key=[keys objectAtIndex:i];
  387. // //如果key不是pic,说明value是字符类型,比如name:Boris
  388. // if(![key isEqualToString:@"pic"])
  389. // {
  390. //// //添加分界线,换行
  391. //// [body appendFormat:@"%@\r\n",MPboundary];
  392. // //添加字段名称,换2行
  393. // [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  394. // //添加字段的值
  395. // [body appendFormat:@"%@\r\n",[params objectForKey:key]];
  396. // DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  397. // }
  398. // }
  399. // DebugLog(@"================parms==================");
  400. //
  401. // NSData* data = [NSData dataWithContentsOfFile: zipfile];
  402. //
  403. // NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_PDF parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  404. // [formData appendPartWithFileData:data name:@"upfile" fileName:[zipfile lastPathComponent] mimeType:@"application/zip"];
  405. // } error:nil];
  406. //
  407. //
  408. // // NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  409. // // [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test" mimeType:@"image/png"];
  410. // // } error:nil];
  411. // //
  412. // AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  413. //
  414. //
  415. //
  416. // //manager.responseSerializer.acceptableContentTypes = [self.operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
  417. //
  418. // //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
  419. //
  420. // //
  421. // NSProgress *progress = nil;
  422. //
  423. // NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  424. //
  425. // // [progress removeObserver:self forKeyPath:@"fractionCompleted"];
  426. //
  427. //
  428. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  429. //
  430. // if (error) {
  431. //
  432. // NSString* err_msg = [error localizedDescription];
  433. // DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  434. //
  435. //
  436. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  437. //
  438. // DebugLog(@"data string: %@",str);
  439. // [RAUtils message_alert:@"Can not connect to server please try again." title:@"Save document" controller:weakSelf] ;
  440. //
  441. // } else {
  442. // DebugLog(@"response ");
  443. //
  444. //
  445. //
  446. // NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  447. //
  448. // // 再将NSData转为字符串
  449. // NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  450. //
  451. // // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  452. //
  453. // DebugLog(@"data string: %@",jsonStr);
  454. //
  455. // NSDictionary* json = responseObject;
  456. //
  457. //
  458. //
  459. //
  460. // if([[json valueForKey:@"result"] intValue]==2)
  461. // {
  462. //
  463. // [weakSelf.navigationController popToRootViewControllerAnimated:false];
  464. ////
  465. ////
  466. // if(weakSelf.OnSave)
  467. // weakSelf.OnSave(pdffile);
  468. //
  469. //
  470. // }
  471. // else
  472. // {
  473. // [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Save document" controller:self] ;
  474. // }
  475. //
  476. //
  477. // }
  478. // // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  479. // }];
  480. //
  481. //
  482. //
  483. //
  484. // // [self.uploadProgress setProgressWithUploadProgressOfTask:uploadTask animated:true];
  485. // //
  486. //
  487. //
  488. //
  489. //
  490. //
  491. //
  492. // [uploadTask resume];
  493. //
  494. // }
  495. // }
  496. // [PDFUtils savep
  497. }
  498. -(void) addSignature :(UIImage*) img to:(NSMutableDictionary*)signatureData
  499. {
  500. if(true)
  501. {
  502. NSString* newfile=[self saveTempSignature:UIImagePNGRepresentation(img)];
  503. int newidx = [self.signatureData[@"count"] intValue];
  504. // [@"file"]= newfile;
  505. NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
  506. item[@"file"]=newfile;
  507. signatureData[[NSString stringWithFormat:@"item_%d",newidx]] = item;
  508. signatureData[@"count"]=[NSNumber numberWithInt:newidx+1];
  509. }
  510. }
  511. -(NSString *) saveTempSignature:(NSData *) image
  512. {
  513. NSString* tempDir = NSTemporaryDirectory();
  514. NSString *saveFileName=[NSString stringWithFormat:@"%@.png",[[NSUUID UUID ] UUIDString] ] ;
  515. NSString *newFilePath=[tempDir stringByAppendingPathComponent:saveFileName];
  516. bool bsuccess=[image writeToFile:newFilePath atomically:YES];
  517. if(bsuccess)
  518. {
  519. return newFilePath;
  520. }
  521. else
  522. {
  523. return nil;
  524. }
  525. }
  526. /*
  527. #pragma mark - Navigation
  528. // In a storyboard-based application, you will often want to do a little preparation before navigation
  529. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  530. // Get the new view controller using [segue destinationViewController].
  531. // Pass the selected object to the new view controller.
  532. }
  533. */
  534. - (PageViewController *)viewControllerAtIndex:(NSUInteger)index
  535. {
  536. //Return the PDFViewController for the given index.
  537. if ((self.total_page == 0 )|| (index > self.total_page) ) {
  538. return nil;
  539. }
  540. //Create a new view controller and pass suitable data.
  541. // PageViewController *PageViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PageViewController"];
  542. PageViewController *PageViewController = [[UIStoryboard storyboardWithName:@"Test" bundle:nil] instantiateViewControllerWithIdentifier:@"PageViewController"];
  543. PageViewController.pageRef = CGPDFDocumentGetPage (self.document , index+1);
  544. PageViewController.pageIndex = index;
  545. __weak typeof(self) weakSelf = self;
  546. PageViewController.blk_Fill = ^(NSString* file,NSString* subtype,bool fillFullDoc)
  547. {
  548. for(int i=0;i<[weakSelf.controlTemplate[@"count"] intValue];i++)
  549. {
  550. NSMutableDictionary* page =weakSelf.controlTemplate[[NSString stringWithFormat:@"page_%d",i]];
  551. if(!fillFullDoc && i!=weakSelf.current_page)
  552. continue;
  553. for(int j=0;j<[page[@"count"] intValue];j++)
  554. {
  555. NSMutableDictionary* dest =page[[NSString stringWithFormat:@"control_%d",j]];
  556. NSString* type = dest[@"type"];
  557. if(![type isEqualToString:@"Signature"])
  558. continue;
  559. if([dest[@"name"] isEqualToString:subtype])
  560. {
  561. dest[@"value"]=file;
  562. }
  563. }
  564. }
  565. // NSString* file_name=[file lastPathComponent];
  566. //
  567. // NSData* img_data=[ImageUtils load_img:file];
  568. //
  569. // if(img_data!=nil)
  570. // {
  571. //
  572. // UIImage* image=[UIImage imageWithData:img_data];
  573. // touchImageView.image = image;
  574. //
  575. // long index = touchImageView.tag - CONTROL_BASE;
  576. // self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
  577. //
  578. // }
  579. };
  580. PageViewController.controlTemplate = self.controlTemplate[[NSString stringWithFormat:@"page_%lu",(unsigned long)index]];
  581. PageViewController.signatureData = self.signatureData;
  582. //PageViewController.pdfview = [self.pagePDF objectAtIndex:index];
  583. /*
  584. PageViewController.pdfview = [[PDFView alloc]initWithFrame:self.view.frame atPage:index];
  585. [PageViewController.view addSubview:PageViewController.pdfview];
  586. NSLog(@"index = %d",index);
  587. */
  588. return PageViewController;
  589. }
  590. - (NSUInteger) indexOfViewController:(PageViewController *)viewController
  591. {
  592. return viewController.pageIndex;//[self.pagePDF indexOfObject:viewController.pdfview];
  593. }
  594. #pragma mark verify data
  595. - (UIView *)createDemoView:(NSString*) msg
  596. {
  597. UIView *demoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 290, 200)];
  598. // UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 270, 180)];
  599. // [imageView setImage:[UIImage imageNamed:@"demo"]];
  600. UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 270, 10)];
  601. titleLabel.font = [UIFont boldSystemFontOfSize:20];
  602. titleLabel.text=@"Please complete missing fields:";
  603. titleLabel.numberOfLines = 0;
  604. titleLabel.lineBreakMode =NSLineBreakByWordWrapping;
  605. // titleLabel.textAlignment = NSTextAlignmentRight;
  606. titleLabel.textAlignment = NSTextAlignmentCenter;
  607. CGSize constraintkey = CGSizeMake(270, 20000.0f);//key label width is 40% cell width;
  608. CGSize sizetitle = [@"Please complete missing fields:" sizeWithFont:[UIFont systemFontOfSize:20.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
  609. //[titleLabel sizeToFit];
  610. // titleLabel.center.x = demoView.center.x;
  611. titleLabel.frame = CGRectMake(10, 10, 270, sizetitle.height);
  612. [demoView addSubview:titleLabel];
  613. UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, titleLabel.frame.origin.y+ titleLabel.frame.size.height+20, 260, 10)];
  614. lineLabel.font = [UIFont boldSystemFontOfSize:17];
  615. lineLabel.text=msg;
  616. lineLabel.numberOfLines = 0;
  617. lineLabel.lineBreakMode =NSLineBreakByWordWrapping;
  618. constraintkey = CGSizeMake(260, 20000.0f);
  619. CGSize sizemsg = [msg sizeWithFont:[UIFont boldSystemFontOfSize:17.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
  620. lineLabel.frame = CGRectMake(15, titleLabel.frame.origin.y+ titleLabel.frame.size.height+20, 260, sizemsg.height);
  621. //[lineLabel sizeToFit];
  622. [demoView addSubview:lineLabel];
  623. demoView.frame = CGRectMake(0, 0, 290, lineLabel.frame.origin.y+lineLabel.frame.size.height+25);
  624. return demoView;
  625. }
  626. -(bool) verifyData
  627. {
  628. if(NO_SAVE_VERIFY)
  629. return true;
  630. // return true;
  631. bool ret=true;
  632. int more=0;
  633. NSMutableArray* fields=[[NSMutableArray alloc] init];
  634. for(int i=0;i<[self.controlTemplate[@"count"] intValue];i++)
  635. {
  636. NSMutableDictionary* page =self.controlTemplate[[NSString stringWithFormat:@"page_%d",i]];
  637. for(int j=0;j<[page[@"count"] intValue];j++)
  638. {
  639. NSMutableDictionary* control =page[[NSString stringWithFormat:@"control_%d",j]];
  640. NSString* type = control[@"type"];
  641. NSString* name = control[@"aname"];
  642. bool required = [control[@"required"] boolValue];
  643. if(required==false)
  644. continue;
  645. if([type isEqualToString:@"Check"])
  646. {
  647. NSArray* arr = control[@"value"];
  648. if(arr.count==0)
  649. {
  650. ret=false;
  651. NSString* msg=[NSString stringWithFormat:@"%u Page %d %@ is missing.",fields.count+1,i+1,name];
  652. if(fields.count<15)
  653. [fields addObject:msg];
  654. else
  655. more++;
  656. }
  657. }
  658. else if(/*[type isEqualToString:@"Signature"]||*/[type isEqualToString:@"Image"]||[type isEqualToString:@"Label"])
  659. {
  660. continue;
  661. }
  662. else
  663. {
  664. NSString* str = control[@"value"];
  665. if(str.length==0)
  666. {
  667. ret=false;
  668. NSString* msg=[NSString stringWithFormat:@"%lu Page %d %@ is missing.",fields.count+1,i+1,name];
  669. if(fields.count<15)
  670. [fields addObject:msg];
  671. else
  672. more++;
  673. }
  674. }
  675. }
  676. }
  677. if(ret==false)
  678. {
  679. if(more>0)
  680. {
  681. NSString* msg=[NSString stringWithFormat:@"And %d more missing field.",more];
  682. [fields addObject:@"......"];
  683. [fields addObject:msg];
  684. }
  685. NSString* missfields=[fields componentsJoinedByString:@"\n"];
  686. NSString* msg = [NSString stringWithFormat:@"%@",missfields];
  687. CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
  688. // Add some custom content to the alert view
  689. [alertView setContainerView:[self createDemoView:msg]];
  690. // Modify the parameters
  691. [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"OK", nil]];
  692. //[alertView setDelegate:self];
  693. // You may use a Block, rather than a delegate.
  694. [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
  695. // DebugLog(@"Block: Button at position %d is clicked on alertView %d.", buttonIndex, (int)[alertView tag]);
  696. [alertView close];
  697. }];
  698. // [alertView setUseMotionEffects:true];
  699. // And launch the dialog
  700. [alertView sizeToFit];
  701. [alertView show];
  702. }
  703. return ret;
  704. }
  705. #pragma mark - Page View Controller Data Source
  706. - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
  707. {
  708. NSUInteger index = [self indexOfViewController:(PageViewController *)viewController];
  709. if ((index == 0 ) || (index == NSNotFound)){
  710. return nil;
  711. }
  712. index--;
  713. self.current_page= index;
  714. return [self viewControllerAtIndex:index];
  715. }
  716. - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
  717. {
  718. NSUInteger index = [self indexOfViewController:(PageViewController *)viewController];
  719. if (index == NSNotFound)
  720. {
  721. return nil;
  722. }
  723. index++;
  724. if (index == self.total_page){
  725. return nil;
  726. }
  727. self.current_page= index;
  728. return [self viewControllerAtIndex:index];
  729. }
  730. #pragma mark - UIPageViewController delegate methods
  731. - (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation {
  732. if (true||UIInterfaceOrientationIsPortrait(orientation) || ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)) {
  733. // In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here.
  734. UIViewController *currentViewController = self.pageViewController.viewControllers[0];
  735. NSArray *viewControllers = @[currentViewController];
  736. [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
  737. self.pageViewController.doubleSided = NO;
  738. return UIPageViewControllerSpineLocationMin;
  739. }
  740. // // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers.
  741. // PageViewController *currentViewController = self.pageViewController.viewControllers[0];
  742. // NSArray *viewControllers = nil;
  743. //
  744. // NSUInteger indexOfCurrentViewController = [self indexOfViewController:currentViewController];
  745. // if (indexOfCurrentViewController == 0 || indexOfCurrentViewController % 2 == 0) {
  746. // UIViewController *nextViewController = [self pageViewController:self.pageViewController viewControllerAfterViewController:currentViewController];
  747. // viewControllers = @[currentViewController, nextViewController];
  748. // } else {
  749. // UIViewController *previousViewController = [self pageViewController:self.pageViewController viewControllerBeforeViewController:currentViewController];
  750. // viewControllers = @[previousViewController, currentViewController];
  751. // }
  752. // [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
  753. //
  754. //
  755. // return UIPageViewControllerSpineLocationMid;
  756. }
  757. @end