KMPDFPrintManageWindowController.m 40 KB

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