KMPDFPrintManageWindowController.m 39 KB

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