DocumentPageViewController.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. @interface DocumentPageViewController ()
  21. @end
  22. @implementation DocumentPageViewController
  23. - (void)viewDidLoad {
  24. [super viewDidLoad];
  25. // self.delegate = self;
  26. // self.dataSource = self;
  27. self.signatureData= [[NSMutableDictionary alloc] init];
  28. self.document = [PDFUtils OpenPDF:self.pdfName];
  29. self.total_page = CGPDFDocumentGetNumberOfPages (self.document);
  30. self.controlTemplate = [PDFUtils loadControl:self.templateName];
  31. PageViewController* startingViewController=[self viewControllerAtIndex:0];
  32. // NSArray* viewControllers =[NSArray arrayWithObjects:page_0,nil];
  33. self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
  34. self.pageViewController.delegate = self;
  35. // PageViewController *startingViewController = [self viewControllerAtIndex:0 storyboard:self.storyboard];
  36. NSArray *viewControllers = @[startingViewController];
  37. [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
  38. self.pageViewController.dataSource = self;
  39. [self addChildViewController:self.pageViewController];
  40. [self.view addSubview:self.pageViewController.view];
  41. // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
  42. CGRect pageViewRect = self.view.bounds;
  43. if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
  44. pageViewRect = pageViewRect;//CGRectInset(pageViewRect, 40.0, 40.0);
  45. }
  46. self.pageViewController.view.frame = pageViewRect;
  47. [self.pageViewController didMoveToParentViewController:self];
  48. // Do any additional setup after loading the view.
  49. }
  50. -(void) dealloc
  51. {
  52. CFBridgingRelease(self.document);
  53. }
  54. - (void)didReceiveMemoryWarning {
  55. [super didReceiveMemoryWarning];
  56. // Dispose of any resources that can be recreated.
  57. }
  58. - (IBAction)onSignatureClicked:(id)sender {
  59. // CGRect cellrect_screen = [RAUtils relativeFrameForScreenWithView:trigger];
  60. //
  61. //
  62. // CGRect rect1=[self.view convertRect:cellrect_screen fromView:[[[UIApplication sharedApplication] delegate] window]];
  63. //
  64. // DebugLog(@"convert1 %@",NSStringFromCGRect(rect1));
  65. SignatureListViewController *signatureVC = [ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureListViewController"];
  66. signatureVC.title=@"Signatures";
  67. signatureVC.signatureData = self.signatureData;
  68. signatureVC.blk_Add = ^()
  69. {
  70. __block UIImage* signimg=nil;
  71. SignatureViewController * vc =[ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureViewController"];
  72. vc.onReturnImg = ^(UIImage* img)
  73. {
  74. signimg = img;
  75. if(signimg!=nil)
  76. [PDFUtils addSignature:signimg to:self.signatureData];
  77. //[self addSignature:signimg];
  78. };
  79. // orderinfoVC.url_type = URL_REMOTE;
  80. // orderinfoVC.request_url=URL_CARTDELIVERY;
  81. //
  82. // orderinfoVC.params = params;
  83. //
  84. // orderinfoVC.delegate=self;
  85. //
  86. // if(checked.count==count)
  87. // {
  88. // orderinfoVC.have_tail = true
  89. // }
  90. [self.navigationController pushViewController:vc animated:true];
  91. };
  92. UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:signatureVC];
  93. navi.modalPresentationStyle=UIModalPresentationPopover;
  94. UIPopoverPresentationController* popPc = navi.popoverPresentationController;
  95. popPc.permittedArrowDirections = UIPopoverArrowDirectionUp;
  96. popPc.barButtonItem = sender;
  97. popPc.delegate = nil;
  98. [self presentViewController:navi animated:true completion:nil];
  99. //// menu.selector = self.selector;
  100. ////
  101. //// menu.selectordelegate = self;
  102. //
  103. // // 1.创建一个UIPopover
  104. // UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:[[UINavigationController alloc] initWithRootViewController:menu]];
  105. //
  106. //
  107. //
  108. // UIPopoverPresentationController
  109. // // 2.设置尺寸
  110. // // popover.popoverContentSize = CGSizeMake(320, 44 * 5);
  111. //
  112. // // 3.从哪里显示出来 --> 指向item
  113. //
  114. // [popover presentPopoverFromRect:self.view.frame inView:self.view permittedArrowDirections:0 animated:YES];
  115. // // [popover presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
  116. //
  117. //// self.popover = popover;
  118. // popover pop
  119. //
  120. // [self performSegueWithIdentifier:@"selector_popover" sender:self];
  121. }
  122. - (IBAction)onSaveClicked:(id)sender {
  123. __weak typeof(self) weakSelf = self;
  124. NSString* pdffile = [PDFUtils SavePDF:self.controlTemplate source:self.document window_rect:CGRectMake(0, 0, 768, 960)];
  125. NSString* zipfile=[ACNetwork prepareUploadFile:pdffile json:self.controlTemplate];
  126. // return;
  127. {
  128. UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Saving"];
  129. // self.uploadProgress.progress = 0;
  130. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  131. {
  132. // UIAlertView * waitalert = [[UIAlertView alloc] initWithTitle:@"wait" message:@"uploading" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  133. // [waitalert show];
  134. // NSData *imageData = UIImagePNGRepresentation(self.imgview.image);
  135. AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  136. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  137. if(appDelegate.user!=nil)
  138. [params setValue:appDelegate.user forKey:@"user"];
  139. // if(appDelegate.contact_id!=nil)
  140. // [params setValue:appDelegate.contact_id forKey:@"contactId"];
  141. if(appDelegate.password!=nil)
  142. [params setValue:appDelegate.password forKey:@"password"];
  143. [params setValue:@"deviceMain" forKey:@"_operate"];
  144. UIDevice * dev = [UIDevice currentDevice];
  145. NSUUID* uuid =dev.identifierForVendor;
  146. #if TARGET_IPHONE_SIMULATOR//模拟器
  147. [params setValue:@"simulator_uuid" forKey:@"deviceid"];
  148. #elif TARGET_OS_IPHONE//真机
  149. [params setValue:uuid.UUIDString forKey:@"deviceid"];
  150. #endif
  151. NSMutableString *body=[[NSMutableString alloc]init];
  152. //参数的集合的所有key的集合
  153. NSArray *keys= [params allKeys];
  154. DebugLog(@"================parms==================");
  155. //遍历keys
  156. for(int i=0;i<[keys count];i++)
  157. {
  158. //得到当前key
  159. NSString *key=[keys objectAtIndex:i];
  160. //如果key不是pic,说明value是字符类型,比如name:Boris
  161. if(![key isEqualToString:@"pic"])
  162. {
  163. // //添加分界线,换行
  164. // [body appendFormat:@"%@\r\n",MPboundary];
  165. //添加字段名称,换2行
  166. [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
  167. //添加字段的值
  168. [body appendFormat:@"%@\r\n",[params objectForKey:key]];
  169. DebugLog(@"parameter: key=%@ value=%@",key,[params objectForKey:key]);
  170. }
  171. }
  172. DebugLog(@"================parms==================");
  173. NSData* data = [NSData dataWithContentsOfFile: zipfile];
  174. NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_PDF parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  175. [formData appendPartWithFileData:data name:@"upfile" fileName:[zipfile lastPathComponent] mimeType:@"application/zip"];
  176. } error:nil];
  177. // NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  178. // [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test" mimeType:@"image/png"];
  179. // } error:nil];
  180. //
  181. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  182. //manager.responseSerializer.acceptableContentTypes = [self.operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
  183. //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
  184. //
  185. NSProgress *progress = nil;
  186. NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  187. // [progress removeObserver:self forKeyPath:@"fractionCompleted"];
  188. [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  189. if (error) {
  190. NSString* err_msg = [error localizedDescription];
  191. DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  192. NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  193. DebugLog(@"data string: %@",str);
  194. [RAUtils message_alert:@"Can not connect to server please try again." title:@"Upload Image" controller:self] ;
  195. } else {
  196. DebugLog(@"response ");
  197. NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  198. // 再将NSData转为字符串
  199. NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  200. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  201. DebugLog(@"data string: %@",jsonStr);
  202. NSDictionary* json = responseObject;
  203. if([[json valueForKey:@"result"] intValue]==2)
  204. {
  205. [weakSelf.navigationController popToRootViewControllerAnimated:false];
  206. //
  207. //
  208. if(weakSelf.OnSave)
  209. weakSelf.OnSave(pdffile);
  210. }
  211. else
  212. {
  213. [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Upload Image" controller:self] ;
  214. }
  215. }
  216. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  217. }];
  218. // [self.uploadProgress setProgressWithUploadProgressOfTask:uploadTask animated:true];
  219. //
  220. [uploadTask resume];
  221. }
  222. }
  223. // [PDFUtils savep
  224. }
  225. -(void) addSignature :(UIImage*) img to:(NSMutableDictionary*)signatureData
  226. {
  227. if(true)
  228. {
  229. NSString* newfile=[self saveTempSignature:UIImagePNGRepresentation(img)];
  230. int newidx = [self.signatureData[@"count"] intValue];
  231. // [@"file"]= newfile;
  232. NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
  233. item[@"file"]=newfile;
  234. signatureData[[NSString stringWithFormat:@"item_%d",newidx]] = item;
  235. signatureData[@"count"]=[NSNumber numberWithInt:newidx+1];
  236. }
  237. }
  238. -(NSString *) saveTempSignature:(NSData *) image
  239. {
  240. NSString* tempDir = NSTemporaryDirectory();
  241. NSString *saveFileName=[NSString stringWithFormat:@"%@.png",[[NSUUID UUID ] UUIDString] ] ;
  242. NSString *newFilePath=[tempDir stringByAppendingPathComponent:saveFileName];
  243. bool bsuccess=[image writeToFile:newFilePath atomically:YES];
  244. if(bsuccess)
  245. {
  246. return newFilePath;
  247. }
  248. else
  249. {
  250. return nil;
  251. }
  252. }
  253. /*
  254. #pragma mark - Navigation
  255. // In a storyboard-based application, you will often want to do a little preparation before navigation
  256. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  257. // Get the new view controller using [segue destinationViewController].
  258. // Pass the selected object to the new view controller.
  259. }
  260. */
  261. - (PageViewController *)viewControllerAtIndex:(NSUInteger)index
  262. {
  263. //Return the PDFViewController for the given index.
  264. if ((self.total_page == 0 )|| (index > self.total_page) ) {
  265. return nil;
  266. }
  267. //Create a new view controller and pass suitable data.
  268. PageViewController *PageViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PageViewController"];
  269. PageViewController.pageRef = CGPDFDocumentGetPage (self.document , index+1);
  270. PageViewController.pageIndex = index;
  271. ;
  272. PageViewController.controlTemplate = self.controlTemplate[[NSString stringWithFormat:@"page_%lu",(unsigned long)index]];
  273. PageViewController.signatureData = self.signatureData;
  274. //PageViewController.pdfview = [self.pagePDF objectAtIndex:index];
  275. /*
  276. PageViewController.pdfview = [[PDFView alloc]initWithFrame:self.view.frame atPage:index];
  277. [PageViewController.view addSubview:PageViewController.pdfview];
  278. NSLog(@"index = %d",index);
  279. */
  280. return PageViewController;
  281. }
  282. - (NSUInteger) indexOfViewController:(PageViewController *)viewController
  283. {
  284. return viewController.pageIndex;//[self.pagePDF indexOfObject:viewController.pdfview];
  285. }
  286. #pragma mark - Page View Controller Data Source
  287. - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
  288. {
  289. NSUInteger index = [self indexOfViewController:(PageViewController *)viewController];
  290. if ((index == 0 ) || (index == NSNotFound)){
  291. return nil;
  292. }
  293. index--;
  294. return [self viewControllerAtIndex:index];
  295. }
  296. - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
  297. {
  298. NSUInteger index = [self indexOfViewController:(PageViewController *)viewController];
  299. if (index == NSNotFound)
  300. {
  301. return nil;
  302. }
  303. index++;
  304. if (index == self.total_page){
  305. return nil;
  306. }
  307. return [self viewControllerAtIndex:index];
  308. }
  309. #pragma mark - UIPageViewController delegate methods
  310. - (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation {
  311. if (true||UIInterfaceOrientationIsPortrait(orientation) || ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)) {
  312. // 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.
  313. UIViewController *currentViewController = self.pageViewController.viewControllers[0];
  314. NSArray *viewControllers = @[currentViewController];
  315. [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
  316. self.pageViewController.doubleSided = NO;
  317. return UIPageViewControllerSpineLocationMin;
  318. }
  319. // // 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.
  320. // PageViewController *currentViewController = self.pageViewController.viewControllers[0];
  321. // NSArray *viewControllers = nil;
  322. //
  323. // NSUInteger indexOfCurrentViewController = [self indexOfViewController:currentViewController];
  324. // if (indexOfCurrentViewController == 0 || indexOfCurrentViewController % 2 == 0) {
  325. // UIViewController *nextViewController = [self pageViewController:self.pageViewController viewControllerAfterViewController:currentViewController];
  326. // viewControllers = @[currentViewController, nextViewController];
  327. // } else {
  328. // UIViewController *previousViewController = [self pageViewController:self.pageViewController viewControllerBeforeViewController:currentViewController];
  329. // viewControllers = @[previousViewController, currentViewController];
  330. // }
  331. // [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
  332. //
  333. //
  334. // return UIPageViewControllerSpineLocationMid;
  335. }
  336. @end