KMPDFPrintManageWindowController.m 39 KB

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