KMPDFPrintManageWindowController.m 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. //
  2. // KMPDFPrintManageWindowController.m
  3. // PDF Reader
  4. //
  5. // Created by 蒋志鹏 on 2018/6/19.
  6. // Copyright © 2018年 Kdan Mobile. All rights reserved.
  7. //
  8. #import "KMPDFPrintManageWindowController.h"
  9. #import "NSMutableArray+KMOddEvenPartFetch.h"
  10. #import "KMPDFMultiplePrintWindowController.h"
  11. #import "KMPDFPosterPrintWindowController.h"
  12. #import "KMPDFBookletWindowController.h"
  13. //#import "NSWindowController_SKExtensions.h"
  14. //#import "KMBookletMaskView.h"
  15. //#import "KMFileAttribute.h"
  16. #import "PDF_Reader_Pro-Swift.h"
  17. #import <Quartz/Quartz.h>
  18. #define kPrintFolderPath [[NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSBundle mainBundle].bundleIdentifier]
  19. #define kPrintManageFileSavePath [[[NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSBundle mainBundle].bundleIdentifier] stringByAppendingPathComponent:@"printManage.pdf"]
  20. #define kPreviewMaxWidth 207.0
  21. #define kPreviewMaxHeight 289.0
  22. typedef NS_ENUM(NSUInteger, kPrintStyle) {
  23. kPrintStyle_DocumentOnly = 0,
  24. kPrintStyle_DocumentAndMarkups,
  25. kPrintStyle_DocumentAndStamps,
  26. kPrintStyle_FormsOnly
  27. };
  28. typedef NS_ENUM(NSUInteger, kPageSelectStyle) {
  29. kPageSelectStyle_AllPage = 0,
  30. kPageSelectStyle_OddPage,
  31. kPageSelectStyle_EvenPage,
  32. kPageSelectStyle_CurrentPage,
  33. kPageSelectStyle_HandInput
  34. };
  35. @interface KMPrintParameter :NSObject
  36. @property (nonatomic, assign) kPrintStyle printStyle;
  37. @property (nonatomic, assign) BOOL reversePages;
  38. @property (nonatomic, assign) kPageSelectStyle pageSelectStyle;
  39. @end
  40. @implementation KMPrintParameter
  41. - (void)dealloc {
  42. }
  43. @end
  44. @interface KMPDFPrintManageWindowController () <NSTextFieldDelegate>
  45. //当前文档
  46. @property (nonatomic, retain) PDFDocument *pdfDocument;
  47. @property (nonatomic, retain) PDFPage *currentPage;
  48. //model 管理
  49. @property (nonatomic, assign) NSModalSession modalSession;
  50. @property (assign) IBOutlet NSTextField *pagesSettingLabel;
  51. @property (assign) IBOutlet NSButton *allPageButton;
  52. @property (assign) IBOutlet NSButton *oddPageButton;
  53. @property (assign) IBOutlet NSButton *evenPageButton;
  54. @property (assign) IBOutlet NSButton *currentPageButton;
  55. @property (assign) IBOutlet NSButton *handInputPageButton;
  56. @property (assign) IBOutlet NSTextField *intputPageRangeTextField;
  57. @property (assign) IBOutlet NSButton *reversePageButton;
  58. @property (assign) IBOutlet NSTextField *printSettingLabel;
  59. @property (assign) IBOutlet NSButton *printDocumentButton;
  60. @property (assign) IBOutlet NSButton *printDocumentAndMarkupsButton;
  61. @property (assign) IBOutlet NSButton *printDocumentAndStampsButton;
  62. @property (assign) IBOutlet NSButton *printFormOnlyButton;
  63. @property (assign) IBOutlet NSButton *printButton;
  64. @property (assign) IBOutlet NSButton *cancelButton;
  65. @property (assign) IBOutlet NSButton *posterButton;
  66. @property (assign) IBOutlet NSButton *mutilpleButton;
  67. @property (assign) IBOutlet NSButton *bookletButton;
  68. @property (assign) IBOutlet NSTextField *currentPageNumberTextField;
  69. @property (assign) IBOutlet NSTextField *totalPageNumberLabel;
  70. @property (assign) IBOutlet NSLayoutConstraint *previewHeightContraint;
  71. @property (assign) IBOutlet NSLayoutConstraint *previewWidthContraint;
  72. @property (assign) IBOutlet PDFView *preview;
  73. @property (nonatomic, retain) KMPrintParameter *printParameter;
  74. @property (nonatomic, retain) NSMutableArray *selectPagesIndexArray;
  75. @property (nonatomic, retain) KMBookletMaskView *maskView;
  76. @property (nonatomic, copy) printCallBack callBack;
  77. @property (retain) NSArray *pageButtons;
  78. @property(nonatomic, strong) KMPDFPosterPrintWindowController *posterVC;
  79. @property(nonatomic, strong) KMPDFMultiplePrintWindowController *multipleVC;
  80. @property(nonatomic, strong) KMPDFBookletWindowController *bookletVC;
  81. @end
  82. @implementation KMPDFPrintManageWindowController
  83. - (void)dealloc {
  84. }
  85. #pragma mark - init Method
  86. - (instancetype)initWithPDFDocument:(PDFDocument *)pdfDocument currentPage:(PDFPage *)currentpage completeHandler:(printCallBack)printHandler
  87. {
  88. self = [super initWithWindowNibName:@"KMPDFPrintManageWindowController"];
  89. if (self) {
  90. [self showWaitting];
  91. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  92. if (![[NSFileManager defaultManager] fileExistsAtPath:kPrintFolderPath]) {
  93. if (![[NSFileManager defaultManager] createDirectoryAtPath:kPrintFolderPath withIntermediateDirectories:NO attributes:nil error:nil]) {
  94. return;
  95. }
  96. }
  97. self.callBack = printHandler;
  98. [pdfDocument writeToURL:[NSURL fileURLWithPath:kPrintManageFileSavePath]];
  99. self.pdfDocument = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:kPrintManageFileSavePath]];
  100. dispatch_async(dispatch_get_main_queue(), ^{
  101. [self hideWaitting];
  102. if (self.pdfDocument) {
  103. // if([self.pdfDocument isLocked]) {
  104. // [self.pdfDocument unlockWithPassword:pdfDocument.password];
  105. // }
  106. [self setTextFieldDelegate];
  107. [self initFormatter];
  108. [self configuInitializationParameter];
  109. [self produceNewPDFForPreview];
  110. }else{
  111. [self close];
  112. }
  113. });
  114. });
  115. }
  116. return self;
  117. }
  118. #pragma mark - 生命周期
  119. - (void)windowDidLoad {
  120. [super windowDidLoad];
  121. [self localizedLanguage];
  122. [self configuInitializationParameter];
  123. if (!self.pdfDocument) {
  124. return;
  125. }
  126. [self setTextFieldDelegate];
  127. [self initFormatter];
  128. [self produceNewPDFForPreview];
  129. }
  130. - (BOOL)windowShouldClose:(id)sender
  131. {
  132. return YES;
  133. }
  134. #pragma mark - Private Methods
  135. - (void)localizedLanguage
  136. {
  137. self.window.title = NSLocalizedString(@"Pages to Print", nil);
  138. self.pagesSettingLabel.stringValue = NSLocalizedString(@"Page Range:", nil);
  139. self.allPageButton.title = NSLocalizedString(@"All Pages", nil);
  140. self.oddPageButton.title = NSLocalizedString(@"Odd Pages Only", nil);
  141. self.evenPageButton.title = NSLocalizedString(@"Even Pages Only", nil);
  142. self.reversePageButton.title = NSLocalizedString(@"Reverse pages", nil);
  143. self.printSettingLabel.stringValue = NSLocalizedString(@"Comments & Forms:", nil);
  144. self.printDocumentButton.title = NSLocalizedString(@"Document", nil);
  145. self.printDocumentAndMarkupsButton.title = NSLocalizedString(@"Document and Markups", nil);
  146. self.printDocumentAndStampsButton.title = NSLocalizedString(@"Document and Stamps", nil);
  147. self.printFormOnlyButton.title = NSLocalizedString(@"Form fields only", nil);
  148. self.posterButton.title = NSLocalizedString(@"Poster", nil);
  149. self.mutilpleButton.title = NSLocalizedString(@"Multiple", nil);
  150. self.bookletButton.title = NSLocalizedString(@"Booklet", nil);
  151. self.cancelButton.title = NSLocalizedString(@"Cancel", nil);
  152. self.printButton.title = NSLocalizedString(@"Printer", nil);
  153. self.currentPageButton.title= NSLocalizedString(@"Current Page", nil);
  154. [self.intputPageRangeTextField.cell setPlaceholderString:NSLocalizedString(@"e.g. 1,3-5,10", nil)];
  155. }
  156. - (void)setTextFieldDelegate
  157. {
  158. self.intputPageRangeTextField.delegate = self;
  159. self.currentPageNumberTextField.delegate = self;
  160. }
  161. - (void)initFormatter
  162. {
  163. NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
  164. formatter.numberStyle = NSNumberFormatterNoStyle;
  165. self.currentPageNumberTextField.formatter = formatter;
  166. }
  167. - (void)configuInitializationParameter
  168. {
  169. if (!self.printParameter) {
  170. self.printParameter = [[KMPrintParameter alloc] init];
  171. self.printParameter.reversePages = NO;
  172. self.printParameter.printStyle = kPrintStyle_DocumentAndMarkups;
  173. self.printParameter.pageSelectStyle = kPageSelectStyle_AllPage;
  174. }
  175. self.preview.autoScales = YES;
  176. self.preview.backgroundColor = [NSColor whiteColor];
  177. self.preview.wantsLayer = YES;
  178. self.preview.layer.borderColor = [NSColor blackColor].CGColor;
  179. self.preview.layer.borderWidth = 2;
  180. self.intputPageRangeTextField.enabled = NO;
  181. }
  182. - (void)adjustPreviewSizeWithPage:(PDFPage *)page
  183. {
  184. CGSize pageSize = [page boundsForBox:kPDFDisplayBoxMediaBox].size;
  185. if (page.rotation %180) {
  186. pageSize = CGSizeMake(pageSize.height, pageSize.width);
  187. }
  188. // NSLog(@"pageSize:%f,%f",pageSize.width,pageSize.height);
  189. CGFloat wRatio = kPreviewMaxWidth/pageSize.width;
  190. CGFloat hRatio = kPreviewMaxHeight/pageSize.height;
  191. CGFloat ratio = MIN(wRatio, hRatio);
  192. if (ratio == hRatio) {
  193. self.previewHeightContraint.constant = kPreviewMaxHeight;
  194. self.previewWidthContraint.constant = kPreviewMaxHeight * pageSize.width/pageSize.height;
  195. } else {
  196. self.previewWidthContraint.constant = kPreviewMaxWidth;
  197. self.previewHeightContraint.constant = kPreviewMaxWidth * pageSize.height/pageSize.width;
  198. }
  199. }
  200. - (NSMutableArray *)fetchPagesArrayWithParameter:(kPageSelectStyle)selectStyle
  201. {
  202. NSMutableArray *pagesArray = [NSMutableArray array];
  203. for (NSInteger i = 0; i < self.pdfDocument.pageCount; i ++) {
  204. PDFPage *page = [[self.pdfDocument pageAtIndex:i] copy];
  205. [pagesArray addObject:page];
  206. self.currentPage = self.preview.currentPage;
  207. }
  208. switch (selectStyle) {
  209. case kPageSelectStyle_AllPage:
  210. break;
  211. case kPageSelectStyle_OddPage:
  212. [pagesArray subArrayWithType:KMSubArrayTypeOdd];
  213. break;
  214. case kPageSelectStyle_EvenPage:
  215. [pagesArray subArrayWithType:KMSubArrayTypeEven];
  216. break;
  217. case kPageSelectStyle_CurrentPage:
  218. {
  219. [pagesArray removeAllObjects];
  220. PDFPage *page = [self.currentPage copy];
  221. [pagesArray addObject:page];
  222. }
  223. break;
  224. case kPageSelectStyle_HandInput:
  225. {
  226. [pagesArray removeAllObjects];
  227. for (NSNumber *pageIndexNum in self.selectPagesIndexArray) {
  228. PDFPage *page = [[self.pdfDocument pageAtIndex:[pageIndexNum integerValue] - 1] copy];
  229. [pagesArray addObject:page];
  230. }
  231. }
  232. break;
  233. default:
  234. break;
  235. }
  236. return pagesArray;
  237. }
  238. - (void)pageRangeSelectWithCurrentSelectStyle:(NSButton *)sender
  239. {
  240. self.allPageButton.state = NO;
  241. self.oddPageButton.state = NO;
  242. self.evenPageButton.state = NO;
  243. self.currentPageButton.state = NO;
  244. self.handInputPageButton.state = NO;
  245. if (sender) {
  246. sender.state = YES;
  247. }
  248. }
  249. - (void)printStyleSelectWithCurrentSelectStyle:(NSButton *)sender
  250. {
  251. self.printDocumentButton.state = NO;
  252. self.printDocumentAndMarkupsButton.state = NO;
  253. self.printDocumentAndStampsButton.state = NO;
  254. self.printFormOnlyButton.state = NO;
  255. if (sender) {
  256. sender.state = YES;
  257. }
  258. }
  259. - (void)produceNewPDFForPreview
  260. {
  261. NSMutableArray *pagesArray = [self fetchPagesArrayWithParameter:self.printParameter.pageSelectStyle];
  262. if (pagesArray.count < 1) {
  263. return;
  264. }
  265. if (self.printParameter.reversePages) {
  266. NSMutableArray *tempArray = [NSMutableArray array];
  267. for (NSInteger i = 0; i < pagesArray.count; i ++) {
  268. [tempArray addObject:[pagesArray objectAtIndex:pagesArray.count - i -1]];
  269. }
  270. [pagesArray removeAllObjects];
  271. [pagesArray addObjectsFromArray:tempArray];
  272. }
  273. [self handleAnnotationWithPrintParameter:pagesArray printStyle:self.printParameter.printStyle];
  274. PDFDocument *document = [[PDFDocument alloc] init];
  275. for (NSInteger i = 0; i < pagesArray.count; i++) {
  276. PDFPage *page = [pagesArray objectAtIndex:i];
  277. [document insertPage:page atIndex:document.pageCount];
  278. }
  279. self.preview.document = document;
  280. [self.preview goToFirstPage:nil];
  281. [self adjustPreviewSizeWithPage:[document pageAtIndex:0]];
  282. self.currentPageNumberTextField.stringValue = @"1";
  283. self.totalPageNumberLabel.stringValue = [NSString stringWithFormat:@" / %ld",pagesArray.count];
  284. }
  285. - (void)handleAnnotationWithPrintParameter:(NSMutableArray *)pagesArray
  286. printStyle:(kPrintStyle)printStyle
  287. {
  288. for (PDFPage *page in pagesArray) {
  289. NSMutableArray *annotationArray = [NSMutableArray new];
  290. for (PDFAnnotation *annotation in page.annotations) {
  291. [annotationArray addObject:annotation];
  292. }
  293. switch (printStyle) {
  294. case kPrintStyle_DocumentOnly:
  295. {
  296. for (PDFAnnotation *annotation in annotationArray) {
  297. [annotation.page removeAnnotation:annotation];
  298. }
  299. }
  300. break;
  301. case kPrintStyle_DocumentAndStamps:
  302. {
  303. for (PDFAnnotation *annotation in annotationArray) {
  304. if (![annotation isKindOfClass:[PDFAnnotationStamp class]]) {
  305. [annotation.page removeAnnotation:annotation];
  306. }
  307. }
  308. }
  309. break;
  310. default:
  311. break;
  312. }
  313. }
  314. }
  315. - (void)showCriticalAlert:(NSString *)alertMsg
  316. {
  317. NSAlert *alert = [[NSAlert alloc] init];
  318. [alert setAlertStyle:NSCriticalAlertStyle];
  319. if (alertMsg) {
  320. [alert setInformativeText:alertMsg];
  321. } else {
  322. [alert setMessageText:[NSString stringWithFormat:@"%@ %@",self.pdfDocument.documentURL.path.lastPathComponent,NSLocalizedString(@"Invalid page range or the page number is out of range. Please try again.", nil)]];
  323. }
  324. [alert runModal];
  325. }
  326. #pragma mark - 按钮点击方法
  327. //所有页
  328. - (IBAction)buttonItemClicked_AllPages:(NSButton *)sender
  329. {
  330. if (sender.state) {
  331. if (self.printParameter.pageSelectStyle == kPageSelectStyle_AllPage) {
  332. return;
  333. }
  334. self.intputPageRangeTextField.stringValue = @"";
  335. self.intputPageRangeTextField.enabled = NO;
  336. [self pageRangeSelectWithCurrentSelectStyle:sender];
  337. self.printParameter.pageSelectStyle = kPageSelectStyle_AllPage;
  338. if (self.printParameter.printStyle == kPrintStyle_FormsOnly) {
  339. [self createOnlyFormDocument];
  340. } else {
  341. [self produceNewPDFForPreview];
  342. }
  343. }
  344. }
  345. //奇数页
  346. - (IBAction)buttonItemClicked_OddPages:(NSButton *)sender
  347. {
  348. if (sender.state) {
  349. if (self.printParameter.pageSelectStyle == kPageSelectStyle_OddPage) {
  350. return;
  351. }
  352. self.intputPageRangeTextField.stringValue = @"";
  353. self.intputPageRangeTextField.enabled = NO;
  354. [self pageRangeSelectWithCurrentSelectStyle:sender];
  355. self.printParameter.pageSelectStyle = kPageSelectStyle_OddPage;
  356. if (self.printParameter.printStyle == kPrintStyle_FormsOnly) {
  357. [self createOnlyFormDocument];
  358. } else {
  359. [self produceNewPDFForPreview];
  360. }
  361. }
  362. }
  363. //偶数页
  364. - (IBAction)buttonItemClicked_EvenPages:(NSButton *)sender
  365. {
  366. if (sender.state) {
  367. if (self.printParameter.pageSelectStyle == kPageSelectStyle_EvenPage) {
  368. return;
  369. }
  370. self.intputPageRangeTextField.stringValue = @"";
  371. self.intputPageRangeTextField.enabled = NO;
  372. [self pageRangeSelectWithCurrentSelectStyle:sender];
  373. self.printParameter.pageSelectStyle = kPageSelectStyle_EvenPage;
  374. if (self.printParameter.printStyle == kPrintStyle_FormsOnly) {
  375. [self createOnlyFormDocument];
  376. } else {
  377. [self produceNewPDFForPreview];
  378. }
  379. }
  380. }
  381. //当前页面
  382. - (IBAction)buttonItemClicked_CurrentPage:(NSButton *)sender
  383. {
  384. if (sender.state) {
  385. if (self.printParameter.pageSelectStyle == kPageSelectStyle_CurrentPage) {
  386. return;
  387. }
  388. self.intputPageRangeTextField.stringValue = @"";
  389. self.intputPageRangeTextField.enabled = NO;
  390. [self pageRangeSelectWithCurrentSelectStyle:sender];
  391. self.printParameter.pageSelectStyle = kPageSelectStyle_CurrentPage;
  392. if (self.printParameter.printStyle == kPrintStyle_FormsOnly) {
  393. [self createOnlyFormDocument];
  394. } else {
  395. [self produceNewPDFForPreview];
  396. }
  397. }
  398. }
  399. //手动输入页码
  400. - (IBAction)buttonItemClicked_handInputPages:(NSButton *)sender
  401. {
  402. if (sender.state) {
  403. if (self.printParameter.pageSelectStyle == kPageSelectStyle_HandInput) {
  404. return;
  405. }
  406. self.intputPageRangeTextField.enabled = YES;
  407. self.intputPageRangeTextField.stringValue = @"";
  408. [self.window makeFirstResponder:self.intputPageRangeTextField];
  409. [self pageRangeSelectWithCurrentSelectStyle:sender];
  410. self.printParameter.pageSelectStyle = kPageSelectStyle_HandInput;
  411. }
  412. }
  413. //反排序
  414. - (IBAction)buttonItemClicked_Reversepages:(NSButton *)sender
  415. {
  416. self.printParameter.reversePages = sender.state;
  417. if (self.printParameter.printStyle == kPrintStyle_FormsOnly) {
  418. [self createOnlyFormDocument];
  419. } else {
  420. [self produceNewPDFForPreview];
  421. }
  422. }
  423. //只打印Document
  424. - (IBAction)buttonItemClicked_PrintDocumentOnly:(NSButton *)sender
  425. {
  426. if (sender.state) {
  427. if (self.printParameter.printStyle == kPrintStyle_DocumentOnly) {
  428. return;
  429. }
  430. [self printStyleSelectWithCurrentSelectStyle:sender];
  431. self.printParameter.printStyle = kPrintStyle_DocumentOnly;
  432. [self produceNewPDFForPreview];
  433. }
  434. }
  435. //打印Document和注释
  436. - (IBAction)buttonItemClicked_PrintDocumentAndMarkups:(NSButton *)sender
  437. {
  438. if (sender.state) {
  439. if (self.printParameter.printStyle == kPrintStyle_DocumentAndMarkups) {
  440. return;
  441. }
  442. [self printStyleSelectWithCurrentSelectStyle:sender];
  443. self.printParameter.printStyle = kPrintStyle_DocumentAndMarkups;
  444. [self produceNewPDFForPreview];
  445. }
  446. }
  447. //打印Document和Stamp类型注释
  448. - (IBAction)buttonItemClicked_PrintDocumentAndStamps:(NSButton *)sender
  449. {
  450. if (sender.state) {
  451. if (self.printParameter.printStyle == kPrintStyle_DocumentAndStamps) {
  452. return;
  453. }
  454. [self printStyleSelectWithCurrentSelectStyle:sender];
  455. self.printParameter.printStyle = kPrintStyle_DocumentAndStamps;
  456. [self produceNewPDFForPreview];
  457. }
  458. }
  459. - (IBAction)buttonItemClicked_PrintFormOnly:(NSButton *)sender {
  460. if (sender.state) {
  461. if (self.printParameter.printStyle == kPrintStyle_FormsOnly) {
  462. return;
  463. }
  464. [self printStyleSelectWithCurrentSelectStyle:sender];
  465. self.printParameter.printStyle = kPrintStyle_FormsOnly;
  466. [self createOnlyFormDocument];
  467. }
  468. }
  469. //Preview上一页
  470. - (IBAction)buttonItemClicked_PreviousPage:(NSButton *)sender
  471. {
  472. if ([self.preview canGoToPreviousPage]) {
  473. [self.preview goToPreviousPage:nil];
  474. self.currentPageNumberTextField.stringValue = [NSString stringWithFormat:@"%ld",[self.preview.document indexForPage:[self.preview currentPage]] + 1];
  475. [self adjustPreviewSizeWithPage:[self.preview currentPage]];
  476. }
  477. }
  478. //PreView下一页
  479. - (IBAction)buttonItemClicked_NextPage:(NSButton *)sender
  480. {
  481. if ([self.preview canGoToNextPage]) {
  482. [self.preview goToNextPage:nil];
  483. self.currentPageNumberTextField.stringValue = [NSString stringWithFormat:@"%ld",[self.preview.document indexForPage:[self.preview currentPage]] + 1];
  484. [self adjustPreviewSizeWithPage:[self.preview currentPage]];
  485. }
  486. }
  487. //Poster
  488. - (IBAction)buttonItemClicked_Poster:(NSButton *)sender
  489. {
  490. if (![KMMemberInfo shared].isMemberAllFunction) {
  491. [self close];
  492. NSWindowController *winC = [KMProductCompareWC shared];
  493. winC.kEventName = @"MenuBar_PrintPoster_BuyNow";
  494. [[KMMemberInfo shared] advancedFunctionUsage];
  495. return;
  496. }
  497. [self close];
  498. _posterVC = [[KMPDFPosterPrintWindowController alloc] initWithPDFDocument:self.pdfDocument];
  499. [[NSApp mainWindow] beginSheet:_posterVC.window completionHandler:^(NSModalResponse returnCode) {
  500. }];
  501. // [posterVC beginSheetModalForWindow:[NSApp mainWindow] completionHandler:nil];
  502. }
  503. //Multiple
  504. - (IBAction)buttonItemClicked_Multiple:(NSButton *)sender
  505. {
  506. if (![KMMemberInfo shared].isMemberAllFunction) {
  507. [self close];
  508. NSWindowController *winC = [KMProductCompareWC shared];
  509. winC.kEventName = @"MenuBar_PrintMultiple_BuyNow";
  510. [[KMMemberInfo shared] advancedFunctionUsage];
  511. return;
  512. }
  513. [self close];
  514. _multipleVC = [[KMPDFMultiplePrintWindowController alloc] initWithPDFDocument:self.pdfDocument];
  515. // [multipleVC beginSheetModalForWindow:[NSApp mainWindow] completionHandler:nil];
  516. [[NSApp mainWindow] beginSheet:_multipleVC.window completionHandler:^(NSModalResponse returnCode) {
  517. }];
  518. }
  519. //Booklet
  520. - (IBAction)buttonItemClicked_Booklet:(NSButton *)sender
  521. {
  522. if (![KMMemberInfo shared].isMemberAllFunction) {
  523. [self close];
  524. NSWindowController *winC = [KMProductCompareWC shared];
  525. winC.kEventName = @"MenuBar_PrintBooklet_BuyNow";
  526. [[KMMemberInfo shared] advancedFunctionUsage];
  527. return;
  528. }
  529. [self close];
  530. _bookletVC = [[KMPDFBookletWindowController alloc] initWithDocument:self.pdfDocument];
  531. // [bookletVC beginSheetModalForWindow:[NSApp mainWindow] completionHandler:nil];
  532. [[NSApp mainWindow] beginSheet:_bookletVC.window completionHandler:^(NSModalResponse returnCode) {
  533. }];
  534. }
  535. //取消
  536. - (IBAction)buttonItemClicked_Cancel:(NSButton *)sender
  537. {
  538. [self close];
  539. }
  540. - (void)close{
  541. if (self.window.isSheet) {
  542. [self.window.sheetParent endSheet:self.window];
  543. // [self dismissSheet:nil];
  544. } else {
  545. [super close];
  546. }
  547. }
  548. //打印
  549. - (IBAction)buttonItemClicked_Print:(NSButton *)sender
  550. {
  551. [self.window makeFirstResponder:self.preview];
  552. if (self.callBack) {
  553. [self close];
  554. self.callBack(self.preview.document);
  555. }
  556. }
  557. #pragma mark - NSTextField Delegate
  558. - (void)controlTextDidEndEditing:(NSNotification *)notification
  559. {
  560. NSTextField *textField = notification.object;
  561. if ([textField isEqual:self.intputPageRangeTextField]) {
  562. if (!self.selectPagesIndexArray) {
  563. self.selectPagesIndexArray = [NSMutableArray array];
  564. }else{
  565. [self.selectPagesIndexArray removeAllObjects];
  566. }
  567. KMFileAttribute *fileAttribute = [[KMFileAttribute alloc] init];
  568. fileAttribute.filePath = [self.pdfDocument.documentURL path];
  569. fileAttribute.bAllPage = NO;
  570. fileAttribute.pagesString = self.intputPageRangeTextField.stringValue;
  571. if ([fileAttribute fetchSelectPages]) {
  572. [self.selectPagesIndexArray addObjectsFromArray: [fileAttribute fetchSelectPages]];
  573. if (self.printParameter.printStyle == kPrintStyle_FormsOnly) {
  574. [self createOnlyFormDocument];
  575. } else {
  576. [self produceNewPDFForPreview];
  577. }
  578. }else{
  579. [self showCriticalAlert:nil];
  580. }
  581. }else if ([textField isEqual:self.currentPageNumberTextField]){
  582. PDFPage *targetPage = [self.preview.document pageAtIndex:[self.currentPageNumberTextField.stringValue integerValue] - 1];
  583. if (targetPage) {
  584. [self.preview goToPage:targetPage];
  585. }
  586. }
  587. }
  588. - (void)controlTextDidChange:(NSNotification *)notification
  589. {
  590. NSTextField *textField = notification.object;
  591. if ([textField isEqual:self.currentPageNumberTextField]) {
  592. NSString *string = [self.currentPageNumberTextField.formatter stringFromNumber:[NSNumber numberWithFloat:[self.currentPageNumberTextField.stringValue integerValue]]];
  593. if ([string integerValue] > self.preview.document.pageCount) {
  594. string = [NSString stringWithFormat:@"%ld",self.preview.document.pageCount];
  595. }else if ([string integerValue] <= 0){
  596. string = @"1";
  597. }
  598. self.currentPageNumberTextField.stringValue = string;
  599. }
  600. }
  601. #pragma mark - 开始转圈,隐藏转圈提示
  602. - (void)showWaitting
  603. {
  604. if (!_maskView) {
  605. _maskView = [[KMBookletMaskView alloc] initWithFrame:NSMakeRect(0, 0, self.window.frame.size.width, self.window.frame.size.height)];
  606. }
  607. [self.window.contentView addSubview:_maskView];
  608. }
  609. - (void)hideWaitting
  610. {
  611. [_maskView removeFromSuperview];
  612. }
  613. //创建一个新的空白只打印formPDF
  614. - (void)createOnlyFormDocument {
  615. NSMutableArray *pagesArray = [self fetchPagesArrayWithParameter:self.printParameter.pageSelectStyle];
  616. if (pagesArray.count < 1) {
  617. NSBeep();
  618. return;
  619. }
  620. if (self.printParameter.reversePages) {
  621. pagesArray = [NSMutableArray arrayWithArray:[[pagesArray reverseObjectEnumerator] allObjects]];
  622. }
  623. //取最大宽高作为画布大小
  624. CGFloat maxWidth = 0;
  625. CGFloat maxHeight = 0;
  626. for (NSInteger i = 0; i < pagesArray.count; i++) {
  627. PDFPage *page = [pagesArray objectAtIndex:i];
  628. CGRect rect = [page boundsForBox:kPDFDisplayBoxMediaBox];
  629. maxWidth = MAX(maxWidth, CGRectGetWidth(rect));
  630. maxHeight = MAX(maxHeight, CGRectGetHeight(rect));
  631. }
  632. //生成画布
  633. CGContextRef myPDFContext = NULL;
  634. CGRect mediaBox = CGRectMake(0, 0, maxWidth, maxHeight);
  635. NSString *newFieldName = [[[self.pdfDocument.documentURL.lastPathComponent stringByDeletingPathExtension] stringByAppendingString:@"_FormOnly"] stringByAppendingPathExtension:@"pdf"];
  636. NSString *newPDFPath = [[[NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSBundle mainBundle].bundleIdentifier] stringByAppendingPathComponent:newFieldName];
  637. CFStringRef ref = (__bridge CFStringRef)newPDFPath;
  638. myPDFContext = PDFContextCreate(&mediaBox, ref);
  639. for (NSInteger i = 0; i < pagesArray.count; i++) {
  640. PDFPage *page = [pagesArray objectAtIndex:i];
  641. mediaBox.size.width = [page boundsForBox:kPDFDisplayBoxMediaBox].size.width;
  642. mediaBox.size.height = [page boundsForBox:kPDFDisplayBoxMediaBox].size.height;
  643. CFStringRef myKeys[1];
  644. CFTypeRef myValues[1];
  645. myKeys[0] = kCGPDFContextMediaBox;
  646. myValues[0] = (CFTypeRef) CFDataCreate(NULL,(const UInt8 *)&mediaBox, sizeof (CGRect));
  647. CFDictionaryRef pageDictionary = CFDictionaryCreate(NULL, (const void **) myKeys,
  648. (const void **) myValues, 1,
  649. &kCFTypeDictionaryKeyCallBacks,
  650. & kCFTypeDictionaryValueCallBacks);
  651. CGPDFContextBeginPage(myPDFContext, pageDictionary);
  652. /*-------------绘制页开始---------------------**/
  653. NSMutableArray *array = [NSMutableArray array];
  654. for (NSInteger i = 0; i < page.annotations.count; i++) {
  655. PDFAnnotation *annotation = [page.annotations objectAtIndex:i];
  656. if ([annotation isKindOfClass:[PDFAnnotationButtonWidget class]] ||
  657. [annotation isKindOfClass:[PDFAnnotationTextWidget class]] ||
  658. [annotation isKindOfClass:[PDFAnnotationChoiceWidget class]]) {
  659. [array addObject:annotation];
  660. }
  661. }
  662. for (NSInteger i = 0; i < array.count; i++) {
  663. PDFAnnotation *annotation = [array objectAtIndex:i];
  664. CGRect newPosition = annotation.bounds;
  665. // if (page.rotation == 90) {
  666. // newPosition = CGRectMake(CGRectGetMinY(annotation.bounds), CGRectGetHeight(mediaBox) - CGRectGetMaxX(annotation.bounds), CGRectGetHeight(annotation.bounds), CGRectGetWidth(annotation.bounds));
  667. // } else if (page.rotation == 180) {
  668. // newPosition = CGRectMake(CGRectGetMaxX(mediaBox) - CGRectGetMaxX(annotation.bounds), CGRectGetMaxY(mediaBox) - CGRectGetMaxY(annotation.bounds), CGRectGetWidth(annotation.bounds), CGRectGetHeight(annotation.bounds));
  669. // } else if (page.rotation == 270) {
  670. // newPosition = CGRectMake(CGRectGetMaxX(mediaBox) - CGRectGetMaxY(annotation.bounds), CGRectGetMinX(annotation.bounds), CGRectGetHeight(annotation.bounds), CGRectGetWidth(annotation.bounds));
  671. // }
  672. if ([annotation isKindOfClass:[PDFAnnotationButtonWidget class]]) {
  673. PDFAnnotationButtonWidget *actulWidget = (PDFAnnotationButtonWidget *)annotation;
  674. if (actulWidget.controlType == kPDFWidgetCheckBoxControl) {
  675. CGContextSaveGState(myPDFContext);
  676. /* 如果没有签署,那么不画
  677. CGContextAddRect(myPDFContext, newPosition);
  678. CGContextStrokePath(myPDFContext);*/
  679. if (actulWidget.state) {
  680. CGFloat originalWidth = CGRectGetWidth(newPosition);
  681. CGFloat originalHeight = CGRectGetHeight(newPosition);
  682. CGFloat min = MIN(CGRectGetWidth(newPosition), CGRectGetHeight(newPosition));
  683. newPosition.size.width = min;
  684. newPosition.size.height = min;
  685. CGContextTranslateCTM(myPDFContext, newPosition.origin.x + (originalWidth - newPosition.size.width)/2.0, newPosition.origin.y + (originalHeight - newPosition.size.height /2.0));
  686. CGFloat x = newPosition.size.width/7;
  687. CGFloat y = newPosition.size.height/5;
  688. CGContextMoveToPoint(myPDFContext, x,newPosition.size.height/2.0);
  689. CGContextAddLineToPoint(myPDFContext,(newPosition.size.width-2*x)/3.0+x, y);
  690. CGContextAddLineToPoint(myPDFContext, newPosition.size.width-x, newPosition.size.height-y);
  691. CGContextStrokePath(myPDFContext);
  692. }
  693. CGContextRestoreGState(myPDFContext);
  694. } else if (actulWidget.controlType == kPDFWidgetRadioButtonControl) {
  695. CGContextSaveGState(myPDFContext);
  696. /*如果没有签署,那么不画
  697. CGContextStrokeEllipseInRect(myPDFContext, newPosition);*/
  698. if (actulWidget.state) {
  699. CGContextSetStrokeColorWithColor(myPDFContext, [NSColor blackColor].CGColor);
  700. CGContextSetFillColorWithColor(myPDFContext, [NSColor blackColor].CGColor);
  701. CGFloat x = newPosition.size.width/9;
  702. CGContextFillEllipseInRect(myPDFContext, CGRectInset(newPosition, x, x));
  703. }
  704. CGContextRestoreGState(myPDFContext);
  705. } else {
  706. CGContextSaveGState(myPDFContext);
  707. CGContextAddRect(myPDFContext, newPosition);
  708. CGContextSetFillColorWithColor(myPDFContext, [NSColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1.0].CGColor);
  709. CGContextFillPath(myPDFContext);
  710. CGContextRestoreGState(myPDFContext);
  711. if (actulWidget.caption.length > 0) {
  712. [NSGraphicsContext saveGraphicsState];
  713. NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:myPDFContext flipped:NO];
  714. [NSGraphicsContext setCurrentContext:context];
  715. NSDictionary *attributeDic = @{NSFontAttributeName:actulWidget.font,NSForegroundColorAttributeName:[(PDFAnnotationTextWidget *)actulWidget fontColor]};
  716. CGSize size = [actulWidget.caption sizeWithAttributes:attributeDic];
  717. CGRect drawRect = newPosition;
  718. if (CGRectGetWidth(drawRect) > size.width) {
  719. drawRect.origin.x += (CGRectGetWidth(drawRect) - size.width)/2.0;
  720. }
  721. if (CGRectGetHeight(drawRect) > size.height) {
  722. drawRect.origin.y += (CGRectGetHeight(drawRect) - size.height)/2.0;
  723. }
  724. drawRect.size.height = size.height;
  725. [actulWidget.caption drawInRect:drawRect withAttributes:@{NSFontAttributeName:actulWidget.font,NSForegroundColorAttributeName:[(PDFAnnotationTextWidget *)actulWidget fontColor]}];
  726. [NSGraphicsContext restoreGraphicsState];
  727. }
  728. }
  729. } else if ([annotation isKindOfClass:[PDFAnnotationTextWidget class]]) {
  730. PDFAnnotationTextWidget *actualWidget = (PDFAnnotationTextWidget *)annotation;
  731. if ([actualWidget stringValue] > 0) {
  732. [NSGraphicsContext saveGraphicsState];
  733. NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:myPDFContext flipped:NO];
  734. [NSGraphicsContext setCurrentContext:context];
  735. NSDictionary *attributeDic = @{NSFontAttributeName:actualWidget.font,NSForegroundColorAttributeName:[actualWidget fontColor]};
  736. if (actualWidget.isMultiline) {
  737. NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:actualWidget.stringValue];
  738. [attributeString setAlignment:actualWidget.alignment range:NSMakeRange(0, attributeString.length)];
  739. [attributeString addAttributes:attributeDic range:NSMakeRange(0, attributeString.length)];
  740. [attributeString drawInRect:newPosition];
  741. } else {
  742. CGSize size = [actualWidget.stringValue sizeWithAttributes:attributeDic];
  743. if (size.height < newPosition.size.height) {
  744. newPosition.origin.y = CGRectGetMaxY(newPosition) - size.height;
  745. newPosition.size.height = size.height;
  746. }
  747. NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:actualWidget.stringValue];
  748. [attributeString addAttributes:attributeDic range:NSMakeRange(0, attributeString.length)];
  749. [attributeString setAlignment:actualWidget.alignment range:NSMakeRange(0, attributeString.length)];
  750. [attributeString drawInRect:newPosition];
  751. }
  752. [NSGraphicsContext restoreGraphicsState];
  753. }
  754. } else if([annotation isKindOfClass:[PDFAnnotationChoiceWidget class]]){
  755. PDFAnnotationChoiceWidget *actualWidget = (PDFAnnotationChoiceWidget *)annotation;
  756. if (actualWidget.isListChoice) {
  757. NSDictionary *attributeDict = @{NSFontAttributeName:actualWidget.font,NSForegroundColorAttributeName:[actualWidget fontColor]};
  758. CGFloat fontHeight = [actualWidget.stringValue sizeWithAttributes:attributeDict].height;
  759. NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:myPDFContext flipped:NO];
  760. [NSGraphicsContext setCurrentContext:context];
  761. for (NSInteger i = 0; i < actualWidget.choices.count; i++) {
  762. CGRect drawRect = CGRectZero;
  763. CGFloat drawedHeight = i * fontHeight;
  764. CGFloat drawingHeight = fontHeight;
  765. drawRect.origin.y = MAX(CGRectGetMaxY(newPosition) - drawedHeight - drawingHeight,CGRectGetMinY(newPosition));
  766. drawRect.origin.x = newPosition.origin.x;
  767. drawRect.size.width = CGRectGetWidth(newPosition);
  768. drawRect.size.height = MIN(fontHeight, CGRectGetHeight(newPosition) - drawedHeight);
  769. NSString *drawString = [actualWidget.choices objectAtIndex:i];
  770. if ([drawString isEqualToString:actualWidget.stringValue]) {
  771. CGContextAddRect(myPDFContext, drawRect);
  772. CGContextSetFillColorWithColor(myPDFContext, [NSColor colorWithRed:155/255.0 green:155/255.0 blue:155/255.0 alpha:1.0].CGColor);
  773. CGContextFillPath(myPDFContext);
  774. }
  775. [drawString drawInRect:drawRect withAttributes:attributeDict];
  776. }
  777. [NSGraphicsContext restoreGraphicsState];
  778. } else {
  779. CGContextSaveGState(myPDFContext);
  780. [NSGraphicsContext saveGraphicsState];
  781. NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:myPDFContext flipped:NO];
  782. [NSGraphicsContext setCurrentContext:context];
  783. NSDictionary *attributeDic = @{NSFontAttributeName:actualWidget.font,NSForegroundColorAttributeName:[actualWidget fontColor]};
  784. CGSize size = [actualWidget.stringValue sizeWithAttributes:attributeDic];
  785. CGRect drawRect = newPosition;
  786. if (CGRectGetWidth(drawRect) > size.width) {
  787. drawRect.origin.x += (CGRectGetWidth(drawRect) - size.width)/2.0;
  788. }
  789. if (CGRectGetHeight(drawRect) > size.height) {
  790. drawRect.origin.y += (CGRectGetHeight(drawRect) - size.height)/2.0;
  791. }
  792. drawRect.size.height = size.height;
  793. [[actualWidget stringValue] drawInRect:drawRect withAttributes:attributeDic];
  794. [NSGraphicsContext restoreGraphicsState];
  795. CGContextRestoreGState(myPDFContext);
  796. }
  797. } else {
  798. CGContextSaveGState(myPDFContext);
  799. CGContextAddRect(myPDFContext, newPosition);
  800. CGContextSetFillColorWithColor(myPDFContext, [NSColor yellowColor].CGColor);
  801. CGContextFillPath(myPDFContext);
  802. CGContextRestoreGState(myPDFContext);
  803. }
  804. }
  805. /*-------------绘制页结束---------------------**/
  806. CGPDFContextEndPage(myPDFContext);
  807. CFRelease(pageDictionary);
  808. CFRelease(myValues[0]);
  809. }
  810. CGPDFContextClose(myPDFContext);
  811. CGContextRelease(myPDFContext);
  812. self.preview.document = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:newPDFPath]];
  813. [self.preview goToFirstPage:nil];
  814. [self adjustPreviewSizeWithPage:[self.preview.document pageAtIndex:0]];
  815. self.currentPageNumberTextField.stringValue = @"1";
  816. self.totalPageNumberLabel.stringValue = [NSString stringWithFormat:@" / %ld",pagesArray.count];
  817. }
  818. //创建一个图形上下文对象
  819. CGContextRef PDFContextCreate (const CGRect *inMediaBox,
  820. CFStringRef path)
  821. {
  822. CGContextRef myOutContext = NULL;
  823. CFURLRef url;
  824. url = CFURLCreateWithFileSystemPath (NULL, // 1
  825. path,
  826. kCFURLPOSIXPathStyle,
  827. false);
  828. if (url != NULL) {
  829. myOutContext = CGPDFContextCreateWithURL (url,// 2
  830. inMediaBox,
  831. NULL);
  832. CFRelease(url);// 3
  833. }
  834. return myOutContext;// 4
  835. }
  836. @end