Quellcode durchsuchen

eSign

添加模板编辑功能
Ray Zhang vor 8 Jahren
Ursprung
Commit
206e7e9baf

BIN
Ants Contract/AntsContract.xcworkspace/xcuserdata/Ray.xcuserdatad/UserInterfaceState.xcuserstate


+ 116 - 7
Ants Contract/AntsContract/AntsContract/Base.lproj/Main.storyboard

@@ -215,6 +215,54 @@
             </objects>
             <point key="canvasLocation" x="2373" y="-62"/>
         </scene>
+        <!--Template View Controller-->
+        <scene sceneID="J7i-eF-9Sx">
+            <objects>
+                <viewController storyboardIdentifier="TemplateViewController" id="VeE-j2-f2V" customClass="TemplateViewController" sceneMemberID="viewController">
+                    <view key="view" contentMode="scaleToFill" id="DPe-e8-0nn">
+                        <rect key="frame" x="0.0" y="0.0" width="768" height="1024"/>
+                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                        <subviews>
+                            <scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" maximumZoomScale="3" id="pzg-Ru-RVP" customClass="PDFScrollView">
+                                <rect key="frame" x="0.0" y="64" width="768" height="960"/>
+                                <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                                <subviews>
+                                    <view tag="1024" contentMode="scaleToFill" id="ZDg-DZ-YJ5">
+                                        <rect key="frame" x="0.0" y="0.0" width="768" height="960"/>
+                                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                                        <subviews>
+                                            <view contentMode="scaleToFill" id="vhq-zu-ya0" customClass="PDFPageView">
+                                                <rect key="frame" x="0.0" y="0.0" width="768" height="960"/>
+                                                <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                                                <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="calibratedRGB"/>
+                                            </view>
+                                            <view contentMode="scaleToFill" id="wQP-TO-G9n">
+                                                <rect key="frame" x="0.0" y="0.0" width="768" height="961"/>
+                                                <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                                            </view>
+                                        </subviews>
+                                        <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
+                                    </view>
+                                </subviews>
+                                <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
+                                <connections>
+                                    <outlet property="delegate" destination="VeE-j2-f2V" id="Aoy-Rt-VM1"/>
+                                </connections>
+                            </scrollView>
+                        </subviews>
+                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="calibratedRGB"/>
+                    </view>
+                    <toolbarItems/>
+                    <connections>
+                        <outlet property="editControlView" destination="wQP-TO-G9n" id="0hR-gT-1IN"/>
+                        <outlet property="pdfPageView" destination="vhq-zu-ya0" id="JE7-su-FGX"/>
+                        <outlet property="pdfScrollView" destination="pzg-Ru-RVP" id="HOE-Aq-Fte"/>
+                    </connections>
+                </viewController>
+                <placeholder placeholderIdentifier="IBFirstResponder" id="kAd-fD-OZc" userLabel="First Responder" sceneMemberID="firstResponder"/>
+            </objects>
+            <point key="canvasLocation" x="3582" y="-62"/>
+        </scene>
         <!--Title-->
         <scene sceneID="8dr-IV-sOm">
             <objects>
@@ -343,11 +391,11 @@
                                         <rect key="frame" x="0.0" y="28" width="360" height="44"/>
                                         <autoresizingMask key="autoresizingMask"/>
                                         <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="v4l-du-pTm" id="JkA-pY-NIV">
-                                            <rect key="frame" x="0.0" y="0.0" width="360" height="44"/>
+                                            <rect key="frame" x="0.0" y="0.0" width="360" height="43.5"/>
                                             <autoresizingMask key="autoresizingMask"/>
                                             <subviews>
                                                 <label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="Ofv-pg-h2w">
-                                                    <rect key="frame" x="15" y="0.0" width="330" height="43"/>
+                                                    <rect key="frame" x="15" y="0.0" width="330" height="43.5"/>
                                                     <autoresizingMask key="autoresizingMask"/>
                                                     <fontDescription key="fontDescription" type="system" pointSize="16"/>
                                                     <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
@@ -469,7 +517,7 @@
                                         <rect key="frame" x="0.0" y="28" width="768" height="128"/>
                                         <autoresizingMask key="autoresizingMask"/>
                                         <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="KmC-hR-Rfo" id="twt-7p-gUd">
-                                            <rect key="frame" x="0.0" y="0.0" width="768" height="128"/>
+                                            <rect key="frame" x="0.0" y="0.0" width="768" height="127.5"/>
                                             <autoresizingMask key="autoresizingMask"/>
                                             <subviews>
                                                 <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" misplaced="YES" text="GE2016121201" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="eH3-OQ-M6Q">
@@ -783,18 +831,18 @@
                                         <rect key="frame" x="0.0" y="28" width="540" height="44"/>
                                         <autoresizingMask key="autoresizingMask"/>
                                         <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="K5M-kB-Cox" id="8bB-hy-1xQ">
-                                            <rect key="frame" x="0.0" y="0.0" width="540" height="43"/>
+                                            <rect key="frame" x="0.0" y="0.0" width="540" height="43.5"/>
                                             <autoresizingMask key="autoresizingMask"/>
                                             <subviews>
                                                 <label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="93T-5h-JKV">
-                                                    <rect key="frame" x="15" y="5" width="33" height="21"/>
+                                                    <rect key="frame" x="15" y="5" width="33.5" height="20.5"/>
                                                     <autoresizingMask key="autoresizingMask"/>
                                                     <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                     <nil key="textColor"/>
                                                     <nil key="highlightedColor"/>
                                                 </label>
                                                 <label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Subtitle" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="mtf-OD-AFL">
-                                                    <rect key="frame" x="15" y="26" width="44" height="14"/>
+                                                    <rect key="frame" x="15" y="25.5" width="44" height="14.5"/>
                                                     <autoresizingMask key="autoresizingMask"/>
                                                     <fontDescription key="fontDescription" type="system" pointSize="12"/>
                                                     <nil key="textColor"/>
@@ -1091,7 +1139,7 @@
                                         <rect key="frame" x="0.0" y="28" width="768" height="44"/>
                                         <autoresizingMask key="autoresizingMask"/>
                                         <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bC4-0A-Qjh" id="rna-0d-wd1">
-                                            <rect key="frame" x="0.0" y="0.0" width="768" height="44"/>
+                                            <rect key="frame" x="0.0" y="0.0" width="768" height="43.5"/>
                                             <autoresizingMask key="autoresizingMask"/>
                                             <subviews>
                                                 <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" misplaced="YES" text="GE2016121201" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="5Tt-7m-QFz">
@@ -1156,6 +1204,67 @@
             </objects>
             <point key="canvasLocation" x="2916" y="-4145"/>
         </scene>
+        <!--document template-->
+        <scene sceneID="Raz-l7-66H">
+            <objects>
+                <viewController storyboardIdentifier="DocumentTemplateViewController" title="document template" useStoryboardIdentifierAsRestorationIdentifier="YES" id="IrJ-nO-Jqx" customClass="DocumentTemplateViewController" sceneMemberID="viewController">
+                    <view key="view" contentMode="scaleToFill" id="YvY-Uw-Cr6">
+                        <rect key="frame" x="0.0" y="0.0" width="768" height="1024"/>
+                        <autoresizingMask key="autoresizingMask" flexibleMinX="YES" widthSizable="YES" flexibleMaxX="YES" flexibleMinY="YES" heightSizable="YES" flexibleMaxY="YES"/>
+                        <subviews>
+                            <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="middleTruncation" id="YRy-cf-b04">
+                                <rect key="frame" x="20" y="472" width="80" height="80"/>
+                                <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES" flexibleMaxY="YES"/>
+                                <state key="normal" title="Button" image="left_arrow"/>
+                                <connections>
+                                    <action selector="onLeftButtonClick:" destination="IrJ-nO-Jqx" eventType="touchUpInside" id="G4D-xx-5E6"/>
+                                </connections>
+                            </button>
+                            <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="middleTruncation" id="tuM-sI-7IN">
+                                <rect key="frame" x="668" y="472" width="80" height="80"/>
+                                <autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMinY="YES" flexibleMaxY="YES"/>
+                                <state key="normal" title="Button" image="right_arrow"/>
+                                <connections>
+                                    <action selector="onRightButtonClick:" destination="IrJ-nO-Jqx" eventType="touchUpInside" id="dEM-hq-dkP"/>
+                                </connections>
+                            </button>
+                            <view contentMode="scaleToFill" misplaced="YES" id="w7G-eF-IRC">
+                                <rect key="frame" x="26" y="696" width="717" height="308"/>
+                                <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
+                                <subviews>
+                                    <stepper opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" verticalHuggingPriority="750" misplaced="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" maximumValue="100" id="861-cb-EzK">
+                                        <rect key="frame" x="354" y="140" width="94" height="29"/>
+                                        <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
+                                    </stepper>
+                                </subviews>
+                                <color key="backgroundColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
+                            </view>
+                        </subviews>
+                        <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
+                    </view>
+                    <navigationItem key="navigationItem" title="Title" id="TOR-BH-g4o">
+                        <barButtonItem key="leftBarButtonItem" title="Cancel" id="G4j-IK-wnq">
+                            <connections>
+                                <action selector="OnCancelClicked:" destination="IrJ-nO-Jqx" id="AFC-fh-zfa"/>
+                            </connections>
+                        </barButtonItem>
+                        <barButtonItem key="rightBarButtonItem" title="Save" id="lAX-gb-VMT">
+                            <connections>
+                                <action selector="onSaveClicked:" destination="IrJ-nO-Jqx" id="VzS-lI-DPQ"/>
+                            </connections>
+                        </barButtonItem>
+                    </navigationItem>
+                    <simulatedNavigationBarMetrics key="simulatedTopBarMetrics" prompted="NO"/>
+                    <connections>
+                        <outlet property="ibSave" destination="lAX-gb-VMT" id="KOn-7l-p52"/>
+                        <outlet property="left_button" destination="YRy-cf-b04" id="3xH-Ve-tNp"/>
+                        <outlet property="right_button" destination="tuM-sI-7IN" id="sVX-vn-m7h"/>
+                    </connections>
+                </viewController>
+                <placeholder placeholderIdentifier="IBFirstResponder" id="83E-Gv-ZLo" userLabel="First Responder" sceneMemberID="firstResponder"/>
+            </objects>
+            <point key="canvasLocation" x="1217" y="1102"/>
+        </scene>
     </scenes>
     <resources>
         <image name="NewDoc" width="100" height="100"/>

+ 12 - 0
Ants Contract/Granite Expo eSign/Granite Expo eSign.xcodeproj/project.pbxproj

@@ -71,6 +71,8 @@
 		71B152EF1E66C87F00D2E5EC /* AddExtDocumentViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 71B152EE1E66C87F00D2E5EC /* AddExtDocumentViewController.m */; };
 		71BBFC371E6419D4008668A7 /* ExtDocumentsViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 71BBFC361E6419D4008668A7 /* ExtDocumentsViewController.m */; };
 		71BBFC3A1E651CC4008668A7 /* DocnotesViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 71BBFC391E651CC4008668A7 /* DocnotesViewController.m */; };
+		71CDA0901F75EE400079F8E6 /* DocumentTemplateViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 71CDA08F1F75EE400079F8E6 /* DocumentTemplateViewController.m */; };
+		71CDA0931F75EEBF0079F8E6 /* TemplateViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 71CDA0921F75EEBF0079F8E6 /* TemplateViewController.m */; };
 		71D5734D1F7220FE008179ED /* GEIC - Home Improvement Contract 2017 Desktop.pdf in Resources */ = {isa = PBXBuildFile; fileRef = 71D5734C1F7220FE008179ED /* GEIC - Home Improvement Contract 2017 Desktop.pdf */; };
 		71D5734F1F723260008179ED /* GEIC - Home Improvement Contract 2017 Desktop.json in Resources */ = {isa = PBXBuildFile; fileRef = 71D5734E1F723260008179ED /* GEIC - Home Improvement Contract 2017 Desktop.json */; };
 		71F8D0341EC057A2002003DB /* RANetworkTaskDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 71F8D0331EC057A2002003DB /* RANetworkTaskDelegate.m */; };
@@ -200,6 +202,10 @@
 		71BBFC361E6419D4008668A7 /* ExtDocumentsViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = ExtDocumentsViewController.m; path = ../../common/ExtDocumentsViewController.m; sourceTree = "<group>"; };
 		71BBFC381E651CC4008668A7 /* DocnotesViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DocnotesViewController.h; path = ../../common/DocnotesViewController.h; sourceTree = "<group>"; };
 		71BBFC391E651CC4008668A7 /* DocnotesViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = DocnotesViewController.m; path = ../../common/DocnotesViewController.m; sourceTree = "<group>"; };
+		71CDA08E1F75EE400079F8E6 /* DocumentTemplateViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DocumentTemplateViewController.h; sourceTree = "<group>"; };
+		71CDA08F1F75EE400079F8E6 /* DocumentTemplateViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DocumentTemplateViewController.m; sourceTree = "<group>"; };
+		71CDA0911F75EEBF0079F8E6 /* TemplateViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TemplateViewController.h; sourceTree = "<group>"; };
+		71CDA0921F75EEBF0079F8E6 /* TemplateViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = TemplateViewController.m; sourceTree = "<group>"; };
 		71D5734C1F7220FE008179ED /* GEIC - Home Improvement Contract 2017 Desktop.pdf */ = {isa = PBXFileReference; lastKnownFileType = image.pdf; path = "GEIC - Home Improvement Contract 2017 Desktop.pdf"; sourceTree = "<group>"; };
 		71D5734E1F723260008179ED /* GEIC - Home Improvement Contract 2017 Desktop.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = "GEIC - Home Improvement Contract 2017 Desktop.json"; sourceTree = "<group>"; };
 		71F8D0321EC057A2002003DB /* RANetworkTaskDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RANetworkTaskDelegate.h; path = ../../../common/upload/RANetworkTaskDelegate.h; sourceTree = "<group>"; };
@@ -366,6 +372,10 @@
 				7128C3451E12545C00FF635B /* DocumentPageViewController.m */,
 				7128C3481E12548C00FF635B /* PageViewController.h */,
 				7128C3491E12548C00FF635B /* PageViewController.m */,
+				71CDA08E1F75EE400079F8E6 /* DocumentTemplateViewController.h */,
+				71CDA08F1F75EE400079F8E6 /* DocumentTemplateViewController.m */,
+				71CDA0911F75EEBF0079F8E6 /* TemplateViewController.h */,
+				71CDA0921F75EEBF0079F8E6 /* TemplateViewController.m */,
 				7128C34A1E12548C00FF635B /* PDFPageView.h */,
 				7128C34B1E12548C00FF635B /* PDFPageView.m */,
 				7128C34C1E12548C00FF635B /* PDFScrollView.h */,
@@ -577,8 +587,10 @@
 				714A9AEC1E9CA92000371995 /* PendingDocumentsViewController.m in Sources */,
 				7128C28E1E12501B00FF635B /* TouchImageView.m in Sources */,
 				7128C2B41E1250CA00FF635B /* GridDrawable.m in Sources */,
+				71CDA0931F75EEBF0079F8E6 /* TemplateViewController.m in Sources */,
 				7115D4561E1606F700EF4E4C /* GEContractFilterViewController.m in Sources */,
 				7128C2DA1E12510900FF635B /* unzip.c in Sources */,
+				71CDA0901F75EE400079F8E6 /* DocumentTemplateViewController.m in Sources */,
 				7128C2981E12504300FF635B /* PDFViewController.m in Sources */,
 				7128C2CB1E1250FC00FF635B /* RAUtils.m in Sources */,
 				7128C2C81E1250FC00FF635B /* TextUtils.m in Sources */,

+ 35 - 0
Ants Contract/Granite Expo eSign/Granite Expo eSign/DocumentTemplateViewController.h

@@ -0,0 +1,35 @@
+//
+//  DocumentTemplateViewController.h
+//  Granite Expo eSign
+//
+//  Created by Ray on 23/09/2017.
+//  Copyright © 2017 United Software Applications, Inc. All rights reserved.
+//
+
+#import <UIKit/UIKit.h>
+typedef NS_ENUM(NSInteger, PDFEditAction) {
+    PDFEditActionNew = 0,
+    PDFEditActionModify = 1
+};
+@interface DocumentTemplateViewController : UIViewController<UIPageViewControllerDelegate , UIPageViewControllerDataSource>
+@property (weak, nonatomic) IBOutlet UIButton *left_button;
+@property (weak, nonatomic) IBOutlet UIButton *right_button;
+
+@property (strong, nonatomic) UIPageViewController *pageViewController;
+@property (strong, nonatomic) NSMutableDictionary * controlTemplate;
+@property size_t total_page;
+@property CGPDFDocumentRef document;
+@property (strong, nonatomic) NSMutableDictionary* signatureData;
+@property (assign, nonatomic) bool  hide_control;
+@property (assign, nonatomic) bool  no_save;
+@property (strong, nonatomic) NSString* pdfPath;//pdfName;
+@property (strong, nonatomic) NSString* templatePath;//templateName;
+
+@property (weak, nonatomic) IBOutlet UIBarButtonItem *ibSave;
+@property (strong, nonatomic) NSString* docment_id;
+@property long current_page;
+
+@property (nonatomic , copy) void (^OnSave)(NSString * file, NSString* subject );
+@property (assign) PDFEditAction action;
+
+@end

+ 1237 - 0
Ants Contract/Granite Expo eSign/Granite Expo eSign/DocumentTemplateViewController.m

@@ -0,0 +1,1237 @@
+//
+//  DocumentTemplateViewController.m
+//  Granite Expo eSign
+//
+//  Created by Ray on 23/09/2017.
+//  Copyright © 2017 United Software Applications, Inc. All rights reserved.
+//
+
+#import "DocumentTemplateViewController.h"
+
+#import "TemplateViewController.h"
+#import "SignatureListViewController.h"
+#import "SignatureViewController.h"
+#import "PDFUtils.h"
+#import "ACNetwork.h"
+
+//#import "AFHTTPSessionManager.h"
+#import "AppDelegate.h"
+#import "ACNetwork.h"
+#import "RAUtils.h"
+#import "PDFViewController.h"
+#import "config.h"
+#import "AESCrypt.h"
+#import "CustomIOSAlertView.h"
+
+#import "ImageUtils.h"
+
+#import "PDFPage.h"
+
+#import "TextDrawable.h"
+#import "ImageDrawable.h"
+#import "RectDrawable.h"
+@interface DocumentTemplateViewController ()
+
+@end
+
+@implementation DocumentTemplateViewController
+
+
+
+- (IBAction)onLeftButtonClick:(id)sender {
+    
+    
+    //    - (NSUInteger) indexOfViewController:(PageViewController *)viewController
+    
+    UIViewController* pvc = [self pageViewController:self.pageViewController viewControllerBeforeViewController:self.pageViewController.viewControllers[0]];
+    
+    if(pvc==nil)
+    return;
+    
+    
+    __weak typeof(self) weakSelf = self;
+    [self.pageViewController setViewControllers:@[pvc] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:^(BOOL finished){
+        
+        long index=[weakSelf indexOfViewController:(TemplateViewController*)pvc];
+        if(index==0)
+        weakSelf.left_button.hidden=true;
+        else
+        weakSelf.left_button.hidden=false;
+        
+        if(index==weakSelf.total_page-1)
+        weakSelf.right_button.hidden=true;
+        else
+        weakSelf.right_button.hidden=false;
+    }];
+    
+    //    self.pageViewController
+}
+- (IBAction)onRightButtonClick:(id)sender {
+    
+    UIViewController* pvc = [self pageViewController:self.pageViewController viewControllerAfterViewController:self.pageViewController.viewControllers[0]];
+    
+    if(pvc==nil)
+    return;
+    
+    
+    __weak typeof(self) weakSelf = self;
+    [self.pageViewController setViewControllers:@[pvc] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:^(BOOL finished){
+        
+        long index=[weakSelf indexOfViewController:(TemplateViewController*)pvc];
+        if(index==0)
+        weakSelf.left_button.hidden=true;
+        else
+        weakSelf.left_button.hidden=false;
+        
+        if(index==weakSelf.total_page-1)
+        weakSelf.right_button.hidden=true;
+        else
+        weakSelf.right_button.hidden=false;
+    }];
+    
+}
+
+-(NSMutableDictionary*) templateInit:(NSMutableDictionary*) template
+{
+    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
+    
+    NSString* temp = NSTemporaryDirectory();
+    NSString* filename =[NSString stringWithFormat:@"%@.png", [[NSUUID UUID] UUIDString]];
+    NSString* qrpath=[temp stringByAppendingPathComponent:filename];
+    UIImage* qrimg=[ImageUtils generateBarCode:self.docment_id width:300 height:44];//[QRCodeGenerator qrImageForString:order_code imageSize:240];
+    
+    
+    bool bwrite=[UIImagePNGRepresentation(qrimg)writeToFile: qrpath    atomically:YES];
+    
+    
+    
+    for(int i=0;i<[template[@"count"] intValue];i++)
+    {
+        NSMutableDictionary* page =template[[NSString stringWithFormat:@"page_%d",i]];
+        for(int j=0;j<[page[@"count"] intValue];j++)
+        {
+            NSMutableDictionary* control =page[[NSString stringWithFormat:@"control_%d",j]];
+            NSString* type = control[@"type"];
+            NSString* field =control[@"field"];
+            bool disable = [control[@"disable"] boolValue];
+            control[@"dirty"]=[NSNumber numberWithBool:false];
+            if([type isEqualToString:@"Label"])
+            {
+                if([field isEqualToString:@"doc_number"])
+                {
+                    control[@"value"]= self.docment_id;
+                }
+            }
+            else if([type isEqualToString:@"Image"])
+            {
+                NSString* name =control[@"name"];
+                if([name isEqualToString:@"BarCode"])
+                {
+                    if(bwrite)
+                    control[@"value"]= qrpath;
+                }
+            }
+            else if([type isEqualToString:@"DatePicker"])
+            {
+                NSString* name =control[@"aname"];
+                if([name isEqualToString:@"Today's Date"]||[name isEqualToString:@"Handwrite date"])
+                {
+                    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
+                    [formatter setDateFormat:@"MM/dd/yyyy"];
+                    NSString* date = [formatter stringFromDate:[NSDate date]] ;
+                    
+                    control[@"value"]= date;
+                }
+            }
+            else if([type isEqualToString:@"Signature"]&&disable)
+            {
+                control[@"value"]= appDelegate.na_path;
+                
+            }
+            else if([type isEqualToString:@"TextView"])
+            {
+                NSString* name =control[@"aname"];
+                if([name isEqualToString:@"Agent Name"]||[name isEqualToString:@"Sales Person"])
+                {
+                    control[@"value"]= appDelegate.agentName;
+                }
+                
+                
+                
+            }
+        }
+    }
+    return template;
+}
+-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
+{
+    
+}
+- (void)viewDidLoad {
+    [super viewDidLoad];
+    self.title = self.docment_id;
+    
+    if(self.hide_control)
+    [self.ibSave setTitle:@"Upload"];
+    else
+    [self.ibSave setTitle:@"Save"];
+    
+    
+    
+    //    self.delegate = self;
+    //    self.dataSource = self;
+    
+    // 修复初始化时视图向下偏移64点
+    UIView *v = [[UIView alloc] init];
+    [self.view insertSubview:v atIndex:0];
+    
+    self.signatureData= [[NSMutableDictionary alloc] init];
+    
+    
+    self.document = [PDFUtils OpenPDF:self.pdfPath];
+    self.total_page = CGPDFDocumentGetNumberOfPages (self.document);
+    self.controlTemplate = [self templateInit:[PDFUtils loadControl:self.templatePath]];
+    
+    
+    //    self.title = [NSString stringWithFormat:@"%@ [%d/%ld]", self.docment_id,1, self.total_page ];
+    
+    
+    TemplateViewController* startingViewController=[self viewControllerAtIndex:0];
+    
+    // NSArray* viewControllers =[NSArray arrayWithObjects:page_0,nil];
+    
+    self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
+    self.pageViewController.delegate = self;
+    
+    //    PageViewController *startingViewController = [self viewControllerAtIndex:0 storyboard:self.storyboard];
+    NSArray *viewControllers = @[startingViewController];
+    
+    
+    
+    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
+    
+    self.pageViewController.dataSource = self;
+    
+    [self addChildViewController:self.pageViewController];
+    [self.view addSubview:self.pageViewController.view];
+    
+    // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
+    CGRect pageViewRect = self.view.bounds;
+    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
+        pageViewRect = pageViewRect;//CGRectInset(pageViewRect, 40.0, 40.0);
+    }
+    self.pageViewController.view.frame = pageViewRect;
+    
+    [self.pageViewController didMoveToParentViewController:self];
+    
+    self.left_button.hidden=true;
+    
+    self.right_button.hidden=false;
+    
+    
+    [self.view bringSubviewToFront:self.left_button];
+    [self.view bringSubviewToFront:self.right_button];
+    // Do any additional setup after loading the view.
+}
+-(void) dealloc
+{
+    CFRelease(self.document);
+}
+- (void)didReceiveMemoryWarning {
+    [super didReceiveMemoryWarning];
+    // Dispose of any resources that can be recreated.
+}
+
+- (IBAction)OnCancelClicked:(id)sender {
+    
+    
+    if(self.no_save|| self.hide_control)
+    {
+        [self.navigationController popViewControllerAnimated:false];
+        return;
+    }
+    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Are you sure to cancel the customer ? You will loose all the information you entered." message:nil preferredStyle:UIAlertControllerStyleAlert];
+    
+    UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
+        [self.navigationController popViewControllerAnimated:false];
+    }];
+    // [alertControl addAction:actionOne];
+    
+    [alertControl addAction:alertthree];
+    
+    
+    UIAlertAction *alertcancel = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
+    }];
+    [alertControl addAction:alertcancel];
+    //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
+    
+    
+    
+    
+    [self presentViewController:alertControl animated:YES completion:nil];
+}
+- (IBAction)onSignatureClicked:(id)sender {
+    
+    //    CGRect cellrect_screen = [RAUtils relativeFrameForScreenWithView:trigger];
+    //
+    //
+    //    CGRect rect1=[self.view convertRect:cellrect_screen fromView:[[[UIApplication sharedApplication] delegate] window]];
+    //
+    //    DebugLog(@"convert1 %@",NSStringFromCGRect(rect1));
+    SignatureListViewController *signatureVC = [ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureListViewController"];
+    signatureVC.title=@"Signatures";
+    signatureVC.signatureData = self.signatureData;
+    
+    
+    signatureVC.blk_Add = ^()
+    {
+        
+        __block UIImage* signimg=nil;
+        SignatureViewController * vc =[ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureViewController"];
+        
+        vc.onReturnImg = ^(UIImage* img)
+        {
+            
+            
+            signimg = img;
+            
+            //            if(signimg!=nil)
+            //                [PDFUtils addSignature:signimg to:self.signatureData];
+            
+            
+            
+            
+        };
+        
+        //    orderinfoVC.url_type = URL_REMOTE;
+        //    orderinfoVC.request_url=URL_CARTDELIVERY;
+        //
+        //    orderinfoVC.params = params;
+        //
+        //    orderinfoVC.delegate=self;
+        //
+        //    if(checked.count==count)
+        //    {
+        //    orderinfoVC.have_tail = true
+        //    }
+        
+        [self.navigationController pushViewController:vc animated:true];
+        
+        
+        
+    };
+    
+    //    signatureVC.blk_Fill =^(NSString* file, bool fillFullDoc)
+    //    {
+    //
+    //
+    //        for(int i=0;i<[self.controlTemplate[@"count"] intValue];i++)
+    //        {
+    //            NSMutableDictionary* page =self.controlTemplate[[NSString stringWithFormat:@"page_%d",i]];
+    //            if(!fillFullDoc && i!=self.current_page)
+    //                continue;
+    //            for(int j=0;j<[page[@"count"] intValue];j++)
+    //            {
+    //                NSMutableDictionary* control =page[[NSString stringWithFormat:@"control_%d",j]];
+    //                NSString* type = control[@"type"];
+    //                if(![type isEqualToString:@"Signature"])
+    //                    continue;
+    //
+    //                control[@"value"]=file;
+    //
+    ////                NSString* name = control[@"aname"];
+    ////                bool required = [control[@"required"] boolValue];
+    ////
+    ////                if(required==false)
+    ////                    continue;
+    ////                if([type isEqualToString:@"Check"])
+    ////                {
+    ////                    NSArray* arr = control[@"value"];
+    ////                    if(arr.count==0)
+    ////                    {
+    ////                        ret=false;
+    ////
+    ////                        NSString* msg=[NSString stringWithFormat:@"%u Page %d %@ is missing.",fields.count+1,i+1,name];
+    ////                        if(fields.count<15)
+    ////                            [fields addObject:msg];
+    ////                        else
+    ////                            more++;
+    ////                    }
+    ////
+    ////                }
+    ////                else if(/*[type isEqualToString:@"Signature"]||*/[type isEqualToString:@"Image"]||[type isEqualToString:@"Label"])
+    ////                {
+    ////                    continue;
+    ////                }
+    ////                else
+    ////                {
+    ////                    NSString* str = control[@"value"];
+    ////                    if(str.length==0)
+    ////                    {
+    ////                        ret=false;
+    ////                        NSString* msg=[NSString stringWithFormat:@"%lu Page %d %@ is missing.",fields.count+1,i+1,name];
+    ////                        if(fields.count<15)
+    ////                            [fields addObject:msg];
+    ////                        else
+    ////                            more++;
+    ////                    }
+    ////                }
+    //            }
+    //        }
+    //
+    //
+    //        //            NSString* file_name=[file lastPathComponent];
+    ////
+    ////        NSData* img_data=[ImageUtils load_img:file];
+    ////
+    ////        if(img_data!=nil)
+    ////        {
+    ////
+    ////            UIImage* image=[UIImage imageWithData:img_data];
+    ////            touchImageView.image = image;
+    ////
+    ////            long index = touchImageView.tag - CONTROL_BASE;
+    ////            self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
+    ////
+    ////        }
+    //
+    //    };
+    
+    UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:signatureVC];
+    navi.modalPresentationStyle=UIModalPresentationPopover;
+    
+    UIPopoverPresentationController* popPc = navi.popoverPresentationController;
+    popPc.permittedArrowDirections = UIPopoverArrowDirectionUp;
+    popPc.barButtonItem = sender;
+    popPc.delegate = nil;
+    
+    
+    
+    [self presentViewController:navi animated:true completion:nil];
+    
+    ////    menu.selector = self.selector;
+    ////
+    ////    menu.selectordelegate = self;
+    //
+    //    // 1.创建一个UIPopover
+    //    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:[[UINavigationController alloc] initWithRootViewController:menu]];
+    //
+    //
+    //
+    //    UIPopoverPresentationController
+    //    // 2.设置尺寸
+    //    //    popover.popoverContentSize = CGSizeMake(320, 44 * 5);
+    //
+    //    // 3.从哪里显示出来 --> 指向item
+    //
+    //    [popover presentPopoverFromRect:self.view.frame   inView:self.view permittedArrowDirections:0 animated:YES];
+    //    //  [popover presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
+    //
+    ////    self.popover = popover;
+    //    popover pop
+    //
+    // [self performSegueWithIdentifier:@"selector_popover" sender:self];
+    
+}
+-(CGRect)WindowRect2PDFRect:(CGRect)rect pdf_rect:(CGRect)pdf_rect window_size:(CGSize)window_size
+{
+    CGRect pdf_expand;
+    float offset_x = 0;
+    float offset_y = 0;
+    float scale =1;
+    if(pdf_rect.size.height>=pdf_rect.size.width)
+    {
+        pdf_expand = CGRectMake(0, 0, pdf_rect.size.height*window_size.width/window_size.height, pdf_rect.size.height);
+        offset_x = (pdf_expand.size.width-pdf_rect.size.width)/2;
+        scale = pdf_rect.size.height/window_size.height;
+        
+    }
+    else
+    {
+        pdf_expand = CGRectMake(0, 0, pdf_rect.size.width, pdf_rect.size.width*window_size.height/window_size.width);
+        offset_y = (pdf_expand.size.height-pdf_rect.size.height)/2;
+        scale = pdf_rect.size.width/window_size.width;
+    }
+    float x=rect.origin.x*scale-offset_x;
+    float y=rect.origin.y*scale-offset_y;
+    float width = rect.size.width*scale;
+    float height = rect.size.height*scale;
+    
+    return CGRectMake(x, y, width, height);
+    
+}
+-(void) EndEditing
+{
+    
+    
+    NSArray* arr =self.pageViewController.viewControllers;
+    
+    TemplateViewController *currentViewController = (TemplateViewController*)self.pageViewController.viewControllers[0];
+    //    PageViewController *currentViewController = (PageViewController*)self.pageViewController.viewControllers[self.current_page];
+    [currentViewController EndEditing];
+}
+
+- (IBAction)onSaveClicked:(id)sender {
+    
+    [self EndEditing];
+    if(self.no_save)
+    {
+        [RAUtils message_alert:@"Can not save pending document under offline mode." title:@"Save document" controller:self] ;
+        return;
+    }
+    
+    if([self verifyData]==false)
+    return;
+    
+    NSString* pdffile = nil;
+    NSString* zipfile = nil;
+    NSString* jsonfile = nil;
+    // for(int l=0;l<1;l++)
+    {
+        
+        if(self.hide_control)
+        {
+            pdffile = self.pdfPath;
+        }
+        else
+        {
+            pdffile = [PDFUtils SavePDF:self.controlTemplate source:self.document window_rect:CGRectMake(0, 0, 768, 960) name:self.docment_id isnew:self.action==PDFEditActionNew];
+        }
+        
+        zipfile=[ACNetwork prepareUploadFile:pdffile json:self.controlTemplate];
+        
+        //jsonfile = [ACNetwork getjsonPath:zip];
+        
+    }
+    
+    __weak typeof(self) weakSelf = self;
+    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
+    if(appDelegate.accessMode == AppAccessModeOffline)
+    {
+        
+        NSMutableDictionary * json = [[NSMutableDictionary alloc]init];
+        
+        json[@"json"]=@"json.json";
+        json[@"pdf"]=pdffile.lastPathComponent;
+        json[@"zip"]=zipfile.lastPathComponent;
+        json[@"serial"]=[json[@"zip"] stringByDeletingPathExtension];
+        
+        
+        
+        json[@"create_by"]=appDelegate.user;
+        
+        
+        json[@"agent_name"]=[self extract_data:@"agent_name"];
+        json[@"doc_number"]=[self extract_data:@"doc_number"];
+        json[@"job_date"]=[self extract_data:@"job_date"];
+        json[@"customer_name"]=[self extract_data:@"customer_name"];
+        json[@"signed_date"]=[self extract_data:@"signed_date"];
+        
+        
+        
+        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
+        NSMutableArray * arr_pending = [[defaults arrayForKey:@"pending_doc"] mutableCopy];
+        if(arr_pending==nil)
+        arr_pending = [[NSMutableArray alloc]init];
+        [arr_pending addObject:json];
+        [defaults setObject:arr_pending forKey:@"pending_doc"];
+        [defaults synchronize];
+        
+        
+        [weakSelf.navigationController popViewControllerAnimated:false];
+        if(weakSelf.OnSave)
+        weakSelf.OnSave(pdffile,@"");
+        
+    }
+    else
+    {
+        UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Saving"];
+        
+        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
+            
+            NSDictionary* json = nil;
+            
+            
+            
+            json = [ACNetwork save_document:zipfile isnew:self.action==PDFEditActionNew];
+            
+            dispatch_async(dispatch_get_main_queue(), ^{
+                
+                
+                [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
+                //                if([[logout_json valueForKey:@"result"] intValue]==2)
+                //                {
+                //                    self.welcomeLabel.text=@"Not sign in";
+                //                    //                        [sender setTitle:@"Sign in" forState:UIControlStateNormal];
+                //                    [bbitem setTitle:@"Sign in"];
+                //
+                //                    self.buttonHIC.enabled = false;
+                //                    self.buttonSRL.enabled = false;
+                //                    self.coverView.hidden = false;
+                //                }
+                //                else
+                //                {
+                //                    [RAUtils message_alert:[logout_json valueForKey:@"err_msg"] title:@"Sign out" controller:self] ;
+                //                }
+                
+                if([[json valueForKey:@"result"] intValue]==2)
+                {
+                    
+                    
+                    [weakSelf.navigationController popViewControllerAnimated:false];
+                    if(weakSelf.OnSave)
+                    weakSelf.OnSave(pdffile,json[@"subject"]);
+                    
+                    
+                }
+                else
+                {
+                    //                    [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Save document" controller:self] ;
+                    
+                    if(self.hide_control)
+                    {
+                        //提交离线合同
+                        [RAUtils message_alert:@"Can not upload pending documents please try again later." title:@"Save document" controller:self] ;
+                        return;
+                    }
+                    
+                    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Create Customer" message:@"Can not create new customer on server, do you want to create an offline document?" preferredStyle:UIAlertControllerStyleAlert];
+                    
+                    
+                    UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
+                        __block NSString* offline_docnumber =[ACNetwork offline_docnumber];
+                        if(offline_docnumber==nil)
+                        {
+                            [RAUtils message_alert:@"Offline document number prefix not found, Please check your user name and make sure you had signed in at least once."  title:@"Create Customer" controller:self] ;
+                            return;
+                        }
+                        [appDelegate SwitchToOffline:appDelegate.user];
+                        
+                        
+                        NSMutableDictionary * json = [[NSMutableDictionary alloc]init];
+                        
+                        json[@"json"]=@"json.json";
+                        json[@"pdf"]=pdffile.lastPathComponent;
+                        json[@"zip"]=zipfile.lastPathComponent;
+                        json[@"serial"]=[json[@"zip"] stringByDeletingPathExtension];
+                        
+                        
+                        
+                        json[@"create_by"]=appDelegate.user;
+                        
+                        
+                        json[@"agent_name"]=[self extract_data:@"agent_name"];
+                        json[@"doc_number"]=[self extract_data:@"doc_number"];
+                        json[@"job_date"]=[self extract_data:@"job_date"];
+                        json[@"customer_name"]=[self extract_data:@"customer_name"];
+                        json[@"signed_date"]=[self extract_data:@"signed_date"];
+                        
+                        
+                        
+                        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
+                        NSMutableArray * arr_pending = [[defaults arrayForKey:@"pending_doc"] mutableCopy];
+                        if(arr_pending==nil)
+                        arr_pending = [[NSMutableArray alloc]init];
+                        [arr_pending addObject:json];
+                        [defaults setObject:arr_pending forKey:@"pending_doc"];
+                        [defaults synchronize];
+                        
+                        
+                        [weakSelf.navigationController popViewControllerAnimated:false];
+                        if(weakSelf.OnSave)
+                        weakSelf.OnSave(pdffile,@"");
+                        
+                        
+                    }];
+                    
+                    UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
+                        DebugLog(@"Cancel");
+                    }];
+                    [alertControl addAction:actionOne];
+                    
+                    [alertControl addAction:alertthree];
+                    
+                    //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
+                    
+                    
+                    [self presentViewController:alertControl animated:YES completion:nil];
+                    
+                }
+                
+                
+            });
+        });
+    }
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    //  return;
+    
+    //    {
+    //
+    //
+    //        UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Saving"];
+    //
+    //
+    ////        self.uploadProgress.progress = 0;
+    //
+    //        AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
+    //
+    //
+    //        {
+    //
+    //            //    UIAlertView * waitalert = [[UIAlertView alloc] initWithTitle:@"wait" message:@"uploading" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
+    //            //    [waitalert show];
+    //
+    ////            NSData *imageData = UIImagePNGRepresentation(self.imgview.image);
+    //
+    //            AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
+    //
+    //
+    //
+    //            NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
+    //
+    ////            if(appDelegate.user!=nil)
+    ////                [params setValue:appDelegate.user forKey:@"user"];
+    ////            //    if(appDelegate.contact_id!=nil)
+    ////            //        [params setValue:appDelegate.contact_id forKey:@"contactId"];
+    ////            if(appDelegate.password!=nil)
+    ////                [params setValue:appDelegate.password forKey:@"password"];
+    //
+    //
+    //            [params setValue:[AESCrypt AES128Encrypt:appDelegate.user  key:@"usai2010"] forKey:@"user"];
+    //            [params setValue:[AESCrypt AES128Encrypt:appDelegate.password  key:@"usai2010"] forKey:@"password"];
+    //
+    //            [params setValue:@"deviceMain" forKey:@"_operate"];
+    //
+    //
+    //            UIDevice * dev = [UIDevice currentDevice];
+    //            NSUUID* uuid =dev.identifierForVendor;
+    //#if TARGET_IPHONE_SIMULATOR//模拟器
+    //            [params setValue:@"simulator_uuid" forKey:@"deviceid"];
+    //#elif TARGET_OS_IPHONE//真机
+    //            [params setValue:uuid.UUIDString forKey:@"deviceid"];
+    //#endif
+    //
+    //
+    //
+    //            NSMutableString *body=[[NSMutableString alloc]init];
+    //            //参数的集合的所有key的集合
+    //            NSArray *keys= [params allKeys];
+    //            DebugLog(@"================parms==================");
+    //            //遍历keys
+    //            for(int i=0;i<[keys count];i++)
+    //            {
+    //                //得到当前key
+    //                NSString *key=[keys objectAtIndex:i];
+    //                //如果key不是pic,说明value是字符类型,比如name:Boris
+    //                if(![key isEqualToString:@"pic"])
+    //                {
+    ////                    //添加分界线,换行
+    ////                    [body appendFormat:@"%@\r\n",MPboundary];
+    //                    //添加字段名称,换2行
+    //                    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
+    //                    //添加字段的值
+    //                    [body appendFormat:@"%@\r\n",[params objectForKey:key]];
+    //                    DebugLog(@"parameter: key=%@   value=%@",key,[params objectForKey:key]);
+    //                }
+    //            }
+    //            DebugLog(@"================parms==================");
+    //
+    //            NSData* data = [NSData dataWithContentsOfFile: zipfile];
+    //
+    //            NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_PDF parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
+    //                [formData appendPartWithFileData:data name:@"upfile" fileName:[zipfile lastPathComponent] mimeType:@"application/zip"];
+    //            } error:nil];
+    //
+    //
+    //            //        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
+    //            //            [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test" mimeType:@"image/png"];
+    //            //        } error:nil];
+    //            //
+    //            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
+    //
+    //
+    //
+    //            //manager.responseSerializer.acceptableContentTypes = [self.operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
+    //
+    //            //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
+    //
+    //            //
+    //            NSProgress *progress = nil;
+    //
+    //            NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
+    //
+    //                //        [progress removeObserver:self forKeyPath:@"fractionCompleted"];
+    //
+    //
+    //                 [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
+    //
+    //                if (error) {
+    //
+    //                    NSString* err_msg = [error localizedDescription];
+    //                    DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
+    //
+    //
+    //                    NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
+    //
+    //                    DebugLog(@"data string: %@",str);
+    //                    [RAUtils message_alert:@"Can not connect to server please try again." title:@"Save document" controller:weakSelf] ;
+    //
+    //                } else {
+    //                    DebugLog(@"response ");
+    //
+    //
+    //
+    //                    NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
+    //
+    //                    // 再将NSData转为字符串
+    //                    NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
+    //
+    //                    //            NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
+    //
+    //                    DebugLog(@"data string: %@",jsonStr);
+    //
+    //                    NSDictionary* json = responseObject;
+    //
+    //
+    //
+    //
+    //                    if([[json valueForKey:@"result"] intValue]==2)
+    //                    {
+    //
+    //                        [weakSelf.navigationController popToRootViewControllerAnimated:false];
+    ////
+    ////
+    //                        if(weakSelf.OnSave)
+    //                            weakSelf.OnSave(pdffile);
+    //
+    //
+    //                    }
+    //                    else
+    //                    {
+    //                        [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Save document" controller:self] ;
+    //                    }
+    //
+    //
+    //                }
+    //                //  [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
+    //            }];
+    //
+    //
+    //
+    //
+    //          //  [self.uploadProgress setProgressWithUploadProgressOfTask:uploadTask animated:true];
+    //            //
+    //
+    //
+    //
+    //
+    //
+    //
+    //            [uploadTask resume];
+    //
+    //        }
+    //    }
+    
+    //  [PDFUtils savep
+}
+
+
+-(void) addSignature :(UIImage*) img to:(NSMutableDictionary*)signatureData
+{
+    
+    
+    if(true)
+    {
+        NSString* newfile=[self saveTempSignature:UIImagePNGRepresentation(img)];
+        
+        int newidx = [self.signatureData[@"count"] intValue];
+        
+        // [@"file"]= newfile;
+        
+        NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
+        item[@"file"]=newfile;
+        signatureData[[NSString stringWithFormat:@"item_%d",newidx]] = item;
+        signatureData[@"count"]=[NSNumber numberWithInt:newidx+1];
+        
+        
+        
+    }
+    
+    
+    
+}
+-(NSString *) saveTempSignature:(NSData *) image
+{
+    NSString* tempDir = NSTemporaryDirectory();
+    
+    NSString *saveFileName=[NSString stringWithFormat:@"%@.png",[[NSUUID UUID ] UUIDString] ] ;
+    
+    NSString *newFilePath=[tempDir stringByAppendingPathComponent:saveFileName];
+    
+    
+    bool bsuccess=[image writeToFile:newFilePath atomically:YES];
+    if(bsuccess)
+    {
+        
+        return newFilePath;
+    }
+    else
+    {
+        return nil;
+    }
+    
+}
+/*
+ #pragma mark - Navigation
+ 
+ // In a storyboard-based application, you will often want to do a little preparation before navigation
+ - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
+ // Get the new view controller using [segue destinationViewController].
+ // Pass the selected object to the new view controller.
+ }
+ */
+
+
+- (TemplateViewController *)viewControllerAtIndex:(NSUInteger)index
+{
+    //Return the PDFViewController for the given index.
+    if ((self.total_page == 0 )|| (index > self.total_page) ) {
+        return nil;
+    }
+    
+    //Create a new view controller and pass suitable data.
+    //    PageViewController *PageViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"PageViewController"];
+    TemplateViewController *TemplateViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"TemplateViewController"];
+    
+    TemplateViewController.pageRef =  CGPDFDocumentGetPage (self.document , index+1);
+    TemplateViewController.pageIndex = index;
+    TemplateViewController.hide_control = self.hide_control;
+    
+    __weak typeof(self) weakSelf = self;
+    TemplateViewController.blk_Fill = ^(NSString* file,NSString* subtype,bool fillFullDoc)
+    {
+        
+        
+        for(int i=0;i<[weakSelf.controlTemplate[@"count"] intValue];i++)
+        {
+            NSMutableDictionary* page =weakSelf.controlTemplate[[NSString stringWithFormat:@"page_%d",i]];
+            if(!fillFullDoc && i!=weakSelf.current_page)
+            continue;
+            for(int j=0;j<[page[@"count"] intValue];j++)
+            {
+                NSMutableDictionary* dest =page[[NSString stringWithFormat:@"control_%d",j]];
+                NSString* type = dest[@"type"];
+                if(![type isEqualToString:@"Signature"])
+                continue;
+                
+                if([dest[@"disable"] boolValue])
+                continue;
+                if([dest[@"name"] isEqualToString:subtype])
+                {
+                    dest[@"value"]=file;
+                }
+            }
+        }
+        
+        
+        //            NSString* file_name=[file lastPathComponent];
+        //
+        //        NSData* img_data=[ImageUtils load_img:file];
+        //
+        //        if(img_data!=nil)
+        //        {
+        //
+        //            UIImage* image=[UIImage imageWithData:img_data];
+        //            touchImageView.image = image;
+        //
+        //            long index = touchImageView.tag - CONTROL_BASE;
+        //            self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
+        //
+        //        }
+        
+    };
+    TemplateViewController.page_controlTemplate = self.controlTemplate[[NSString stringWithFormat:@"page_%lu",(unsigned long)index]];
+    TemplateViewController.doc_controlTemplate = self.controlTemplate;
+    TemplateViewController.signatureData = self.signatureData;
+    //PageViewController.pdfview = [self.pagePDF objectAtIndex:index];
+    
+    /*
+     PageViewController.pdfview = [[PDFView alloc]initWithFrame:self.view.frame atPage:index];
+     [PageViewController.view addSubview:PageViewController.pdfview];
+     NSLog(@"index = %d",index);
+     
+     
+     */
+    return TemplateViewController;
+}
+
+- (NSUInteger) indexOfViewController:(TemplateViewController *)viewController
+{
+    return viewController.pageIndex;//[self.pagePDF indexOfObject:viewController.pdfview];
+}
+- (NSString*) extract_data:(NSString*)field_name
+{
+    for(int p=0;p<[self.controlTemplate[@"count"] intValue];p++)
+    {
+        NSDictionary* page=self.controlTemplate[[NSString stringWithFormat:@"page_%d",p]];
+        for(int c=0;c<[page[@"count"] intValue];c++)
+        {
+            NSDictionary* control=page[[NSString stringWithFormat:@"control_%d",c]];
+            if([control[@"field"] isEqualToString:field_name])
+            {
+                return control[@"value"]==nil?@"":control[@"value"];
+            }
+        }
+    }
+    return @"";
+}
+
+
+#pragma mark verify data
+- (UIView *)createDemoView:(NSString*) msg
+{
+    UIView *demoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 290, 200)];
+    
+    //    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 270, 180)];
+    //    [imageView setImage:[UIImage imageNamed:@"demo"]];
+    
+    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 270, 10)];
+    titleLabel.font = [UIFont boldSystemFontOfSize:20];
+    titleLabel.text=@"Missing fields:";
+    titleLabel.numberOfLines = 0;
+    titleLabel.lineBreakMode =NSLineBreakByWordWrapping;
+    //    titleLabel.textAlignment = NSTextAlignmentRight;
+    titleLabel.textAlignment = NSTextAlignmentCenter;
+    CGSize constraintkey = CGSizeMake(270, 20000.0f);//key label width is 40% cell width;
+    CGSize sizetitle = [@"Missing fields:" sizeWithFont:[UIFont systemFontOfSize:20.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
+    
+    //[titleLabel sizeToFit];
+    //    titleLabel.center.x = demoView.center.x;
+    titleLabel.frame = CGRectMake(10, 10, 270, sizetitle.height);
+    [demoView addSubview:titleLabel];
+    
+    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, titleLabel.frame.origin.y+ titleLabel.frame.size.height+20, 260, 10)];
+    lineLabel.font = [UIFont boldSystemFontOfSize:17];
+    lineLabel.text=msg;
+    lineLabel.numberOfLines = 0;
+    lineLabel.lineBreakMode =NSLineBreakByWordWrapping;
+    
+    
+    constraintkey = CGSizeMake(260, 20000.0f);
+    CGSize sizemsg = [msg sizeWithFont:[UIFont boldSystemFontOfSize:17.0] constrainedToSize:constraintkey lineBreakMode:NSLineBreakByWordWrapping];
+    
+    lineLabel.frame = CGRectMake(15, titleLabel.frame.origin.y+ titleLabel.frame.size.height+20, 260, sizemsg.height);
+    //[lineLabel sizeToFit];
+    
+    [demoView addSubview:lineLabel];
+    demoView.frame = CGRectMake(0, 0, 290, lineLabel.frame.origin.y+lineLabel.frame.size.height+25);
+    return demoView;
+}
+-(bool) verifyData
+{
+    
+    if(NO_SAVE_VERIFY)
+    return true;
+    //   return true;
+    bool ret=true;
+    int more=0;
+    NSMutableArray* fields=[[NSMutableArray alloc] init];
+    
+    for(int i=0;i<[self.controlTemplate[@"count"] intValue];i++)
+    {
+        NSMutableDictionary* page =self.controlTemplate[[NSString stringWithFormat:@"page_%d",i]];
+        for(int j=0;j<[page[@"count"] intValue];j++)
+        {
+            NSMutableDictionary* control =page[[NSString stringWithFormat:@"control_%d",j]];
+            NSString* type = control[@"type"];
+            NSString* name = control[@"aname"];
+            bool required = [control[@"required"] boolValue];
+            
+            if(required==false || [type.lowercaseString isEqualToString:@"ignor"])
+            continue;
+            if([type isEqualToString:@"Check"])
+            {
+                NSArray* arr = control[@"value"];
+                if(arr.count==0)
+                {
+                    ret=false;
+                    
+                    NSString* msg=[NSString stringWithFormat:@"%u. Page %d: %@",fields.count+1,i+1,name];
+                    if(fields.count<15)
+                    [fields addObject:msg];
+                    else
+                    more++;
+                }
+                
+            }
+            else if(/*[type isEqualToString:@"Signature"]||*/[type isEqualToString:@"Image"]||[type isEqualToString:@"Label"])
+            {
+                continue;
+            }
+            else
+            {
+                NSString* str = control[@"value"];
+                if(str.length==0)
+                {
+                    ret=false;
+                    NSString* msg=[NSString stringWithFormat:@"%lu. Page %d: %@",fields.count+1,i+1,name];
+                    if(fields.count<15)
+                    [fields addObject:msg];
+                    else
+                    more++;
+                }
+            }
+        }
+    }
+    if(ret==false)
+    {
+        if(more>0)
+        {
+            NSString* msg=[NSString stringWithFormat:@"And %d more missing fields.",more];
+            
+            [fields addObject:@"......"];
+            [fields addObject:msg];
+        }
+        NSString* missfields=[fields componentsJoinedByString:@"\n"];
+        NSString* msg = [NSString stringWithFormat:@"%@",missfields];
+        
+        CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
+        
+        
+        
+        
+        // Add some custom content to the alert view
+        [alertView setContainerView:[self createDemoView:msg]];
+        
+        // Modify the parameters
+        
+        
+        
+        [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"OK", nil]];
+        //[alertView setDelegate:self];
+        
+        // You may use a Block, rather than a delegate.
+        [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
+            //   DebugLog(@"Block: Button at position %d is clicked on alertView %d.", buttonIndex, (int)[alertView tag]);
+            [alertView close];
+        }];
+        
+        //  [alertView setUseMotionEffects:true];
+        
+        // And launch the dialog
+        
+        [alertView sizeToFit];
+        [alertView show];
+        
+        
+    }
+    return ret;
+}
+
+#pragma mark - Page View Controller Data Source
+
+
+- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
+{
+    NSUInteger index = [self indexOfViewController:(TemplateViewController *)viewController];
+    if ((index == 0 ) || (index == NSNotFound)){
+        return nil;
+    }
+    //   self.current_page= index;
+    
+    index--;
+    return  [self viewControllerAtIndex:index];
+}
+
+- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
+{
+    NSUInteger index = [self indexOfViewController:(TemplateViewController *)viewController];
+    if (index == NSNotFound)
+    {
+        return nil;
+    }
+    //    self.current_page= index;
+    
+    index++;
+    
+    if (index == self.total_page){
+        return  nil;
+    }
+    return [self viewControllerAtIndex:index];
+}
+
+
+#pragma mark - UIPageViewController delegate methods
+- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed
+{
+    NSLog(@"didFinishAnimating");
+    
+    
+    
+    long index=[self indexOfViewController:pageViewController.viewControllers[0]];
+    if(index==0)
+    self.left_button.hidden=true;
+    else
+    self.left_button.hidden=false;
+    
+    if(index==self.total_page-1)
+    self.right_button.hidden=true;
+    else
+    self.right_button.hidden=false;
+    //        self.title = [NSString stringWithFormat:@"%@ [%ld/%ld]", self.docment_id,((PageViewController*)self.pageViewController.viewControllers[0]).pageIndex+1, self.total_page ];
+}
+- (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation {
+    if (true||UIInterfaceOrientationIsPortrait(orientation) || ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)) {
+        // 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.
+        
+        UIViewController *currentViewController = self.pageViewController.viewControllers[0];
+        NSArray *viewControllers = @[currentViewController];
+        
+        __weak typeof(self) weakSelf = self;
+        [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:^(BOOL finished){
+            
+            long index=[weakSelf indexOfViewController:(TemplateViewController*)currentViewController];
+            if(index==0)
+            weakSelf.left_button.hidden=true;
+            else
+            weakSelf.left_button.hidden=false;
+            
+            if(index==weakSelf.total_page-1)
+            weakSelf.right_button.hidden=true;
+            else
+            weakSelf.right_button.hidden=false;
+        }];
+        
+        self.pageViewController.doubleSided = NO;
+        return UIPageViewControllerSpineLocationMin;
+    }
+    
+    //    // 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.
+    //    PageViewController *currentViewController = self.pageViewController.viewControllers[0];
+    //    NSArray *viewControllers = nil;
+    //
+    //    NSUInteger indexOfCurrentViewController = [self indexOfViewController:currentViewController];
+    //    if (indexOfCurrentViewController == 0 || indexOfCurrentViewController % 2 == 0) {
+    //        UIViewController *nextViewController = [self pageViewController:self.pageViewController viewControllerAfterViewController:currentViewController];
+    //        viewControllers = @[currentViewController, nextViewController];
+    //    } else {
+    //        UIViewController *previousViewController = [self pageViewController:self.pageViewController viewControllerBeforeViewController:currentViewController];
+    //        viewControllers = @[previousViewController, currentViewController];
+    //    }
+    //    [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];
+    //    
+    //    
+    //    return UIPageViewControllerSpineLocationMid;
+}
+
+
+
+@end

+ 38 - 0
Ants Contract/Granite Expo eSign/Granite Expo eSign/TemplateViewController.h

@@ -0,0 +1,38 @@
+//
+//  TemplateViewController.h
+//  Granite Expo eSign
+//
+//  Created by Ray on 23/09/2017.
+//  Copyright © 2017 United Software Applications, Inc. All rights reserved.
+//
+
+#import <UIKit/UIKit.h>
+#import "PDFPageView.h"
+#import "PDFScrollView.h"
+//#import "EditControlView.h"
+#import "TouchImageView.h"
+
+@interface TemplateViewController : UIViewController<UITextViewDelegate,TouchImageViewDelegate>
+
+@property (strong, nonatomic) IBOutlet PDFPageView *pdfPageView;
+@property (strong, nonatomic) IBOutlet UIView *editControlView;
+@property size_t pageIndex;
+@property CGPDFPageRef pageRef;
+@property (strong, nonatomic) IBOutlet PDFScrollView *pdfScrollView;
+@property (nonatomic , copy) void (^blk_Fill)(NSString* file,NSString* subtype, bool fillFullDoc);
+
+
+@property (strong, nonatomic) NSMutableDictionary * page_controlTemplate;
+@property (strong, nonatomic) NSMutableDictionary * doc_controlTemplate;
+@property (strong, nonatomic) NSMutableDictionary * signatureData;
+@property (strong, nonatomic) UITextView * hotTextView;
+@property bool keyboard_show;
+@property int keyboard_h;
+-(void)EndEditing;
+@property (assign, nonatomic) long  tiv_index;
+@property (assign, nonatomic) bool  hide_control;
+
+- (void)rotateView;
+
+
+@end

+ 2055 - 0
Ants Contract/Granite Expo eSign/Granite Expo eSign/TemplateViewController.m

@@ -0,0 +1,2055 @@
+//
+//  TemplateViewController.m
+//  Granite Expo eSign
+//
+//  Created by Ray on 23/09/2017.
+//  Copyright © 2017 United Software Applications, Inc. All rights reserved.
+//
+
+#import "TemplateViewController.h"
+#define NUMBERS @"0123456789.\n"
+
+
+#import "config.h"
+#import "const.h"
+
+#import "SignatureListViewController.h"
+#import "SignatureViewController.h"
+#import "PDFUtils.h"
+#import "ImageUtils.h"
+#import "TextUtils.h"
+
+#import "CheckSelectorViewController.h"
+#import "DatePickerViewController.h"
+
+#import "RAUtils.h"
+#import "AppDelegate.h"
+
+
+typedef enum {
+    ScreenOrientationUnknown = 0,
+    ScreenOrientationPortrait = 1,
+    ScreenOrientationLand = 3
+}ScreenOrientation;
+@interface TemplateViewController ()
+
+@property (nonatomic,assign) ScreenOrientation orientation;
+@property (nonatomic,assign) ScreenOrientation currentAppOrientation;
+@end
+
+@implementation TemplateViewController
+
+- (BOOL)canBecomeFirstResponder{
+    return YES;
+}
+//- (IBAction)onBtnClick:(id)sender {
+//    [self becomeFirstResponder];
+//    UIView* v = sender;
+//
+//    UIMenuItem *detail = [[UIMenuItem alloc] initWithTitle:@"abc" action:@selector(showDetail:)];
+//    //    [detail setValue:_id forKey:@"_id"];
+//
+//    UIMenuController *menu = [UIMenuController sharedMenuController];
+//
+//    [menu setMenuItems:[NSArray arrayWithObjects:detail, nil]];
+//
+//    [menu setTargetRect:v.frame inView:v.superview];
+//    [menu setMenuVisible:YES animated:YES];
+//}
+
+- (ScreenOrientation)currentAppOrientation {
+    CGSize screenSize = [UIScreen mainScreen].bounds.size;
+    if (screenSize.width > screenSize.height) return ScreenOrientationLand;
+    return ScreenOrientationPortrait;
+}
+
+- (void)viewDidLoad {
+    [super viewDidLoad];
+    
+    //
+    //    self.pdfScrollView = [[PDFScrollView alloc]initWithFrame:CGRectMake(0, 64, 768, 960)];
+    //    self.pdfScrollView.backgroundColor= [UIColor redColor];
+    
+    //self.edgesForExtendedLayout = UIRectEdgeNone;
+    //   self.pageIndex=1;
+    
+    // self.pdfPageView.pageIndex=self.pageIndex;
+    self.pdfPageView.pageRef= self.pageRef;
+    
+    self.pdfScrollView.contentSize = self.pdfScrollView.frame.size;
+    self.keyboard_h=0;
+    //    self.pdfScrollView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
+    //    [self initControl];
+    
+    //    UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]
+    //                                                        initWithTarget:self
+    //                                                        action:@selector(handlePinch:)];
+    //
+    //    [self.view addGestureRecognizer:pinchGestureRecognizer];
+    
+    // Do any additional setup after loading the view.
+    self.orientation = ScreenOrientationUnknown;
+    
+    //    self.pdfScrollView.backgroundColor = [UIColor redColor];
+    //    [self.pdfScrollView viewWithTag:1024].backgroundColor = [UIColor orangeColor];
+    //    self.pdfPageView.backgroundColor = [UIColor yellowColor];
+    //    self.editControlView.backgroundColor = [UIColor colorWithRed:0.4 green:0.8 blue:0.3 alpha:0.5];
+    //
+    //    [self.pdfPageView removeFromSuperview];
+    //    [self.editControlView removeFromSuperview];
+    //    self.view.backgroundColor = [UIColor blueColor];
+}
+-(void)viewWillAppear:(BOOL)animated
+{
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
+    
+    // 键盘高度变化通知,ios5.0新增的
+#ifdef __IPHONE_5_0
+    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
+    if (version >= 5.0) {
+        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
+    }
+#endif
+    
+    //    self.pdfScrollView.contentSize = self.pdfScrollView.frame.size;
+    
+    
+    
+}
+
+- (void)viewDidAppear:(BOOL)animated {
+    [super viewDidAppear:animated];
+    if (self.orientation != ScreenOrientationUnknown) {
+        if (self.orientation == self.currentAppOrientation) {
+            // 修复未完全显示时停止拖动,再进入该页面就不会生成Control控件
+            if (self.editControlView.subviews.count) {
+                [self refreshControl];
+            } else {
+                [self initControl];
+            }
+            
+            
+        } else {
+            [self rotateView];
+        }
+    } else {
+        [self initControl];
+    }
+    [self.parentViewController.view layoutIfNeeded];
+}
+
+
+- (void)viewWillLayoutSubviews {
+    
+    /*
+     *  解决旋转后第二个视图覆盖部分当前视图
+     */
+    
+    [self clearControlView];
+    
+    self.pdfScrollView.scrollEnabled = NO;
+    // root
+    [self updateView:self.view];
+    
+    // scroll
+    [self updateView:self.pdfScrollView];
+    
+    // 1024 view
+    [self updateView:[self.pdfScrollView viewWithTag:1024]];
+    
+    // pdf
+    [self updateView:self.pdfPageView];
+    //            NSLog(@"pdf page frame %@",[NSValue valueWithCGRect:self.pdfPageView.frame]);
+    [self.pdfPageView setNeedsDisplay];
+    
+    // edit
+    [self updateView:self.editControlView];
+    
+    // contentSize
+    self.pdfScrollView.contentSize = [self.pdfScrollView viewWithTag:1024].bounds.size;
+    self.pdfScrollView.contentOffset = CGPointZero;
+    
+    [self initControl];
+    
+    [self.view setNeedsDisplay];
+    
+    self.pdfScrollView.scrollEnabled = YES;
+    
+}
+
+- (void)clearControlView {
+    for (UIView * v in self.editControlView.subviews)
+    {
+        [v removeFromSuperview ];
+    }
+    
+}
+
+- (void)rotateView {
+    
+    if (self.orientation == self.currentAppOrientation) return;
+    [self viewWillLayoutSubviews];
+    
+    self.orientation = self.currentAppOrientation;
+    
+    for (UIViewController *vc in self.parentViewController.childViewControllers) {
+        [vc viewWillLayoutSubviews];
+    }
+    
+}
+
+- (void)updateView:(UIView *)view {
+    //    return;
+    if (!view) return;
+    CGRect frame = [UIScreen mainScreen].bounds;
+    
+    if (view == self.view) {
+        
+    } else if (view == self.pdfScrollView) {
+        frame.origin.y = 64;
+        frame.size.height -= 64;
+        self.pdfScrollView.contentSize = CGSizeZero;
+    } else {
+        frame.size.height -= 64;
+        view.transform = CGAffineTransformIdentity; // 解决缩放后,旋转屏幕。产生偏差(ContentSize和ContentOffset)
+    }
+    
+    view.frame = frame;
+    view.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
+    
+    [view layoutIfNeeded];
+    [view setNeedsDisplay];
+}
+
+-(void) viewWillDisappear:(BOOL)animated
+{
+    [self.hotTextView endEditing:true];
+    [[NSNotificationCenter defaultCenter] removeObserver:self];
+    self.orientation = self.currentAppOrientation;
+    
+}
+-(void) dealloc
+{
+    //   CFBridgingRelease(self.pageRef);
+}
+- (void)didReceiveMemoryWarning {
+    [super didReceiveMemoryWarning];
+    // Dispose of any resources that can be recreated.
+}
+//- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer
+//{
+////    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
+////    recognizer.scale = 1;
+//
+//    CGSize contentsize =self.pdfScrollView.contentSize;
+//
+//    self.pdfScrollView.contentSize = CGSizeMake(contentsize.width*recognizer.scale, contentsize.height*recognizer.scale);
+//}
+
+
+
+//+(CGRect)WindowRect2PDFRect:(CGRect)rect pdf_rect:(CGRect)pdf_rect window_size:(CGSize)window_size
+//{
+//    CGRect pdf_expand;
+//    float offset_x = 0;
+//    float offset_y = 0;
+//    float scale =1;
+//    if(pdf_rect.size.height>=pdf_rect.size.width)
+//    {
+//        pdf_expand = CGRectMake(0, 0, pdf_rect.size.height*window_size.width/window_size.height, pdf_rect.size.height);
+//        offset_x = (pdf_expand.size.width-pdf_rect.size.width)/2;
+//        scale = pdf_rect.size.height/window_size.height;
+//
+//    }
+//    else
+//    {
+//        pdf_expand = CGRectMake(0, 0, pdf_rect.size.width, pdf_rect.size.width*window_size.height/window_size.width);
+//        offset_y = (pdf_expand.size.height-pdf_rect.size.height)/2;
+//        scale = pdf_rect.size.width/window_size.width;
+//    }
+//    float x=rect.origin.x*scale-offset_x;
+//    float y=rect.origin.y*scale-offset_y;
+//    float width = rect.size.width*scale;
+//    float height = rect.size.height*scale;
+//
+//    return CGRectMake(x, y, width, height);
+//
+//}
+
+-(CGRect) scaleControl:(CGRect) frame from:(CGSize)fwindowsize to:(CGSize)twindowsize
+{
+    CGRect pdfsize=CGPDFPageGetBoxRect(self.pageRef, kCGPDFMediaBox);
+    frame=[PDFUtils WindowRect2PDFRect:frame pdf_rect:pdfsize window_size:fwindowsize];
+    
+    frame= [PDFUtils PDFRect2WindowRect:frame pdf_rect:pdfsize window_size:twindowsize];
+    
+    return frame;
+    
+}
+-(void) initControl
+{
+    
+    if(self.hide_control)
+    return;
+    //    return;
+    [self clearControlView]; // fill all时未显示。
+    int count = [self.page_controlTemplate[@"count"] intValue];
+    for(int i=0;i<count;i++)
+    {
+        NSMutableDictionary * control =self.page_controlTemplate [[NSString stringWithFormat:@"control_%d",i] ];
+        if([control[@"type"] isEqualToString:@"TextView"])
+        {
+            [self addTextView:control destView:self.editControlView index:i];
+        }
+        else if([control[@"type"] isEqualToString:@"Button"])
+        {
+            [self addButton:control destView:self.editControlView index:i];
+            
+        }
+        else if([control[@"type"] isEqualToString:@"Check"])
+        {
+            [self addCheck:control destView:self.editControlView index:i];
+            
+        }
+        else if([control[@"type"] isEqualToString:@"Signature"])
+        {
+            [self addSignatureButton:control destView:self.editControlView index:i];
+            
+        }
+        else if([control[@"type"] isEqualToString:@"Image"])
+        {
+            [self addImage:control destView:self.editControlView index:i];
+            
+        }
+        else if([control[@"type"] isEqualToString:@"Label"])
+        {
+            [self addLabel:control destView:self.editControlView index:i];
+            
+        }
+        else if([control[@"type"] isEqualToString:@"DatePicker"])
+        {
+            [self addDatePicker:control destView:self.editControlView index:i];
+            
+        }
+    }
+    
+}
+-(void) refreshControl
+{
+    int count = [self.page_controlTemplate[@"count"] intValue];
+    for(int i=0;i<count;i++)
+    {
+        NSString* controlname =[NSString stringWithFormat:@"control_%d",i];
+        NSMutableDictionary * control =self.page_controlTemplate [ controlname];
+        
+        
+        //        if([control[@"type"] isEqualToString:@"TextView"])
+        //        {
+        //            UITextView* tv = (UITextView*) [self findControl:controlname];
+        //            tv.text = control[@"value"];
+        //        }
+        //        else if([control[@"type"] isEqualToString:@"Button"])
+        //        {
+        //            [self addButton:control destView:self.editControlView index:i];
+        //
+        //        }
+        //        else if([control[@"type"] isEqualToString:@"Check"])
+        //        {
+        //            [self addCheck:control destView:self.editControlView index:i];
+        //
+        //        }
+        //        else
+        if([control[@"type"] isEqualToString:@"Signature"])
+        {
+            TouchImageView* btn = (TouchImageView*) [self findControl:controlname];
+            NSString* file =control[@"value"];
+            
+            NSData* img_data=[ImageUtils load_img:file];
+            
+            if(img_data!=nil)
+            {
+                
+                UIImage* image=[UIImage imageWithData:img_data];
+                btn.image = image;
+                
+            }
+            
+        }
+        //        else if([control[@"type"] isEqualToString:@"Image"])
+        //        {
+        //            [self addImage:control destView:self.editControlView index:i];
+        //
+        //        }
+        //        else if([control[@"type"] isEqualToString:@"Label"])
+        //        {
+        //            [self addLabel:control destView:self.editControlView index:i];
+        //
+        //        }
+        //        else if([control[@"type"] isEqualToString:@"DatePicker"])
+        //        {
+        //            [self addDatePicker:control destView:self.editControlView index:i];
+        //
+        //        }
+    }
+}
+-(void)EndEditing
+{
+    [[self view] endEditing:YES];
+}
+-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
+{
+    if (self.presentedViewController) {
+        [self.presentedViewController dismissViewControllerAnimated:NO completion:nil];
+    }
+    
+}
+
+- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
+    [self rotateView];// 在此重新布局使视图在旋转过程中减少卡顿,更自然。
+}
+
+-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
+{
+    
+    //    [self rotateView];
+    
+    //    [self initControl];
+    ////    [self.pdfPageView setNeedsLayout];
+    //    [self.pdfPageView setNeedsDisplay];
+    ////    UIDeviceOrientation dev_ori = [[UIDevice currentDevice]orientation];
+    //
+    ////    UIApplication * app = [UIApplication sharedApplication];
+    ////    AppDelegate *appDelegate = (AppDelegate *)[app delegate];
+    ////    [appDelegate didRotated];
+    //
+    //    //    UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
+    //    //    if (UIInterfaceOrientationIsLandscape(orientation)|| UIInterfaceOrientationIsPortrait(orientation))
+    //    //    {
+    //    //        self.orientation = orientation;
+    //    //        [self.collectionview.collectionViewLayout invalidateLayout];
+    //    //        DebugLog(@"routed");
+    //    //    }
+    //
+    
+    
+    
+}
+
+#pragma mark add controls
+-(bool) checkActionCondition:(NSString*) condition
+{
+    if([condition isEqualToString:@"true"])
+    return true;
+    if([condition isEqualToString:@"false"])
+    return false;
+    if([condition isEqualToString:@"control_18:[value]==0"])
+    {
+        NSArray* arr= self.page_controlTemplate[@"control_18"][@"value"];
+        if(arr.count==0)
+        return false;
+        else
+        return [arr[0] intValue]==0;
+        
+    }
+    
+    return false;
+}
+-(UIView*) findControl:(NSString*)controlName
+{
+    
+    controlName=[controlName stringByReplacingOccurrencesOfString:@"control_" withString:@""];
+    int d_idx = [controlName intValue];
+    return [self.view viewWithTag:d_idx+CONTROL_BASE];
+}
+-(UITextView*) findNextTV:(UITextView*)tv
+{
+    long index = tv.tag - CONTROL_BASE;
+    
+    
+    
+    
+    int count = [self.page_controlTemplate[@"count"] intValue];
+    for(long i=index+1;i<count;i++)
+    {
+        NSMutableDictionary * control =self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",i] ];
+        if(![control[@"type"] isEqualToString:@"TextView"])
+        {
+            continue;
+        }
+        
+        for(UIView*v in self.editControlView.subviews)
+        {
+            if(v.tag==i+CONTROL_BASE)
+            return (UITextView*)v;
+        }
+        
+        
+    }
+    return nil;
+    
+}
+-(void) addTextView:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
+{
+    
+    CGRect srect=[self scaleControl:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue]) from:CGSizeMake(768, 960.5) to:destView.frame.size];
+    
+    UITextView* tv = [[UITextView alloc] initWithFrame:srect];
+    if([template[@"next_end"] boolValue])
+    tv.returnKeyType=UIReturnKeyDefault;
+    else
+    tv.returnKeyType=UIReturnKeyNext;
+    float fontsize = [template[@"size"] floatValue];
+    if(fontsize==0)
+    fontsize=10;
+    if(self.currentAppOrientation==ScreenOrientationLand)
+    fontsize=fontsize*0.8; // 缩小字体否则textview显示不下。
+    [tv setFont:[UIFont systemFontOfSize:fontsize]];
+    bool isdisable = [template[@"disable"] boolValue];
+    
+    tv.editable = !isdisable;
+    NSString* text= template[@"value"];
+    if(text.length==0)
+    text=@" ";
+    tv.text =text;
+    
+    float tv_vmargin= [template[@"tv_vmargin"] floatValue];
+    NSString* capital= template[@"capital"];
+    UITextAutocapitalizationType capitalType=UITextAutocapitalizationTypeWords;
+    if([capital isEqualToString:@"charater"])
+    {
+        capitalType=UITextAutocapitalizationTypeAllCharacters;
+    }
+    else if([capital isEqualToString:@"sentences"])
+    {
+        capitalType=UITextAutocapitalizationTypeSentences;
+    }
+    else if([capital isEqualToString:@"none"])
+    {
+        capitalType=UITextAutocapitalizationTypeNone;
+    }
+    else
+    {
+        capitalType=UITextAutocapitalizationTypeWords;
+    }
+    
+    tv.autocapitalizationType=capitalType;
+    
+    NSMutableAttributedString* attr_str= [tv.attributedText mutableCopy];
+    
+    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
+    if(tv_vmargin!=0)
+    paragraphStyle.lineHeightMultiple = tv_vmargin;
+    //    paragraphStyle.maximumLineHeight = 25.f;
+    //    paragraphStyle.minimumLineHeight = 15.f;
+    //    paragraphStyle.firstLineHeadIndent = 20.f;
+    //    paragraphStyle.alignment = NSTextAlignmentJustified;
+    [attr_str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,attr_str.length)];
+    
+    tv.attributedText=attr_str;
+    if([text isEqualToString:(@" ")])
+    tv.text=@"";
+    
+    tv.tag = index+ CONTROL_BASE;
+    
+    
+    tv.scrollEnabled=false;
+    
+    NSString* tv_format=template[@"keyboard"];
+    if([tv_format isEqualToString:@"tel"])
+    {
+        tv.keyboardType=UIKeyboardTypePhonePad;
+    }
+    else if([tv_format isEqualToString:@"number"])
+    {
+        tv.keyboardType=UIKeyboardTypeNumberPad;
+    }
+    else if([tv_format isEqualToString:@"email"])
+    {
+        tv.keyboardType=UIKeyboardTypeEmailAddress;
+    }
+    else
+    {
+        tv.keyboardType=UIKeyboardTypeDefault;
+    }
+    
+    
+    //UIColorFromARGB(0x4066ccff);
+    
+    tv.backgroundColor = UIColorFromRGB(TV_BG);//[UIColor lightGrayColor];
+    //    tv.place
+    //    [btn setTitle:template[@"title"] forState:UIControlStateNormal];
+    //    ref addTarget:self action:@selector(manually_refresh) forControlEvents:UIControlEventValueChanged
+    
+    
+    tv.delegate = self;
+    //    [btn addTarget:self action:@selector(ControlButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
+    if(DEBUG_PDFSIG)
+    {
+        
+        
+        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
+    }
+    [destView addSubview:tv];
+}
+-(void) addLabel:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
+{
+    CGRect srect=[self scaleControl:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue]) from:CGSizeMake(768, 960.5) to:destView.frame.size];
+    UILabel* label = [[UILabel alloc] initWithFrame:srect];
+    float fontsize = [template[@"size"] floatValue];
+    if(fontsize==0)
+    fontsize=10;
+    [label setFont:[UIFont systemFontOfSize:fontsize]];
+    
+    NSString * alignment=template[@"textAlignment"];
+    
+    if([alignment.lowercaseString isEqualToString:@"center"])
+    label.textAlignment=NSTextAlignmentCenter;
+    else if([alignment.lowercaseString isEqualToString:@"left"])
+    label.textAlignment=NSTextAlignmentLeft;
+    else if([alignment.lowercaseString isEqualToString:@"right"])
+    label.textAlignment=NSTextAlignmentRight;
+    
+    
+    label.text =template[@"value"];
+    
+    label.tag = index+ CONTROL_BASE;
+    
+    
+    
+    //UIColorFromARGB(0x4066ccff);
+    
+    //    tv.backgroundColor = UIColorFromRGB(TV_BG);//[UIColor lightGrayColor];
+    //    tv.place
+    //    [btn setTitle:template[@"title"] forState:UIControlStateNormal];
+    //    ref addTarget:self action:@selector(manually_refresh) forControlEvents:UIControlEventValueChanged
+    
+    
+    //    tv.delegate = self;
+    //    [btn addTarget:self action:@selector(ControlButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
+    if(DEBUG_PDFSIG)
+    {
+        
+        [label setBackgroundColor:[UIColor grayColor]];
+        
+    }
+    [destView addSubview:label];
+}
+
+-(void) addButton:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
+{
+    CGRect srect=[self scaleControl:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue]) from:CGSizeMake(768, 960.5) to:destView.frame.size];
+    UIButton* btn = [[UIButton alloc] initWithFrame:srect];
+    [btn setTitle:template[@"title"] forState:UIControlStateNormal];
+    
+    btn.tag = index+ CONTROL_BASE;
+    //    ref addTarget:self action:@selector(manually_refresh) forControlEvents:UIControlEventValueChanged
+    btn.backgroundColor = UIColorFromRGB(BT_BG);
+    [btn addTarget:self action:@selector(ControlButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
+    if(DEBUG_PDFSIG)
+    {
+        // btn.backgroundColor = [UIColor lightGrayColor];
+        
+        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
+    }
+    [destView addSubview:btn];
+}
+-(void) addDatePicker:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
+{
+    CGRect srect=[self scaleControl:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue]) from:CGSizeMake(768, 960.5) to:destView.frame.size];
+    UIButton* btn = [[UIButton alloc] initWithFrame:srect];
+    
+    
+    [btn setTitle:template[@"value"] forState:UIControlStateNormal];
+    float fontsize = [template[@"size"] floatValue];
+    if(fontsize==0)
+    fontsize=10;
+    
+    if(self.currentAppOrientation==ScreenOrientationLand)
+    fontsize=fontsize*0.8; // 缩小字体否则textview显示不下。
+    btn.titleLabel.font = [UIFont systemFontOfSize: fontsize];
+    btn.tag = index+ CONTROL_BASE;
+    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
+    //    ref addTarget:self action:@selector(manually_refresh) forControlEvents:UIControlEventValueChanged
+    btn.backgroundColor = UIColorFromRGB(BT_BG);
+    [btn addTarget:self action:@selector(ControlDatePickerClicked:) forControlEvents:UIControlEventTouchUpInside];
+    if(DEBUG_PDFSIG)
+    {
+        // btn.backgroundColor = [UIColor lightGrayColor];
+        
+        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
+    }
+    [destView addSubview:btn];
+}
+-(UIView*) createMarker:(int)size x:(int)x y:(int)y destView:(UIView*)destView
+{
+    
+    
+    CGRect srect=[self scaleControl:CGRectMake(x,y,size,size) from:CGSizeMake(768, 960.5) to:destView.frame.size];
+    UIView* v=[[UIView alloc] initWithFrame:srect];
+    return v;
+    
+}
+-(void) addCheck:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
+{
+    
+    CGRect srect=[self scaleControl:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue]) from:CGSizeMake(768, 960.5) to:destView.frame.size];
+    UIButton* btn = [[UIButton alloc] initWithFrame:srect];
+    
+    //    ref addTarget:self action:@selector(manually_refresh) forControlEvents:UIControlEventValueChanged
+    btn.tag = index+ CONTROL_BASE;
+    [btn addTarget:self action:@selector(CheckButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
+    UIColor* marker_bg=UIColorFromRGB(CK_BG);//[UIColor clearColor];
+    if(DEBUG_PDFSIG)
+    {
+        btn.backgroundColor = [UIColor lightGrayColor];
+        
+        [btn setTitle:template[@"title"] forState:UIControlStateNormal];
+        //        marker_bg = [UIColor redColor];
+        
+        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
+    }
+    [destView addSubview:btn];
+    NSArray* cadedate = template[@"cadedate"];
+    
+    NSArray* checkedData = self.page_controlTemplate [[NSString stringWithFormat:@"control_%d",index] ][@"value"];
+    float fontsize = [template[@"size"] floatValue];
+    if(fontsize==0)
+    fontsize=10;
+    
+    //    if(checkedData.count>0)
+    //        marker_bg = [UIColor clearColor];
+    //    else
+    marker_bg=UIColorFromRGB(CK_BG);
+    
+    for(int i=0;i<cadedate.count;i++)
+    {
+        NSArray* item = cadedate[i];
+        NSArray* checkmarker = item[1];
+        if(checkmarker.count==0)
+        {
+            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
+            btn.titleLabel.font = [UIFont systemFontOfSize: fontsize];
+            btn.backgroundColor = UIColorFromRGB(CK_BG);
+            if([checkedData containsObject:[NSNumber numberWithLong:i]])
+            {
+                [btn setTitle:item[0][0] forState:UIControlStateNormal];
+                
+            }
+            continue;
+        }
+        else
+        {
+            [btn setTitle:@"" forState:UIControlStateNormal];
+        }
+        UIView* marker=[self createMarker:[template[@"marker_size"] intValue] x:[item[1][0] intValue] y:[item[1][1] intValue] destView:destView];
+        
+        marker.backgroundColor = marker_bg;
+        marker.tag = CHECK_BASE+index*1000+i;
+        
+        
+        if([checkedData containsObject:[NSNumber numberWithLong:i]])
+        {
+            
+            marker.backgroundColor= UIColorFromRGB(CK_MK);
+            
+        }
+        else
+        {
+            marker.backgroundColor= marker_bg;
+        }
+        
+        [destView addSubview:marker];
+        
+    }
+    
+}
+-(void) addSignatureButton:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
+{
+    CGRect srect=[self scaleControl:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue]) from:CGSizeMake(768, 960.5) to:destView.frame.size];
+    TouchImageView* btn = [[TouchImageView alloc] initWithFrame:srect];
+    
+    btn.contentMode = UIViewContentModeScaleAspectFit;
+    btn.delegate = self;
+    btn.layer.borderColor = [UIColor clearColor].CGColor;
+    btn.layer.borderWidth = 0;
+    btn.tag = index+ CONTROL_BASE;
+    
+    NSString* file =template[@"value"];
+    
+    NSData* img_data=[ImageUtils load_img:file];
+    
+    if(img_data!=nil)
+    {
+        
+        UIImage* image=[UIImage imageWithData:img_data];
+        btn.image = image;
+        
+    }
+    else
+    {
+        if([template[@"disable"] boolValue]&& [template[@"required"] boolValue])
+        {
+            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
+            UIImage* img = [UIImage imageNamed:@"na"];
+            btn.image = img;
+            template[@"value"]=appDelegate.na_path;
+            
+        }
+    }
+    
+    
+    btn.backgroundColor = UIColorFromRGB(SIG_BG);
+    
+    if(DEBUG_PDFSIG)
+    {
+        
+        
+        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
+    }
+    [destView addSubview:btn];
+}
+-(void) addImage:(NSMutableDictionary*) template destView:(UIView*)destView index:(int) index
+{
+    CGRect srect=[self scaleControl:CGRectMake([template[@"pos_x"] floatValue], [template[@"pos_y"] floatValue], [template[@"width"] floatValue], [template[@"height"] floatValue]) from:CGSizeMake(768, 960.5) to:destView.frame.size];
+    UIImageView* btn = [[UIImageView alloc] initWithFrame:srect];
+    
+    btn.contentMode = UIViewContentModeScaleAspectFit;
+    
+    btn.layer.borderColor = [UIColor clearColor].CGColor;
+    btn.layer.borderWidth = 0;
+    btn.tag = index+ CONTROL_BASE;
+    
+    NSString* file =template[@"value"];
+    
+    NSData* img_data=[ImageUtils load_img:file];
+    
+    if(img_data!=nil)
+    {
+        
+        UIImage* image=[UIImage imageWithData:img_data];
+        btn.image = image;
+        
+    }
+    
+    
+    btn.backgroundColor = UIColorFromRGB(SIG_BG);
+    
+    if(DEBUG_PDFSIG)
+    {
+        
+        
+        // [btn setBackgroundImage:[UIColor grayColor] forState:UIControlStateNormal];
+    }
+    [destView addSubview:btn];
+}
+#pragma mark UIScrollView delegate
+
+- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
+    
+    
+    UIView *subView = [scrollView viewWithTag:1024];
+    return subView;
+    
+}
+- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(nullable UIView *)view atScale:(CGFloat)scale
+{
+    CGPoint contentOffsetPoint = self.pdfScrollView.contentOffset;
+    CGSize contentSize =self.pdfScrollView.contentSize;//frame.size;
+    //    CGSize size1 = self.pdfScrollView.bounds.size;
+    //    NSLog(@"frame:%@ bound:%@", NSStringFromCGSize(contentSize),NSStringFromCGSize(size1) );
+    contentSize.height+=self.keyboard_h;
+    contentOffsetPoint.y+=self.keyboard_h;
+    
+    
+    
+    self.pdfScrollView.contentSize =contentSize;
+    self.pdfScrollView.contentOffset=contentOffsetPoint;
+    
+    [self.pdfPageView setNeedsDisplay];
+}
+//- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale {
+//
+//
+//
+//}
+#pragma mark Button Click
+- (void)ControlDatePickerClicked:(UIButton *)sender {
+    
+    
+    long index = sender.tag - CONTROL_BASE;
+    
+    
+    if([self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"disable"] boolValue] )
+    {
+        return;
+    }
+    
+    __weak __typeof(self)weakSelf = self;
+    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
+    [formatter setDateFormat:@"MM/dd/yyyy"];
+    NSString* date = sender.currentTitle;
+    
+    NSDate* currentDate =nil;
+    if(date.length==0)
+    currentDate=[NSDate date];
+    else
+    currentDate=[formatter dateFromString:date];
+    
+    DatePickerViewController* dpvc =[ [UIStoryboard storyboardWithName:@"CommonEditor" bundle:nil] instantiateViewControllerWithIdentifier:@"DatePickerViewController"];
+    
+    dpvc.pickerMode = UIDatePickerModeDate;
+    
+    
+    
+    dpvc.date = currentDate;
+    dpvc.formatter = formatter;
+    dpvc.labelTime.text = [formatter stringFromDate:currentDate];
+    
+    dpvc.blk_Set = ^(NSString* strdate)
+    {
+        //        weakSelf.labelSignDate.text = strdate;
+        
+        [sender setTitle:strdate forState:UIControlStateNormal];
+        
+        weakSelf.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = strdate;
+        weakSelf.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"dirty"]=[NSNumber numberWithBool:true];
+    };
+    dpvc.title=@"Please choose a date";
+    [self.navigationController pushViewController:dpvc animated:true];
+}
+- (void)ControlButtonClicked:(UIButton *)sender {
+    //    DebugLog(@"cart sort button clicked");
+    
+    NSLog(@"button clicked;");
+    //    [self.view addSubview:self.sortItemController.view];
+}
+- (void)CheckButtonClicked:(UIButton *)sender {
+    //    DebugLog(@"cart sort button clicked");
+    
+    NSLog(@"check clicked;");
+    
+    long index = sender.tag - CONTROL_BASE;
+    
+    
+    bool single_select = [self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"single_select"] boolValue];
+    bool show_detail = [self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"show_detail"] boolValue];
+    NSArray* rowData = self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"cadedate"];
+    NSArray* checkedData = self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"];
+    CheckSelectorViewController *checkVC = [ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"CheckSelectorViewController"];
+    
+    checkVC.blk_OK = ^(NSArray* checkedData){
+        
+        
+        
+        
+        for(int i=0;i<rowData.count;i++)
+        {
+            long tag=CHECK_BASE+index*1000+i;
+            
+            
+            
+            NSArray* item = rowData[i];
+            NSArray* checkmarker = item[1];
+            
+            // checkmarker 不显示,则显示选项内容文字。
+            if(checkmarker.count==0)
+            {
+                sender.backgroundColor = UIColorFromRGB(CK_BG);
+                
+                if([checkedData containsObject:[NSNumber numberWithLong:i]])
+                {
+                    [sender setTitle:item[0][0] forState:UIControlStateNormal];
+                }
+                //                continue;
+            }
+            else
+            {
+                [sender setTitle:@"" forState:UIControlStateNormal];
+                if([checkedData containsObject:[NSNumber numberWithLong:i]])
+                {
+                    // [checkedData removeObject:[NSNumber numberWithLong:indexPath.row]];
+                    
+                    [sender.superview viewWithTag:tag].backgroundColor= [UIColor blackColor];
+                    
+                }
+                else
+                {
+                    // [self.checkedData addObject:[NSNumber numberWithLong:indexPath.row] ];
+                    [sender.superview viewWithTag:tag].backgroundColor= [UIColor clearColor];
+                }
+            }
+            
+            bool checked =[checkedData containsObject:[NSNumber numberWithLong:i]];
+            if(item.count>=3) // 模板有action项
+            {
+                //[sender setTitle:item[0][0] forState:UIControlStateNormal];
+                NSMutableDictionary* action = item[2];
+                if(checked)
+                {
+                    
+                    NSArray* disable_arr = action[@"disable"] ;
+                    for(int d = 0 ; d<disable_arr.count;d++)
+                    {
+                        self.page_controlTemplate [disable_arr[d] ] [@"disable"] = [NSNumber numberWithBool:true];
+                        NSString* s_idx =disable_arr[d];
+                        s_idx=[s_idx stringByReplacingOccurrencesOfString:@"control_" withString:@""];
+                        int d_idx = [s_idx intValue];
+                        ((UITextView*)[sender.superview viewWithTag:d_idx+CONTROL_BASE]).editable = false;
+                    }
+                    NSArray* enable_arr = action[@"enable"] ;
+                    for(int e = 0 ; e<enable_arr.count;e++)
+                    {
+                        self.page_controlTemplate [enable_arr[e] ] [@"disable"] = [NSNumber numberWithBool:false];
+                        
+                        NSString* s_idx =enable_arr[e];
+                        s_idx=[s_idx stringByReplacingOccurrencesOfString:@"control_" withString:@""];
+                        int d_idx = [s_idx intValue];
+                        
+                        ((UITextView*)[sender.superview viewWithTag:d_idx+CONTROL_BASE]).editable = true;
+                    }
+                    
+                    
+                    
+                    
+                    
+                    NSMutableDictionary* json_setval=action[@"set_val"] ;
+                    for(int i=0;i<[json_setval[@"count"] intValue];i++)
+                    {
+                        
+                        NSMutableDictionary * control =  json_setval [[NSString stringWithFormat:@"item_%d",i] ];
+                        UITextView* tv = (UITextView*) [self findControl:control[@"control"]];
+                        NSString* value = control[@"value"];
+                        
+                        UITextView* tv6 = (UITextView*) [self findControl:@"control_10"];
+                        NSString* text = tv6.text;
+                        NSString* newvalue = nil;
+                        if([value isEqualToString:@"*0.1"])
+                        {
+                            
+                            NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
+                            formatter.numberStyle =kCFNumberFormatterCurrencyStyle;
+                            NSString* prefix_str= self.page_controlTemplate [control[@"control"] ][@"prefix_str"];
+                            if(prefix_str.length==0)
+                            prefix_str = @"";
+                            text=[text stringByReplacingOccurrencesOfString:prefix_str withString:@"$"];
+                            double f = [[formatter numberFromString:text] doubleValue]*0.1;
+                            newvalue = [formatter stringFromNumber:[NSNumber numberWithDouble: f]];
+                            
+                            newvalue=[newvalue stringByReplacingOccurrencesOfString:@"$" withString:prefix_str];
+                            //                                float f= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue]*0.1;
+                            //                                newvalue = [NSString stringWithFormat:@"$ %.2f",f];
+                            self.page_controlTemplate [control[@"control"] ][@"value"] = newvalue;
+                            self.page_controlTemplate [control[@"control"] ][@"dirty"] = [NSNumber numberWithBool:true];
+                        }
+                        else if([value isEqualToString:@"*0.9"])
+                        {
+                            //                                float f= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue]*0.9;
+                            NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
+                            formatter.numberStyle =kCFNumberFormatterCurrencyStyle;
+                            NSString* prefix_str= self.page_controlTemplate [control[@"control"] ][@"prefix_str"];
+                            if(prefix_str.length==0)
+                            prefix_str = @"";
+                            text=[text stringByReplacingOccurrencesOfString:prefix_str withString:@"$"];
+                            double f = [[formatter numberFromString:text] doubleValue]*0.9;
+                            newvalue = [formatter stringFromNumber:[NSNumber numberWithDouble: f]];
+                            newvalue=[newvalue stringByReplacingOccurrencesOfString:@"$" withString:prefix_str];
+                            //                                newvalue = [NSString stringWithFormat:@"$ %.2f",f];
+                            self.page_controlTemplate [control[@"control"] ][@"value"] = newvalue;
+                            self.page_controlTemplate [control[@"control"] ][@"dirty"] = [NSNumber numberWithBool:true];
+                        }
+                        
+                        
+                        tv.text = newvalue;
+                        
+                    }
+                }
+                
+                
+                NSMutableDictionary* json_cd=action[@"conditional_constraint"][checked?@"true":@"false"] ;
+                {
+                    for(int i=0;i<[json_cd[@"count"] intValue];i++)
+                    {
+                        
+                        NSMutableDictionary * destination =  json_cd [[NSString stringWithFormat:@"item_%d",i] ];
+                        int page = [destination[@"page"] intValue];
+                        NSString* control = destination[@"control"];
+                        self.doc_controlTemplate[[NSString stringWithFormat:@"page_%d",page]][control][@"disable"]=destination[@"disable"];
+                        id value =destination[@"set_val"];
+                        self.doc_controlTemplate[[NSString stringWithFormat:@"page_%d",page]][control][@"value"]=value;
+                        //                        UITextView* tv = (UITextView*) [self findControl:destination[@"control"]];
+                        //                        NSString* value = control[@"value"];
+                        //
+                        //                        UITextView* tv6 = (UITextView*) [self findControl:@"control_10"];
+                        //                        NSString* text = tv6.text;
+                        //                        NSString* newvalue = nil;
+                        //                        if([value isEqualToString:@"*0.1"])
+                        //                        {
+                        //
+                        //                            NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
+                        //                            formatter.numberStyle =kCFNumberFormatterCurrencyStyle;
+                        //                            NSString* prefix_str= self.page_controlTemplate [control[@"control"] ][@"prefix_str"];
+                        //                            if(prefix_str.length==0)
+                        //                                prefix_str = @"";
+                        //                            text=[text stringByReplacingOccurrencesOfString:prefix_str withString:@"$"];
+                        //                            double f = [[formatter numberFromString:text] doubleValue]*0.1;
+                        //                            newvalue = [formatter stringFromNumber:[NSNumber numberWithDouble: f]];
+                        //
+                        //                            newvalue=[newvalue stringByReplacingOccurrencesOfString:@"$" withString:prefix_str];
+                        //                            //                                float f= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue]*0.1;
+                        //                            //                                newvalue = [NSString stringWithFormat:@"$ %.2f",f];
+                        //                            self.page_controlTemplate [control[@"control"] ][@"value"] = newvalue;
+                        //                            self.page_controlTemplate [control[@"control"] ][@"dirty"] = [NSNumber numberWithBool:true];
+                        //                        }
+                        //                        else if([value isEqualToString:@"*0.9"])
+                        //                        {
+                        //                            //                                float f= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue]*0.9;
+                        //                            NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
+                        //                            formatter.numberStyle =kCFNumberFormatterCurrencyStyle;
+                        //                            NSString* prefix_str= self.page_controlTemplate [control[@"control"] ][@"prefix_str"];
+                        //                            if(prefix_str.length==0)
+                        //                                prefix_str = @"";
+                        //                            text=[text stringByReplacingOccurrencesOfString:prefix_str withString:@"$"];
+                        //                            double f = [[formatter numberFromString:text] doubleValue]*0.9;
+                        //                            newvalue = [formatter stringFromNumber:[NSNumber numberWithDouble: f]];
+                        //                            newvalue=[newvalue stringByReplacingOccurrencesOfString:@"$" withString:prefix_str];
+                        //                            //                                newvalue = [NSString stringWithFormat:@"$ %.2f",f];
+                        //                            self.page_controlTemplate [control[@"control"] ][@"value"] = newvalue;
+                        //                            self.page_controlTemplate [control[@"control"] ][@"dirty"] = [NSNumber numberWithBool:true];
+                        //                        }
+                        //
+                        //
+                        //                        tv.text = newvalue;
+                        
+                    }
+                }
+                
+            }
+            
+            // UIView* v= sender;
+            
+            
+            
+        }
+        self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"]=checkedData;
+        
+        self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"dirty"] = [NSNumber numberWithBool:true];
+    };
+    checkVC.rowData = rowData;
+    checkVC.checkedData = [checkedData mutableCopy];
+    checkVC.single_select = single_select;
+    checkVC.show_detail = show_detail;
+    
+    checkVC.title=@"abcdefg";
+    checkVC.modalPresentationStyle = UIModalPresentationFormSheet;
+    [self presentViewController:checkVC animated:YES completion:nil];
+    
+}
+
+#pragma mark TextViewDelegate
+
+- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
+{
+    long index = textView.tag - CONTROL_BASE;
+    
+    if([text isEqualToString:@""])
+    return true;
+    
+    if([text isEqualToString:@"\n"])
+    {
+        //  [textView resignFirstResponder];
+        
+        UITextView * tv = [self findNextTV:textView];
+        
+        if(tv)
+        [tv becomeFirstResponder];
+        
+        
+        [textView resignFirstResponder];
+        return false;
+    }
+    
+    NSString* tv_format=self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"format"];
+    if([tv_format isEqualToString:@"us_tel"])
+    {
+        NSMutableString *newString = [[textView.text stringByReplacingCharactersInRange:range withString:text] mutableCopy];
+        NSArray *components = [newString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
+        NSString *decimalString = [components componentsJoinedByString:@""];
+        
+        NSUInteger length = decimalString.length;
+        BOOL hasLeadingOne = length > 0 && [decimalString characterAtIndex:0] == '1';
+        
+        if (length == 0 ) {
+            textView.text = decimalString;
+            return NO;
+        }
+        if((length >= 10 && !hasLeadingOne) )
+        {
+            if(length>15)
+            return NO;
+            //            newString=[[newString stringByReplacingOccurrencesOfString:@"-" withString:@""] mutableCopy];
+            //            [newString  insertString:@"-" atIndex:14];
+            //            textView.text = newString;
+            //            return NO;
+        }
+        if((length >= 11))
+        {
+            if(length>16)
+            return NO;
+            //            newString=[[newString stringByReplacingOccurrencesOfString:@"-" withString:@""] mutableCopy];
+            //            [newString  insertString:@"-" atIndex:16];
+            //            textView.text = newString;
+            //            return NO;
+        }
+        NSUInteger index = 0;
+        NSMutableString *formattedString = [NSMutableString string];
+        
+        if (hasLeadingOne) {
+            [formattedString appendString:@"1 "];
+            index += 1;
+        }
+        
+        if (length - index > 3) {
+            NSString *areaCode = [decimalString substringWithRange:NSMakeRange(index, 3)];
+            [formattedString appendFormat:@"(%@) ",areaCode];
+            index += 3;
+        }
+        
+        if (length - index > 3) {
+            NSString *prefix = [decimalString substringWithRange:NSMakeRange(index, 3)];
+            [formattedString appendFormat:@"%@ ",prefix];
+            index += 3;
+        }
+        
+        if (length - index > 4) {
+            NSString *prefix = [decimalString substringWithRange:NSMakeRange(index, 4)];
+            [formattedString appendFormat:@"%@-",prefix];
+            index += 4;
+        }
+        
+        NSString *remainder = [decimalString substringFromIndex:index];
+        [formattedString appendString:remainder];
+        
+        textView.text = formattedString;
+        
+        return NO;
+    }
+    else if([tv_format isEqualToString:@"price"])
+    {
+        //        NSMutableString *newString = [[textView.text stringByReplacingCharactersInRange:range withString:text] mutableCopy];
+        //        NSArray *components = [newString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
+        //        NSString *decimalString = [components componentsJoinedByString:@""];
+        //
+        //
+        //
+        
+        
+        
+        //
+        //        NSString *newprice = [formatter stringFromNumber:[NSNumber numberWithInt: [decimalString intValue]]];
+        //
+        //        textView.text = newprice;
+        
+        
+        
+        NSCharacterSet *cs;
+        cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS]invertedSet];
+        //
+        NSString *filtered = [[text componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
+        
+        BOOL canChange = [text isEqualToString:filtered];
+        
+        //        if(canChange)
+        //        {
+        //
+        //        }
+        return canChange;
+        
+        
+        //        return NO;
+    }
+    else
+    {
+        
+        NSString* oldtext =textView.text;
+        if(oldtext==nil)
+        oldtext=@"";
+        
+        bool canChange=true;
+        
+        int max_line = [self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"lines"] intValue];
+        if(max_line==0)//默认只能有一行
+        max_line=1;
+        long linecount=[TextUtils countOccurencesOfString:oldtext find:@"\n"];
+        if(max_line!=-1) //maxline -1表示不限制行数。
+        {
+            if(linecount<=max_line-1&& [text isEqualToString:@"\n"])
+            {
+                canChange = false;
+            }
+        }
+        
+        
+        int lenth = [self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"length"] intValue];
+        if(lenth==0)
+        return canChange;
+        else
+        {
+            return canChange&& (lenth>textView.text.length ||[text isEqualToString:@""]);
+        }
+    }
+    
+    
+    
+}
+//- (void)textViewDidBeginEditing:(UITextView *)textView
+//{
+//    self.hotTextView = textView;
+//}
+
+- (void)textViewDidBeginEditing:(UITextView *)textView
+{
+    long index = textView.tag - CONTROL_BASE;
+    NSString* tv_format=self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"format"];
+    if([tv_format isEqualToString:@"price"])
+    {
+        
+        NSString* prefix_str= self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"prefix_str"];
+        if(prefix_str.length==0)
+        prefix_str = @"";
+        
+        
+        NSString* text =[textView.text stringByReplacingOccurrencesOfString:prefix_str withString:@"$"];
+        
+        
+        NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
+        
+        formatter.numberStyle =kCFNumberFormatterCurrencyStyle;
+        NSNumber* number= [formatter numberFromString:text];
+        if(number!=nil)
+        textView.text = [NSString stringWithFormat:@"%.2f",[number doubleValue]];
+    }
+    
+    //    NSRange r = textView.selectedRange;
+    //
+    //
+    //    textView.selectedRange = NSMakeRange(textView.text.length, 0);
+    //    NSRange range;
+    //
+    //    range.location = textView.text.length;
+    //
+    //    range.length = 0;
+    //
+    //    textView.selectedRange = range;
+    
+}
+- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
+{
+    
+    NSLog(@"textViewShouldBeginEditing");
+    
+    
+    //    long index = textView.tag - CONTROL_BASE;
+    //
+    //
+    //    NSMutableDictionary* control_json = self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ];
+    //
+    //    if([control_json[@"disable"] boolValue] )
+    //    {
+    //        return false;
+    //    }
+    //
+    
+    
+    
+    self.hotTextView = textView;//(UITableViewCell*)textView.superview.superview;
+    
+    
+    
+    
+    
+    
+    
+    
+    return textView.editable;
+}
+- (void)textViewDidEndEditing:(UITextView *)textView
+{
+    
+    long index = textView.tag - CONTROL_BASE;
+    
+    
+    //处理 prefix 和 浮点格式化
+    NSString* prefix_str= self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"prefix_str"];
+    if(prefix_str.length==0)
+    prefix_str = @"";
+    NSString* text =textView.text;// [textView.text stringByReplacingOccurrencesOfString:prefix_str withString:@""];
+    
+    NSString* value_type= self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value_type"];
+    if([value_type isEqualToString:@"float"])
+    text=[NSString stringWithFormat:@"%.2f",[text doubleValue] ];
+    
+    
+    
+    //    text =[NSString stringWithFormat:@"%@%@",prefix_str,text] ;
+    
+    
+    
+    if([self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"format"] isEqualToString:@"price"])
+    {
+        text =textView.text;
+        
+        NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
+        
+        formatter.numberStyle =kCFNumberFormatterCurrencyStyle;
+        
+        
+        NSNumber * nprice =[NSNumber numberWithDouble: [text doubleValue]];
+        if(text.length==0)
+        nprice=nil;
+        text = [formatter stringFromNumber:nprice];
+        text=[text stringByReplacingOccurrencesOfString:@"$" withString:prefix_str];
+        //                textView.text = newprice;
+        //        return NO;
+    }
+    
+    
+    textView.text = text;
+    
+    if(text==nil)
+    text=@"";
+    self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = text;
+    self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"dirty"] =[NSNumber numberWithBool:true];
+    NSDictionary* action = self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"action"];
+    NSArray* keys=[action allKeys];
+    for(int k=0;k<keys.count;k++)
+    {
+        NSMutableDictionary* act_k = action[keys[k] ];
+        
+        
+        if (![self checkActionCondition:act_k[@"condition"]])
+        continue;
+        for(int i=0;i<[act_k[@"count"] intValue];i++)
+        {
+            
+            NSMutableDictionary * control =  act_k [[NSString stringWithFormat:@"item_%d",i] ];
+            UITextView* tv = (UITextView*) [self findControl:control[@"control"]];
+            NSString* value = control[@"value"];
+            
+            NSString* newvalue = nil;
+            if([value isEqualToString:@"*0.1"])
+            {
+                //                double f= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] doubleValue]*0.1;
+                NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
+                formatter.numberStyle =kCFNumberFormatterCurrencyStyle;
+                
+                NSString* prefix_str= self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"prefix_str"];
+                if(prefix_str.length==0)
+                prefix_str = @"";
+                
+                if(text.length==0)
+                {
+                    newvalue=nil;
+                }
+                else
+                {
+                    text=[text stringByReplacingOccurrencesOfString:prefix_str withString:@"$"];
+                    double f = [[formatter numberFromString:text] doubleValue]*0.1;
+                    
+                    //                    if(tv==self.hotTextView)
+                    //                    {
+                    //
+                    //                        newvalue = [NSString stringWithFormat:@"%.2f",f];
+                    //                    }
+                    //                    else
+                    {
+                        newvalue = [formatter stringFromNumber:[NSNumber numberWithDouble: f]];
+                        newvalue=[newvalue stringByReplacingOccurrencesOfString:@"$" withString:prefix_str];
+                        //                newvalue = [NSString stringWithFormat:@"$ %.2f",f];
+                    }
+                }
+                
+                
+                self.page_controlTemplate [control[@"control"] ][@"value"] = newvalue;
+                self.page_controlTemplate [control[@"control"] ][@"dirty"] =[NSNumber numberWithBool:true];
+            }
+            else if([value isEqualToString:@"*0.9"])
+            {
+                //                double f= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] doubleValue]*0.9;
+                NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
+                formatter.numberStyle =kCFNumberFormatterCurrencyStyle;
+                
+                NSString* prefix_str= self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"prefix_str"];
+                if(prefix_str.length==0)
+                prefix_str = @"";
+                
+                if(text.length==0)
+                {
+                    newvalue=nil;
+                }
+                else
+                {
+                    text=[text stringByReplacingOccurrencesOfString:prefix_str withString:@"$"];
+                    double f = [[formatter numberFromString:text] doubleValue]*0.9;
+                    newvalue = [formatter stringFromNumber:[NSNumber numberWithDouble: f]];
+                    newvalue=[newvalue stringByReplacingOccurrencesOfString:@"$" withString:prefix_str];
+                }
+                //                newvalue = [NSString stringWithFormat:@"$ %.2f",f];
+                self.page_controlTemplate [control[@"control"] ][@"value"] = newvalue;
+                self.page_controlTemplate [control[@"control"] ][@"dirty"] = [NSNumber numberWithBool:true];
+                
+            }
+            else if([value isEqualToString:@"control_6-control_7"])
+            {
+                
+                UITextView* tv6 = (UITextView*) [self findControl:@"control_10"];
+                //                float f6= [[tv6.text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue];
+                //
+                //                float f7= [[text stringByReplacingOccurrencesOfString:@"$" withString:@"" ] floatValue];
+                
+                
+                
+                NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
+                formatter.numberStyle =kCFNumberFormatterCurrencyStyle;
+                
+                NSString* prefix_str= self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"prefix_str"];
+                if(prefix_str.length==0)
+                prefix_str = @"";
+                NSString * text6=[tv6.text stringByReplacingOccurrencesOfString:prefix_str withString:@"$"];
+                text=[text stringByReplacingOccurrencesOfString:prefix_str withString:@"$"];
+                double f6 =0.0;
+                //                if(tv6==self.hotTextView)
+                //                    f6=[tv6.text doubleValue];
+                //                else
+                f6=[[formatter numberFromString:text6] doubleValue];
+                double f7 = [[formatter numberFromString:text] doubleValue];
+                newvalue = [formatter stringFromNumber:[NSNumber numberWithDouble: f6-f7]];
+                newvalue=[newvalue stringByReplacingOccurrencesOfString:@"$" withString:prefix_str];
+                //                newvalue = [NSString stringWithFormat:@"$ %.2f",f6-f7];
+                self.page_controlTemplate [control[@"control"] ][@"value"] = newvalue;
+                self.page_controlTemplate [control[@"control"] ][@"dirty"] = [NSNumber numberWithBool:true];
+            }
+            
+            tv.text = newvalue;
+            
+        }
+    }
+    
+    
+    //    int count = [self.controlTemplate[@"count"] intValue];
+    //    for(int i=0;i<count;i++)
+    //    {
+    //        NSMutableDictionary * control =;
+    //[self update_newprice];
+}
+
+/*
+ #pragma mark - Navigation
+ 
+ // In a storyboard-based application, you will often want to do a little preparation before navigation
+ - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
+ // Get the new view controller using [segue destinationViewController].
+ // Pass the selected object to the new view controller.
+ }
+ */
+#pragma mark signature clicked
+//touchimageview Delegate
+-(void) signature:(TouchImageView *)touchImageView
+{
+    __weak __typeof(self)weakSelf = self;
+    
+    
+    
+    long index = touchImageView.tag - CONTROL_BASE;
+    
+    
+    NSMutableDictionary* control_json = self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ];
+    
+    
+    //    CGRect cellrect_screen = [RAUtils relativeFrameForScreenWithView:trigger];
+    //
+    //
+    //    CGRect rect1=[self.view convertRect:cellrect_screen fromView:[[[UIApplication sharedApplication] delegate] window]];
+    //
+    //    DebugLog(@"convert1 %@",NSStringFromCGRect(rect1));
+    SignatureListViewController *signatureVC = [ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureListViewController"];
+    signatureVC.title=@"Signatures";
+    signatureVC.signatureData = self.signatureData;
+    signatureVC.subType = control_json[@"name"];
+    signatureVC.can_fill= [control_json[@"can_fill"] boolValue];
+    signatureVC.signature_ratio= touchImageView.frame.size;
+    
+    //        signatureVC.imageView = touchImageView;
+    
+    signatureVC.blk_Select =^(NSString* file)
+    {
+        
+        
+        
+        //            NSString* file_name=[file lastPathComponent];
+        
+        NSData* img_data=[ImageUtils load_img:file];
+        
+        if(img_data!=nil)
+        {
+            
+            UIImage* image=[UIImage imageWithData:img_data];
+            touchImageView.image = image;
+            
+            long index = touchImageView.tag - CONTROL_BASE;
+            weakSelf.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
+            weakSelf.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"dirty"] = [NSNumber numberWithBool:true];
+        }
+        
+    };
+    signatureVC.blk_Fill =^(NSString* file,bool fillFullDoc)
+    {
+        
+        if(weakSelf.blk_Fill)
+        weakSelf.blk_Fill(file,control_json[@"name"],fillFullDoc);
+        //            for(int j=0;j<[self.controlTemplate[@"count"] intValue];j++)
+        //            {
+        //                NSMutableDictionary* dest =self.controlTemplate[[NSString stringWithFormat:@"control_%d",j]];
+        //                NSString* type = dest[@"type"];
+        //                if(![type isEqualToString:@"Signature"])
+        //                    continue;
+        //                if([dest[@"name"] isEqualToString:control_json[@"name"]])
+        //                {
+        //                    dest[@"value"]=file;
+        //                }
+        //            }
+        [weakSelf refreshControl];
+        
+        //            //            NSString* file_name=[file lastPathComponent];
+        //
+        //            NSData* img_data=[ImageUtils load_img:file];
+        //
+        //            if(img_data!=nil)
+        //            {
+        //
+        //                UIImage* image=[UIImage imageWithData:img_data];
+        //                touchImageView.image = image;
+        //
+        //                long index = touchImageView.tag - CONTROL_BASE;
+        //                self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
+        //
+        //            }
+        
+    };
+    signatureVC.blk_Add = ^()
+    {
+        
+        __block UIImage* signimg=nil;
+        SignatureViewController * vc =[ [UIStoryboard storyboardWithName:@"signature" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SignatureViewController"];
+        vc.title =[NSString stringWithFormat:@"Signature: %@",control_json[@"name"]];
+        vc.signature_ratio= touchImageView.frame.size;
+        vc.linewidth = [control_json[@"linewidth"] intValue];
+        vc.onReturnImg = ^(UIImage* img)
+        {
+            
+            
+            signimg = img;
+            
+            if(signimg!=nil)
+            {
+                NSString* file=[PDFUtils addSignature:signimg to:self.signatureData subType:control_json[@"name"]];
+                long index = touchImageView.tag - CONTROL_BASE;
+                self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = file;
+                self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"dirty"] =[NSNumber numberWithBool:true];
+                
+                touchImageView.image = signimg;
+            }
+            
+            
+        };
+        //    orderinfoVC.url_type = URL_REMOTE;
+        //    orderinfoVC.request_url=URL_CARTDELIVERY;
+        //
+        //    orderinfoVC.params = params;
+        //
+        //    orderinfoVC.delegate=self;
+        //
+        //    if(checked.count==count)
+        //    {
+        //    orderinfoVC.have_tail = true
+        //    }
+        
+        [self.navigationController pushViewController:vc animated:true];
+        
+        
+        
+    };
+    
+    
+    UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:signatureVC];
+    navi.modalPresentationStyle=UIModalPresentationPopover;
+    
+    UIPopoverPresentationController* popPc = navi.popoverPresentationController;
+    popPc.permittedArrowDirections = UIPopoverArrowDirectionAny;
+    popPc.sourceView = touchImageView;
+    popPc.delegate = nil;
+    
+    
+    
+    [self presentViewController:navi animated:true completion:nil];
+}
+- (void) TouchImageViewOnLongPress:(TouchImageView *)touchImageView
+{
+    
+    long index = touchImageView.tag - CONTROL_BASE;
+    
+    
+    NSMutableDictionary* control_json = self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ];
+    
+    if([control_json[@"disable"] boolValue] )
+    {
+        return;
+    }
+    
+    if(touchImageView.image!=nil)
+    {
+        NSLog(@"long press");
+        
+        
+        [self becomeFirstResponder];
+        UIView* v = touchImageView;
+        
+        self.tiv_index = v.tag;
+        UIMenuItem *clear = [[UIMenuItem alloc] initWithTitle:@"Clear" action:@selector(touchImageClear:)];
+        //        UIMenuItem *modify = [[UIMenuItem alloc] initWithTitle:@"Modify" action:@selector(touchImageModify:)];
+        //    [detail setValue:_id forKey:@"_id"];
+        
+        UIMenuController *menu = [UIMenuController sharedMenuController];
+        
+        
+        [menu setMenuItems:[NSArray arrayWithObjects:clear,/*modify,*/ nil]];
+        
+        [menu setTargetRect:v.frame inView:v.superview];
+        [menu setMenuVisible:YES animated:YES];
+    }
+}
+//- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
+//{
+//    if (action == @selector(showDetail:))
+//        return YES;//显示
+//    else
+//        return NO;//不显示
+//}
+- (void) touchImageClear:(id) sender
+{
+    long index = self.tiv_index - CONTROL_BASE;
+    
+    for(UIView*v in self.editControlView.subviews)
+    {
+        if(v.tag==self.tiv_index)
+        ((UIImageView*)v).image = nil;
+    }
+    //    NSMutableDictionary* control_json = self.controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ];
+    
+    self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"value"] = @"";
+    self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ][@"dirty"] =[NSNumber numberWithBool:true];
+}
+- (void) touchImageModify:(id) sender
+{
+    
+}
+- (void)TouchImageViewOnTouche:(TouchImageView *)touchImageView
+{
+    
+    NSLog(@"signature button clicked;");
+    
+    //
+    //    __weak __typeof(self)weakSelf = self;
+    //
+    //
+    //
+    long index = touchImageView.tag - CONTROL_BASE;
+    
+    
+    NSMutableDictionary* control_json = self.page_controlTemplate [[NSString stringWithFormat:@"control_%ld",index] ];
+    
+    if([control_json[@"disable"] boolValue] )
+    {
+        return;
+    }
+    
+    
+    bool bvalidation=[control_json[@"required_validation"] boolValue];
+    NSString* pwd= control_json[@"validation_code"];
+    if(bvalidation&& pwd.length>0)
+    {
+        
+        
+        //UIAlertControllerStyle两种类型UIAlertControllerStyleAlert类似UIAlertView
+        //UIAlertControllerStyleActionSheet类似UIActionSheet
+        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Authorization Verification" message:@"Please enter authorization code." preferredStyle:UIAlertControllerStyleAlert];
+        //block代码块取代了delegate
+        
+        
+        [alertControl addTextFieldWithConfigurationHandler:^(UITextField *textField) {
+            
+            
+            
+        }];
+        
+        UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
+            
+            UITextField *name = alertControl.textFields.firstObject;
+            if(![name.text isEqualToString:pwd])
+            {
+                [RAUtils message_alert:@"You are not authorized to change this field" title:@"Authorization verification failed." controller:self];
+                return;
+            }
+            else
+            {
+                [self signature:touchImageView];
+            }
+            
+        }];
+        
+        UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
+            DebugLog(@"Cancel");
+            return;
+        }];
+        [alertControl addAction:actionOne];
+        
+        [alertControl addAction:alertthree];
+        
+        //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
+        
+        
+        [self presentViewController:alertControl animated:YES completion:nil];
+        
+        
+        
+    }
+    else
+    {
+        [self signature:touchImageView];
+    }
+    ////    menu.selector = self.selector;
+    ////
+    ////    menu.selectordelegate = self;
+    //
+    //    // 1.创建一个UIPopover
+    //    UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:[[UINavigationController alloc] initWithRootViewController:menu]];
+    //
+    //
+    //
+    //    UIPopoverPresentationController
+    //    // 2.设置尺寸
+    //    //    popover.popoverContentSize = CGSizeMake(320, 44 * 5);
+    //
+    //    // 3.从哪里显示出来 --> 指向item
+    //
+    //    [popover presentPopoverFromRect:self.view.frame   inView:self.view permittedArrowDirections:0 animated:YES];
+    //    //  [popover presentPopoverFromBarButtonItem:item permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
+    //
+    ////    self.popover = popover;
+    //    popover pop
+    //
+    // [self performSegueWithIdentifier:@"selector_popover" sender:self];
+    
+    
+    //    __block int tag = touchImageView.tag;
+    //    UIViewController* vc=[RAUtils getViewController :touchImageView];
+    //
+    //    if(self.editable==true)
+    //    {
+    //
+    //
+    //        ImageUploadViewController * uploadvc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"ImageUploadViewController"];
+    //
+    //        //        UIImage* img =[self.buttonImg backgroundImageForState:UIControlStateNormal];;
+    //
+    //        if(self.img_validate)
+    //            uploadvc.img= touchImageView.image;
+    //
+    //        uploadvc.returnValue = ^(NSString* url_down,NSString* url_up,UIImage* img)
+    //        {
+    //
+    //            self.imgs[tag] = url_up;
+    //
+    //            NSString* newurl=[RAUtils arr2string:self.imgs separator:@"," trim:false];
+    //
+    //            touchImageView.image=img;
+    //
+    //            if(self.imgChanged)
+    //                self.imgChanged(url_down,newurl,tag,url_up);
+    //
+    //        };
+    //
+    //        [vc.navigationController pushViewController:uploadvc animated:false];
+    //    }
+    //    else
+    //    {
+    //        if(touchImageView.image==nil)
+    //            return ;
+    //        ImageViewController * imagevc =[ vc.storyboard instantiateViewControllerWithIdentifier:@"ImageViewController"];
+    //
+    //
+    //        UIImage* img=touchImageView.image;
+    //
+    //        if(self.img_validate)
+    //            imagevc.image = img;//.imageView.image = [self.buttonImg backgroundImageForState:UIControlStateNormal];
+    //
+    //        //        uploadvc.returnValue = ^(NSString* url_down,NSString* url_up,UIImage* img)
+    //        //        {
+    //        //
+    //        //            [self.buttonImg setBackgroundImage:img forState:UIControlStateNormal];
+    //        //
+    //        //            if(self.imgChanged)
+    //        //                self.imgChanged(url_down,url_up);
+    //        //
+    //        //        };
+    //
+    //        [vc.navigationController pushViewController:imagevc animated:false];
+    //    }
+    //    //    bundleVC.content_data = self.bundle_item;
+    //
+    
+}
+
+#pragma mark Responding to keyboard events
+- (CGRect)relativeFrameForScreenWithView:(UIView *)v
+{
+    UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
+    CGRect rect=[v convertRect: v.bounds toView:window];
+    return rect;
+    
+    
+    //    BOOL iOS7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7;
+    //
+    //    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
+    //    if (!iOS7) {
+    //        screenHeight -= 20;
+    //    }
+    //    UIView *view = v;
+    //    CGFloat x = .0;
+    //    CGFloat y = .0;
+    //    while (view.frame.size.width != 320 || view.frame.size.height != screenHeight) {
+    //        x += view.frame.origin.x;
+    //        y += view.frame.origin.y;
+    //        view = view.superview;
+    //        if ([view isKindOfClass:[UIScrollView class]]) {
+    //            x -= ((UIScrollView *) view).contentOffset.x;
+    //            y -= ((UIScrollView *) view).contentOffset.y;
+    //        }
+    //    }
+    //    return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
+}
+
+- (void)keyboardWillChangeFrame:(NSNotification *)notification {
+    NSLog(@"keyboardWillChangeFrame");
+}
+- (void)keyboardWillShow:(NSNotification *)notification {
+    NSLog(@"keyboardWillShow");
+    
+    if(self.keyboard_show)
+    return;
+    
+    self.keyboard_show=true;
+    /*
+     Reduce the size of the text view so that it's not obscured by the keyboard.
+     Animate the resize so that it's in sync with the appearance of the keyboard.
+     */
+    
+    NSDictionary *userInfo = [notification userInfo];
+    
+    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
+    CGSize keyboardSize = [aValue CGRectValue].size;
+    NSLog(@"keyboard height:%f",keyboardSize.height);
+    
+    
+    CGRect cellrect_screen = [self relativeFrameForScreenWithView:self.hotTextView];
+    CGRect rect_screen = [ UIScreen mainScreen ].bounds;
+    int cellpos = cellrect_screen.origin.y+cellrect_screen.size.height;
+    if(cellpos>rect_screen.size.height-keyboardSize.height)
+    {
+        //  self.resize = true;
+        
+        self.keyboard_h =keyboardSize.height;
+        CGPoint contentOffsetPoint = self.pdfScrollView.contentOffset;
+        CGSize contentSize =self.pdfScrollView.contentSize;//frame.size;
+        CGSize size1 = self.pdfScrollView.bounds.size;
+        NSLog(@"frame:%@ bound:%@", NSStringFromCGSize(contentSize),NSStringFromCGSize(size1) );
+        contentSize.height+=self.keyboard_h;
+        contentOffsetPoint.y+=self.keyboard_h;
+        
+        
+        
+        self.pdfScrollView.contentSize =contentSize;
+        self.pdfScrollView.contentOffset=contentOffsetPoint;
+        
+    }
+    
+    
+    //    self.pdfScrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-self.keyboard_h);
+    
+    //    CGSize tablecontent =self.editorTable.contentSize;
+    //    tablecontent.height=tablecontent.height+self.keyboard_h;
+    //    self.editorTable.contentSize=tablecontent;
+    //    }
+    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
+    //  [self moveInputBarWithKeyboardHeight:keyboardRect.size.height withDuration:animationDuration];
+}
+- (void)keyboardWillHide:(NSNotification *)notification {
+    NSLog(@"keyboardWillHide");
+    
+    self.keyboard_show=false;
+    //    NSDictionary* userInfo = [notification userInfo];
+    
+    /*
+     Restore the size of the text view (fill self's view).
+     Animate the resize so that it's in sync with the disappearance of the keyboard.
+     */
+    //    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
+    //    NSTimeInterval animationDuration;
+    //    [animationDurationValue getValue:&animationDuration];
+    
+    
+    CGPoint contentOffsetPoint = self.pdfScrollView.contentOffset;
+    CGSize contentSize =self.pdfScrollView.contentSize;//frame.size;
+    contentSize.height-=self.keyboard_h;
+    
+    contentOffsetPoint.y-=self.keyboard_h;
+    
+    self.pdfScrollView.contentSize=contentSize;
+    self.pdfScrollView.contentOffset=contentOffsetPoint;
+    //    CGSize tablecontent =self.pdfScrollView.contentSize;
+    //    tablecontent.height=tablecontent.height-self.keyboard_h;
+    //    self.editorTable.contentSize=tablecontent;
+    
+    //   self.pdfScrollView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
+    
+    self.keyboard_h= 0;
+    //    NSLog(@"before refresh %@",NSStringFromCGSize(self.editorTable.contentSize));
+    
+    
+    //    if(self.resize)
+    //    {
+    //        NSTimeInterval animationDuration = 0.30f;
+    //        CGRect frame = self.view.frame;
+    //        //    if(prewTag == textField.tag) //当结束编辑的View的TAG是上次的就移动
+    //        //    {   //还原界面
+    //        //        moveY =  prewMoveY;
+    //        frame.origin.y +=self.ioffset;
+    //        frame.size. height -=self.ioffset;
+    //        self.view.frame = frame;
+    //        //    }
+    //        //self.view移回原位置
+    //        [UIView beginAnimations:@"ResizeView" context:nil];
+    //        [UIView setAnimationDuration:animationDuration];
+    //        self.view.frame = frame;
+    //        [UIView commitAnimations];
+    //        //[textField resignFirstResponder];
+    //        self.ioffset=0;
+    //    }
+    
+    
+    //  [self moveInputBarWithKeyboardHeight:0.0 withDuration:animationDuration];
+}
+
+
+
+@end

BIN
RA Image/RA Image.xcodeproj/project.xcworkspace/xcuserdata/ray.xcuserdatad/UserInterfaceState.xcuserstate