KMPDFPrintManageWindowController.m 40 KB

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