KMPDFPrintManageWindowController.m 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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 (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  491. // [self close];
  492. // [[KMProductCompareWC shared] setOrientation:NO];
  493. // NSWindowController *winC = [KMProductCompareWC shared];
  494. // winC.kEventName = @"MenuBar_PrintPoster_BuyNow";
  495. // [winC showWindow:nil];
  496. // return;
  497. // }
  498. if (![KMMemberInfo shared].isMemberAllFunction) {
  499. [self close];
  500. NSWindowController *winC = [KMProductCompareWC shared];
  501. winC.kEventName = @"MenuBar_PrintPoster_BuyNow";
  502. [[KMMemberInfo shared] advancedFunctionUsage];
  503. return;
  504. }
  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. // [[KMProductCompareWC shared] setOrientation:NO];
  517. // NSWindowController *winC = [KMProductCompareWC shared];
  518. // winC.kEventName = @"MenuBar_PrintMultiple_BuyNow";
  519. // [winC showWindow:nil];
  520. // return;
  521. // }
  522. if (![KMMemberInfo shared].isMemberAllFunction) {
  523. [self close];
  524. NSWindowController *winC = [KMProductCompareWC shared];
  525. winC.kEventName = @"MenuBar_PrintMultiple_BuyNow";
  526. [[KMMemberInfo shared] advancedFunctionUsage];
  527. return;
  528. }
  529. [self close];
  530. _multipleVC = [[KMPDFMultiplePrintWindowController alloc] initWithPDFDocument:self.pdfDocument];
  531. // [multipleVC beginSheetModalForWindow:[NSApp mainWindow] completionHandler:nil];
  532. [[NSApp mainWindow] beginSheet:_multipleVC.window completionHandler:^(NSModalResponse returnCode) {
  533. }];
  534. }
  535. //Booklet
  536. - (IBAction)buttonItemClicked_Booklet:(NSButton *)sender
  537. {
  538. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  539. // [self close];
  540. // [[KMProductCompareWC shared] setOrientation:NO];
  541. // NSWindowController *winC = [KMProductCompareWC shared];
  542. // winC.kEventName = @"MenuBar_PrintBooklet_BuyNow";
  543. // [winC showWindow:nil];
  544. // return;
  545. // }
  546. if (![KMMemberInfo shared].isMemberAllFunction) {
  547. [self close];
  548. NSWindowController *winC = [KMProductCompareWC shared];
  549. winC.kEventName = @"MenuBar_PrintBooklet_BuyNow";
  550. [[KMMemberInfo shared] advancedFunctionUsage];
  551. return;
  552. }
  553. [self close];
  554. _bookletVC = [[KMPDFBookletWindowController alloc] initWithDocument:self.pdfDocument];
  555. // [bookletVC beginSheetModalForWindow:[NSApp mainWindow] completionHandler:nil];
  556. [[NSApp mainWindow] beginSheet:_bookletVC.window completionHandler:^(NSModalResponse returnCode) {
  557. }];
  558. }
  559. //取消
  560. - (IBAction)buttonItemClicked_Cancel:(NSButton *)sender
  561. {
  562. [self close];
  563. }
  564. - (void)close{
  565. if (self.window.isSheet) {
  566. [self.window.sheetParent endSheet:self.window];
  567. // [self dismissSheet:nil];
  568. } else {
  569. [super close];
  570. }
  571. }
  572. //打印
  573. - (IBAction)buttonItemClicked_Print:(NSButton *)sender
  574. {
  575. [self.window makeFirstResponder:self.preview];
  576. if (self.callBack) {
  577. [self close];
  578. self.callBack(self.preview.document);
  579. }
  580. }
  581. #pragma mark - NSTextField Delegate
  582. - (void)controlTextDidEndEditing:(NSNotification *)notification
  583. {
  584. NSTextField *textField = notification.object;
  585. if ([textField isEqual:self.intputPageRangeTextField]) {
  586. if (!self.selectPagesIndexArray) {
  587. self.selectPagesIndexArray = [NSMutableArray array];
  588. }else{
  589. [self.selectPagesIndexArray removeAllObjects];
  590. }
  591. KMFileAttribute *fileAttribute = [[KMFileAttribute alloc] init];
  592. fileAttribute.filePath = [self.pdfDocument.documentURL path];
  593. fileAttribute.bAllPage = NO;
  594. fileAttribute.pagesString = self.intputPageRangeTextField.stringValue;
  595. if ([fileAttribute fetchSelectPages]) {
  596. [self.selectPagesIndexArray addObjectsFromArray: [fileAttribute fetchSelectPages]];
  597. if (self.printParameter.printStyle == kPrintStyle_FormsOnly) {
  598. [self createOnlyFormDocument];
  599. } else {
  600. [self produceNewPDFForPreview];
  601. }
  602. }else{
  603. [self showCriticalAlert:nil];
  604. }
  605. }else if ([textField isEqual:self.currentPageNumberTextField]){
  606. PDFPage *targetPage = [self.preview.document pageAtIndex:[self.currentPageNumberTextField.stringValue integerValue] - 1];
  607. if (targetPage) {
  608. [self.preview goToPage:targetPage];
  609. }
  610. }
  611. }
  612. - (void)controlTextDidChange:(NSNotification *)notification
  613. {
  614. NSTextField *textField = notification.object;
  615. if ([textField isEqual:self.currentPageNumberTextField]) {
  616. NSString *string = [self.currentPageNumberTextField.formatter stringFromNumber:[NSNumber numberWithFloat:[self.currentPageNumberTextField.stringValue integerValue]]];
  617. if ([string integerValue] > self.preview.document.pageCount) {
  618. string = [NSString stringWithFormat:@"%ld",self.preview.document.pageCount];
  619. }else if ([string integerValue] <= 0){
  620. string = @"1";
  621. }
  622. self.currentPageNumberTextField.stringValue = string;
  623. }
  624. }
  625. #pragma mark - 开始转圈,隐藏转圈提示
  626. - (void)showWaitting
  627. {
  628. if (!_maskView) {
  629. _maskView = [[KMBookletMaskView alloc] initWithFrame:NSMakeRect(0, 0, self.window.frame.size.width, self.window.frame.size.height)];
  630. }
  631. [self.window.contentView addSubview:_maskView];
  632. }
  633. - (void)hideWaitting
  634. {
  635. [_maskView removeFromSuperview];
  636. }
  637. //创建一个新的空白只打印formPDF
  638. - (void)createOnlyFormDocument {
  639. NSMutableArray *pagesArray = [self fetchPagesArrayWithParameter:self.printParameter.pageSelectStyle];
  640. if (pagesArray.count < 1) {
  641. NSBeep();
  642. return;
  643. }
  644. if (self.printParameter.reversePages) {
  645. pagesArray = [NSMutableArray arrayWithArray:[[pagesArray reverseObjectEnumerator] allObjects]];
  646. }
  647. //取最大宽高作为画布大小
  648. CGFloat maxWidth = 0;
  649. CGFloat maxHeight = 0;
  650. for (NSInteger i = 0; i < pagesArray.count; i++) {
  651. PDFPage *page = [pagesArray objectAtIndex:i];
  652. CGRect rect = [page boundsForBox:kPDFDisplayBoxMediaBox];
  653. maxWidth = MAX(maxWidth, CGRectGetWidth(rect));
  654. maxHeight = MAX(maxHeight, CGRectGetHeight(rect));
  655. }
  656. //生成画布
  657. CGContextRef myPDFContext = NULL;
  658. CGRect mediaBox = CGRectMake(0, 0, maxWidth, maxHeight);
  659. NSString *newFieldName = [[[self.pdfDocument.documentURL.lastPathComponent stringByDeletingPathExtension] stringByAppendingString:@"_FormOnly"] stringByAppendingPathExtension:@"pdf"];
  660. NSString *newPDFPath = [[[NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSBundle mainBundle].bundleIdentifier] stringByAppendingPathComponent:newFieldName];
  661. CFStringRef ref = (__bridge CFStringRef)newPDFPath;
  662. myPDFContext = PDFContextCreate(&mediaBox, ref);
  663. for (NSInteger i = 0; i < pagesArray.count; i++) {
  664. PDFPage *page = [pagesArray objectAtIndex:i];
  665. mediaBox.size.width = [page boundsForBox:kPDFDisplayBoxMediaBox].size.width;
  666. mediaBox.size.height = [page boundsForBox:kPDFDisplayBoxMediaBox].size.height;
  667. CFStringRef myKeys[1];
  668. CFTypeRef myValues[1];
  669. myKeys[0] = kCGPDFContextMediaBox;
  670. myValues[0] = (CFTypeRef) CFDataCreate(NULL,(const UInt8 *)&mediaBox, sizeof (CGRect));
  671. CFDictionaryRef pageDictionary = CFDictionaryCreate(NULL, (const void **) myKeys,
  672. (const void **) myValues, 1,
  673. &kCFTypeDictionaryKeyCallBacks,
  674. & kCFTypeDictionaryValueCallBacks);
  675. CGPDFContextBeginPage(myPDFContext, pageDictionary);
  676. /*-------------绘制页开始---------------------**/
  677. NSMutableArray *array = [NSMutableArray array];
  678. for (NSInteger i = 0; i < page.annotations.count; i++) {
  679. PDFAnnotation *annotation = [page.annotations objectAtIndex:i];
  680. if ([annotation isKindOfClass:[PDFAnnotationButtonWidget class]] ||
  681. [annotation isKindOfClass:[PDFAnnotationTextWidget class]] ||
  682. [annotation isKindOfClass:[PDFAnnotationChoiceWidget class]]) {
  683. [array addObject:annotation];
  684. }
  685. }
  686. for (NSInteger i = 0; i < array.count; i++) {
  687. PDFAnnotation *annotation = [array objectAtIndex:i];
  688. CGRect newPosition = annotation.bounds;
  689. // if (page.rotation == 90) {
  690. // newPosition = CGRectMake(CGRectGetMinY(annotation.bounds), CGRectGetHeight(mediaBox) - CGRectGetMaxX(annotation.bounds), CGRectGetHeight(annotation.bounds), CGRectGetWidth(annotation.bounds));
  691. // } else if (page.rotation == 180) {
  692. // newPosition = CGRectMake(CGRectGetMaxX(mediaBox) - CGRectGetMaxX(annotation.bounds), CGRectGetMaxY(mediaBox) - CGRectGetMaxY(annotation.bounds), CGRectGetWidth(annotation.bounds), CGRectGetHeight(annotation.bounds));
  693. // } else if (page.rotation == 270) {
  694. // newPosition = CGRectMake(CGRectGetMaxX(mediaBox) - CGRectGetMaxY(annotation.bounds), CGRectGetMinX(annotation.bounds), CGRectGetHeight(annotation.bounds), CGRectGetWidth(annotation.bounds));
  695. // }
  696. if ([annotation isKindOfClass:[PDFAnnotationButtonWidget class]]) {
  697. PDFAnnotationButtonWidget *actulWidget = (PDFAnnotationButtonWidget *)annotation;
  698. if (actulWidget.controlType == kPDFWidgetCheckBoxControl) {
  699. CGContextSaveGState(myPDFContext);
  700. /* 如果没有签署,那么不画
  701. CGContextAddRect(myPDFContext, newPosition);
  702. CGContextStrokePath(myPDFContext);*/
  703. if (actulWidget.state) {
  704. CGFloat originalWidth = CGRectGetWidth(newPosition);
  705. CGFloat originalHeight = CGRectGetHeight(newPosition);
  706. CGFloat min = MIN(CGRectGetWidth(newPosition), CGRectGetHeight(newPosition));
  707. newPosition.size.width = min;
  708. newPosition.size.height = min;
  709. CGContextTranslateCTM(myPDFContext, newPosition.origin.x + (originalWidth - newPosition.size.width)/2.0, newPosition.origin.y + (originalHeight - newPosition.size.height /2.0));
  710. CGFloat x = newPosition.size.width/7;
  711. CGFloat y = newPosition.size.height/5;
  712. CGContextMoveToPoint(myPDFContext, x,newPosition.size.height/2.0);
  713. CGContextAddLineToPoint(myPDFContext,(newPosition.size.width-2*x)/3.0+x, y);
  714. CGContextAddLineToPoint(myPDFContext, newPosition.size.width-x, newPosition.size.height-y);
  715. CGContextStrokePath(myPDFContext);
  716. }
  717. CGContextRestoreGState(myPDFContext);
  718. } else if (actulWidget.controlType == kPDFWidgetRadioButtonControl) {
  719. CGContextSaveGState(myPDFContext);
  720. /*如果没有签署,那么不画
  721. CGContextStrokeEllipseInRect(myPDFContext, newPosition);*/
  722. if (actulWidget.state) {
  723. CGContextSetStrokeColorWithColor(myPDFContext, [NSColor blackColor].CGColor);
  724. CGContextSetFillColorWithColor(myPDFContext, [NSColor blackColor].CGColor);
  725. CGFloat x = newPosition.size.width/9;
  726. CGContextFillEllipseInRect(myPDFContext, CGRectInset(newPosition, x, x));
  727. }
  728. CGContextRestoreGState(myPDFContext);
  729. } else {
  730. CGContextSaveGState(myPDFContext);
  731. CGContextAddRect(myPDFContext, newPosition);
  732. CGContextSetFillColorWithColor(myPDFContext, [NSColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1.0].CGColor);
  733. CGContextFillPath(myPDFContext);
  734. CGContextRestoreGState(myPDFContext);
  735. if (actulWidget.caption.length > 0) {
  736. [NSGraphicsContext saveGraphicsState];
  737. NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:myPDFContext flipped:NO];
  738. [NSGraphicsContext setCurrentContext:context];
  739. NSDictionary *attributeDic = @{NSFontAttributeName:actulWidget.font,NSForegroundColorAttributeName:[(PDFAnnotationTextWidget *)actulWidget fontColor]};
  740. CGSize size = [actulWidget.caption sizeWithAttributes:attributeDic];
  741. CGRect drawRect = newPosition;
  742. if (CGRectGetWidth(drawRect) > size.width) {
  743. drawRect.origin.x += (CGRectGetWidth(drawRect) - size.width)/2.0;
  744. }
  745. if (CGRectGetHeight(drawRect) > size.height) {
  746. drawRect.origin.y += (CGRectGetHeight(drawRect) - size.height)/2.0;
  747. }
  748. drawRect.size.height = size.height;
  749. [actulWidget.caption drawInRect:drawRect withAttributes:@{NSFontAttributeName:actulWidget.font,NSForegroundColorAttributeName:[(PDFAnnotationTextWidget *)actulWidget fontColor]}];
  750. [NSGraphicsContext restoreGraphicsState];
  751. }
  752. }
  753. } else if ([annotation isKindOfClass:[PDFAnnotationTextWidget class]]) {
  754. PDFAnnotationTextWidget *actualWidget = (PDFAnnotationTextWidget *)annotation;
  755. if ([actualWidget stringValue] > 0) {
  756. [NSGraphicsContext saveGraphicsState];
  757. NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:myPDFContext flipped:NO];
  758. [NSGraphicsContext setCurrentContext:context];
  759. NSDictionary *attributeDic = @{NSFontAttributeName:actualWidget.font,NSForegroundColorAttributeName:[actualWidget fontColor]};
  760. if (actualWidget.isMultiline) {
  761. NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:actualWidget.stringValue];
  762. [attributeString setAlignment:actualWidget.alignment range:NSMakeRange(0, attributeString.length)];
  763. [attributeString addAttributes:attributeDic range:NSMakeRange(0, attributeString.length)];
  764. [attributeString drawInRect:newPosition];
  765. } else {
  766. CGSize size = [actualWidget.stringValue sizeWithAttributes:attributeDic];
  767. if (size.height < newPosition.size.height) {
  768. newPosition.origin.y = CGRectGetMaxY(newPosition) - size.height;
  769. newPosition.size.height = size.height;
  770. }
  771. NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:actualWidget.stringValue];
  772. [attributeString addAttributes:attributeDic range:NSMakeRange(0, attributeString.length)];
  773. [attributeString setAlignment:actualWidget.alignment range:NSMakeRange(0, attributeString.length)];
  774. [attributeString drawInRect:newPosition];
  775. }
  776. [NSGraphicsContext restoreGraphicsState];
  777. }
  778. } else if([annotation isKindOfClass:[PDFAnnotationChoiceWidget class]]){
  779. PDFAnnotationChoiceWidget *actualWidget = (PDFAnnotationChoiceWidget *)annotation;
  780. if (actualWidget.isListChoice) {
  781. NSDictionary *attributeDict = @{NSFontAttributeName:actualWidget.font,NSForegroundColorAttributeName:[actualWidget fontColor]};
  782. CGFloat fontHeight = [actualWidget.stringValue sizeWithAttributes:attributeDict].height;
  783. NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:myPDFContext flipped:NO];
  784. [NSGraphicsContext setCurrentContext:context];
  785. for (NSInteger i = 0; i < actualWidget.choices.count; i++) {
  786. CGRect drawRect = CGRectZero;
  787. CGFloat drawedHeight = i * fontHeight;
  788. CGFloat drawingHeight = fontHeight;
  789. drawRect.origin.y = MAX(CGRectGetMaxY(newPosition) - drawedHeight - drawingHeight,CGRectGetMinY(newPosition));
  790. drawRect.origin.x = newPosition.origin.x;
  791. drawRect.size.width = CGRectGetWidth(newPosition);
  792. drawRect.size.height = MIN(fontHeight, CGRectGetHeight(newPosition) - drawedHeight);
  793. NSString *drawString = [actualWidget.choices objectAtIndex:i];
  794. if ([drawString isEqualToString:actualWidget.stringValue]) {
  795. CGContextAddRect(myPDFContext, drawRect);
  796. CGContextSetFillColorWithColor(myPDFContext, [NSColor colorWithRed:155/255.0 green:155/255.0 blue:155/255.0 alpha:1.0].CGColor);
  797. CGContextFillPath(myPDFContext);
  798. }
  799. [drawString drawInRect:drawRect withAttributes:attributeDict];
  800. }
  801. [NSGraphicsContext restoreGraphicsState];
  802. } else {
  803. CGContextSaveGState(myPDFContext);
  804. [NSGraphicsContext saveGraphicsState];
  805. NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithGraphicsPort:myPDFContext flipped:NO];
  806. [NSGraphicsContext setCurrentContext:context];
  807. NSDictionary *attributeDic = @{NSFontAttributeName:actualWidget.font,NSForegroundColorAttributeName:[actualWidget fontColor]};
  808. CGSize size = [actualWidget.stringValue sizeWithAttributes:attributeDic];
  809. CGRect drawRect = newPosition;
  810. if (CGRectGetWidth(drawRect) > size.width) {
  811. drawRect.origin.x += (CGRectGetWidth(drawRect) - size.width)/2.0;
  812. }
  813. if (CGRectGetHeight(drawRect) > size.height) {
  814. drawRect.origin.y += (CGRectGetHeight(drawRect) - size.height)/2.0;
  815. }
  816. drawRect.size.height = size.height;
  817. [[actualWidget stringValue] drawInRect:drawRect withAttributes:attributeDic];
  818. [NSGraphicsContext restoreGraphicsState];
  819. CGContextRestoreGState(myPDFContext);
  820. }
  821. } else {
  822. CGContextSaveGState(myPDFContext);
  823. CGContextAddRect(myPDFContext, newPosition);
  824. CGContextSetFillColorWithColor(myPDFContext, [NSColor yellowColor].CGColor);
  825. CGContextFillPath(myPDFContext);
  826. CGContextRestoreGState(myPDFContext);
  827. }
  828. }
  829. /*-------------绘制页结束---------------------**/
  830. CGPDFContextEndPage(myPDFContext);
  831. CFRelease(pageDictionary);
  832. CFRelease(myValues[0]);
  833. }
  834. CGPDFContextClose(myPDFContext);
  835. CGContextRelease(myPDFContext);
  836. self.preview.document = [[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath:newPDFPath]];
  837. [self.preview goToFirstPage:nil];
  838. [self adjustPreviewSizeWithPage:[self.preview.document pageAtIndex:0]];
  839. self.currentPageNumberTextField.stringValue = @"1";
  840. self.totalPageNumberLabel.stringValue = [NSString stringWithFormat:@" / %ld",pagesArray.count];
  841. }
  842. //创建一个图形上下文对象
  843. CGContextRef PDFContextCreate (const CGRect *inMediaBox,
  844. CFStringRef path)
  845. {
  846. CGContextRef myOutContext = NULL;
  847. CFURLRef url;
  848. url = CFURLCreateWithFileSystemPath (NULL, // 1
  849. path,
  850. kCFURLPOSIXPathStyle,
  851. false);
  852. if (url != NULL) {
  853. myOutContext = CGPDFContextCreateWithURL (url,// 2
  854. inMediaBox,
  855. NULL);
  856. CFRelease(url);// 3
  857. }
  858. return myOutContext;// 4
  859. }
  860. @end