KMPDFPrintManageWindowController.m 39 KB

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