KMBatchSettingView.swift 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. //
  2. // KMBatchSettingView.swift
  3. // PDF Master
  4. //
  5. // Created by lizhe on 2023/1/16.
  6. //
  7. import Cocoa
  8. class KMBatchSettingView: KMBaseXibView {
  9. var currentView: KMBatchSettingItemView = KMBatchSettingItemView()
  10. lazy var itemViewArray: [KMBatchSettingItemView] = []
  11. var filesData: [KMBatchProcessingTableViewModel]? {
  12. didSet {
  13. currentView.filesData = filesData!
  14. }
  15. }
  16. var type: KMBatchCollectionViewType = .convertPDF {
  17. didSet {
  18. self.reloadData()
  19. }
  20. }
  21. var subType: Any? {
  22. didSet {
  23. self.reloadData()
  24. }
  25. }
  26. override func draw(_ dirtyRect: NSRect) {
  27. super.draw(dirtyRect)
  28. // Drawing code here.
  29. }
  30. override func setup() {
  31. super.setup()
  32. self.contentView.wantsLayer = true
  33. self.contentView.layer?.backgroundColor = NSColor.km_init(hex: "#F7F8FA").cgColor
  34. self.type = .convertPDF
  35. }
  36. override func reloadData() {
  37. super.reloadData()
  38. if (self.type != self.currentView.type) {
  39. let view: KMBatchSettingItemView = self.fetchCurrentView(type: self.type, subType: self.subType as Any)
  40. self.currentView.removeFromSuperview()
  41. self.addSubview(view)
  42. view.translatesAutoresizingMaskIntoConstraints = false
  43. NSLayoutConstraint.activate([
  44. view.topAnchor.constraint(equalTo: topAnchor),
  45. view.leftAnchor.constraint(equalTo: leftAnchor),
  46. view.rightAnchor.constraint(equalTo: rightAnchor),
  47. view.bottomAnchor.constraint(equalTo: bottomAnchor)])
  48. view.updateConstraintsForSubtreeIfNeeded()
  49. self.currentView = view
  50. } else if (self.subType.debugDescription != self.currentView.subType.debugDescription) {
  51. self.currentView.subType = self.subType
  52. }
  53. }
  54. func fetchCurrentView(type: KMBatchCollectionViewType, subType: Any) -> KMBatchSettingItemView {
  55. var resultView: KMBatchSettingItemView = KMBatchSecurityView.init()
  56. var isExist = false
  57. for item in self.itemViewArray {
  58. if item.type == type {
  59. isExist = true
  60. resultView = item
  61. }
  62. }
  63. if !isExist {
  64. switch type {
  65. case .convertPDF:
  66. resultView = KMBatchConvertPDFView.init()
  67. resultView.export = { [unowned self] (view, data) in
  68. self.convertPDFExport(data: data)
  69. }
  70. break
  71. case .compress:
  72. resultView = KMBatchCompressView.init()
  73. resultView.export = { [unowned self] (view, data) in
  74. self.compressExport(data: data)
  75. }
  76. break
  77. case .security:
  78. resultView = KMBatchSecurityView.init()
  79. resultView.export = { [unowned self] (view, data) in
  80. self.securityExport(data: data)
  81. }
  82. break
  83. case .watermark:
  84. resultView = KMBatchWatermarkView.init()
  85. resultView.export = { [unowned self] (view, data) in
  86. self.waterMarkApplay(data: data)
  87. }
  88. break
  89. case .background:
  90. resultView = KMBatchBackgroundView.init()
  91. resultView.export = { [unowned self] (view, data) in
  92. self.backgroundApplay(data: data)
  93. }
  94. break
  95. case .headerAndFooter:
  96. resultView = KMBatchHeaderAndFooterView.init()
  97. resultView.export = { [unowned self] (view, data) in
  98. self.headAndFooterApplay(data: data)
  99. }
  100. break
  101. case .batesNumber:
  102. resultView = KMBatchBatesNumberView.init()
  103. resultView.export = { [unowned self] (view, data) in
  104. self.batesApplay(data: data)
  105. }
  106. break
  107. case .batchRemove:
  108. resultView = KMBatchRemoveView.init()
  109. resultView.export = { [unowned self] (view, data) in
  110. self.removeApplay(data: data)
  111. }
  112. break
  113. default:
  114. KMPrint("找不到")
  115. break
  116. }
  117. resultView.type = type
  118. resultView.subType = subType
  119. resultView.filesData = self.filesData ?? []
  120. self.itemViewArray.append(resultView)
  121. } else {
  122. if resultView.filesData.count == 0 && self.filesData?.count != 0{
  123. resultView.filesData = self.filesData ?? []
  124. }
  125. }
  126. return resultView
  127. }
  128. }
  129. protocol KMBatchSettingViewExport {}
  130. extension KMBatchSettingView: KMBatchSettingViewExport {
  131. //MARK: 转档
  132. func convertPDFExport(data: KMBatchSettingItemViewModel) {
  133. let panel = NSOpenPanel()
  134. panel.canChooseFiles = false
  135. panel.canChooseDirectories = true
  136. panel.canCreateDirectories = true
  137. panel.beginSheetModal(for: self.window!) { response in
  138. if response == .cancel {
  139. return
  140. }
  141. let outputFolderPath = panel.url?.path
  142. self.convertFile(outputFolderPath: outputFolderPath!, data: data, filesData: self.filesData)
  143. }
  144. }
  145. func convertFile(outputFolderPath: String, data: KMBatchSettingItemViewModel, filesData: [KMBatchProcessingTableViewModel]?) {
  146. if filesData?.count != 0 {
  147. DispatchQueue.global().async {
  148. for item in filesData! {
  149. //创建Document
  150. let filePath = item.filePath
  151. let document = PDFDocument(url: URL(fileURLWithPath: filePath))
  152. let convert = KMPDFConvert()
  153. let settingData = data as? KMBatchConvertPDFViewModel ?? KMBatchConvertPDFViewModel()
  154. var convertType: KMPDFConvertType = .word
  155. var fileName = filePath.deletingPathExtension.lastPathComponent
  156. if ((fileName.isEmpty)) {
  157. fileName = NSLocalizedString("Untitled", comment: "")
  158. }
  159. //获取page
  160. var pages:[Int] = []
  161. for i in 0 ... document!.pageCount - 1 {
  162. pages.append(i+1)
  163. }
  164. convert.outputFolderPath = outputFolderPath
  165. convert.filePath = filePath
  166. convert.outputFileName = fileName
  167. convert.pages = pages
  168. switch settingData.convertPDFType {
  169. case .word:
  170. convertType = .word
  171. if settingData.layoutSettingType == .flowingText {
  172. convert.isAllInOneSheet = false
  173. } else {
  174. convert.isAllInOneSheet = true
  175. }
  176. case .excel:
  177. convertType = .excel
  178. if settingData.excelSetting == .separate {
  179. convert.isAllInOneSheet = false
  180. convert.isExtractTable = false
  181. } else if settingData.excelSetting == .format {
  182. convert.isAllInOneSheet = true
  183. convert.isExtractTable = false
  184. } else if settingData.excelSetting == .tables {
  185. convert.isAllInOneSheet = false
  186. convert.isExtractTable = true
  187. switch settingData.excelTablesType {
  188. case .oneTable:
  189. convert.extractTableIndex = 0
  190. case .pageTable:
  191. convert.extractTableIndex = 1
  192. case .allTable:
  193. convert.extractTableIndex = 2
  194. default:
  195. KMPrint("未找到")
  196. }
  197. }
  198. case .ppt:
  199. convertType = .ppt
  200. case .csv:
  201. convertType = .csv
  202. if settingData.csvOnlyTables {
  203. convert.isExtractTable = true
  204. switch settingData.excelTablesType {
  205. case .oneTable:
  206. convert.extractTableIndex = 0
  207. case .pageTable:
  208. convert.extractTableIndex = 1
  209. case .allTable:
  210. convert.extractTableIndex = 2
  211. default:
  212. KMPrint("未找到")
  213. }
  214. } else {
  215. convert.isExtractTable = false
  216. }
  217. case .image:
  218. convertType = .png
  219. case .html:
  220. convertType = .html
  221. case .rtf:
  222. convertType = .rtf
  223. default:
  224. KMPrint("不清楚")
  225. }
  226. convert.convertType = convertType
  227. KMPDFConvertManager.defaultManager.convert(convert: convert) { [unowned self] finished, error in
  228. if finished {
  229. // cancelButtonAction()
  230. } else {
  231. var errorString = ""
  232. let myError: NSError = error! as NSError
  233. if myError.code == 1 {
  234. errorString = NSLocalizedString("Password required or incorrect password. Please re-enter your password and try again", comment: "")
  235. } else if myError.code == 2 {
  236. errorString = NSLocalizedString("The license doesn't allow the permission", comment: "")
  237. } else if myError.code == 3 {
  238. errorString = NSLocalizedString("Malloc failure", comment: "")
  239. } else if myError.code == 4 {
  240. errorString = NSLocalizedString("Unknown error in processing conversion. Please try again later", comment: "")
  241. } else if myError.code == 5 {
  242. errorString = NSLocalizedString("Unknown error in processing PDF. Please try again later", comment: "")
  243. } else if myError.code == 6 {
  244. errorString = NSLocalizedString("File not found or could not be opened. Check if your file exists or choose another file to convert", comment: "")
  245. } else if myError.code == 7 {
  246. errorString = NSLocalizedString("File not in PDF format or corruptead. Change a PDF file and try again", comment: "")
  247. } else if myError.code == 8 {
  248. errorString = NSLocalizedString("Unsupported security scheme", comment: "")
  249. } else if myError.code == 9 {
  250. errorString = NSLocalizedString("Page not found or content error", comment: "")
  251. } else {
  252. errorString = NSLocalizedString("Table not found", comment: "")
  253. }
  254. let alert = NSAlert()
  255. alert.alertStyle = .critical
  256. alert.messageText = NSLocalizedString("Conversion Failed", comment: "")
  257. alert.informativeText = errorString
  258. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  259. alert.runModal()
  260. }
  261. }
  262. }
  263. if FileManager.default.fileExists(atPath: outputFolderPath) {
  264. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  265. }
  266. }
  267. }
  268. }
  269. //MARK: 压缩
  270. func compressExport(data: KMBatchSettingItemViewModel) {
  271. let panel = NSOpenPanel()
  272. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  273. button.state = .on
  274. panel.accessoryView = button
  275. panel.canChooseFiles = false
  276. panel.canChooseDirectories = true
  277. panel.canCreateDirectories = true
  278. panel.beginSheetModal(for: self.window!) { [self] response in
  279. if response == .cancel {
  280. return
  281. }
  282. let outputFolderPath = panel.url?.path
  283. self.compressFile(outputFolderPath: outputFolderPath!, data: (data as? KMBatchCompressViewModel)!, filesData: self.filesData!)
  284. }
  285. }
  286. func compressFile(outputFolderPath: String, data: KMBatchCompressViewModel, filesData: [KMBatchProcessingTableViewModel]?) {
  287. if filesData?.count != 0 {
  288. for item in filesData! {
  289. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  290. if ((fileName.isEmpty)) {
  291. fileName = NSLocalizedString("Untitled", comment: "")
  292. }
  293. let path = outputFolderPath + "/" + fileName + ".pdf"
  294. let docuemt = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  295. // if (docuemt?.isLocked)! && password != nil {
  296. // docuemt?.unlock(withPassword: password)
  297. // }
  298. var option = 120
  299. switch data.type {
  300. case .large:
  301. option = 120
  302. case .standard:
  303. option = 90
  304. case .small:
  305. option = 60
  306. case .minimum:
  307. option = 30
  308. }
  309. docuemt?.writeOptimize(to: URL(fileURLWithPath: path), withOptions: [.imageQualityOption : option])
  310. }
  311. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  312. }
  313. }
  314. //MARK: 安全
  315. func securityExport(data: KMBatchSettingItemViewModel) {
  316. let panel = NSOpenPanel()
  317. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  318. button.state = .on
  319. panel.accessoryView = button
  320. panel.canChooseFiles = false
  321. panel.canChooseDirectories = true
  322. panel.canCreateDirectories = true
  323. panel.beginSheetModal(for: self.window!) { [self] response in
  324. if response == .cancel {
  325. return
  326. }
  327. let outputFolderPath = panel.url?.path
  328. self.securityFile(outputFolderPath: outputFolderPath!, data: data as! KMBatchSecurityViewModel, filesData: self.filesData!)
  329. }
  330. }
  331. func securityFile(outputFolderPath: String, data: KMBatchSecurityViewModel, filesData: [KMBatchProcessingTableViewModel]?) {
  332. if filesData?.count != 0 {
  333. for item in filesData! {
  334. let docuemt = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  335. if (docuemt != nil) {
  336. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  337. if ((fileName.isEmpty)) {
  338. fileName = NSLocalizedString("Untitled", comment: "")
  339. }
  340. let path = outputFolderPath + "/" + fileName + ".pdf"
  341. var options: [CPDFDocumentWriteOption : Any] = [:]
  342. //开启密码
  343. if data.isOpenPassword &&
  344. !data.openPasswordString.isEmpty {
  345. options.updateValue(data.openPasswordString, forKey: .userPasswordOption)
  346. }
  347. //
  348. //权限密码
  349. if data.isPermission &&
  350. !data.permissionString.isEmpty {
  351. options.updateValue(data.permissionString, forKey: .userPasswordOption)
  352. }
  353. // 限制打印
  354. if data.restrictOptions.contains(.print) {
  355. options.updateValue(false, forKey: .allowsPrintingOption)
  356. } else {
  357. options.updateValue(true, forKey: .allowsPrintingOption)
  358. }
  359. //限制复制
  360. if data.restrictOptions.contains(.copy) {
  361. options.updateValue(false, forKey: .allowsCopyingOption)
  362. } else {
  363. options.updateValue(true, forKey: .allowsCopyingOption)
  364. }
  365. let result = docuemt!.write(to: URL(fileURLWithPath: path), withOptions: options)
  366. if result {
  367. KMPrint("成功")
  368. } else {
  369. KMPrint("失败")
  370. }
  371. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  372. }
  373. }
  374. }
  375. }
  376. func waterMarkApplay(data: KMBatchSettingItemViewModel) {
  377. self.waterMarkFile(data: data as! KMWatermarkAdjectiveBaseModel, filesData: self.filesData!)
  378. }
  379. func waterMarkFile(data: KMWatermarkAdjectiveBaseModel, filesData: [KMBatchProcessingTableViewModel]?) {
  380. if filesData?.count != 0 {
  381. for item in filesData! {
  382. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  383. let pdfView = CPDFView()
  384. pdfView.document = document
  385. if (document != nil) {
  386. let watermarks = document!.watermarks()
  387. if (watermarks != nil && watermarks!.count > 0) { /// /// 替换水印
  388. /// 替换
  389. for i in 0 ..< watermarks!.count {
  390. let model = watermarks![i]
  391. document!.removeWatermark(model)
  392. }
  393. }
  394. }
  395. var pageRangeType: Int = 0
  396. var pageRangeString: String = "0"
  397. switch item.pageRange.type {
  398. case .allPage:
  399. pageRangeType = 0
  400. case .oddPage:
  401. pageRangeType = 1
  402. case .evenPage:
  403. pageRangeType = 2
  404. case.custom:
  405. pageRangeString = item.pageRange.selectPages.description
  406. case .currentPage:
  407. pageRangeType = 0
  408. }
  409. data.pageRangeType = pageRangeType
  410. data.pageRangeString = pageRangeString
  411. KMWatermarkAdjectiveTools.apply(data, pdfView, pdfView.document.documentURL.path) {
  412. result in
  413. if (result) {
  414. let alert = NSAlert()
  415. alert.alertStyle = .warning
  416. alert.messageText = "成功"
  417. alert.runModal()
  418. } else {
  419. let alert = NSAlert()
  420. alert.alertStyle = .critical
  421. alert.messageText = "失败"
  422. alert.runModal()
  423. }
  424. }
  425. }
  426. }
  427. }
  428. func backgroundApplay(data: KMBatchSettingItemViewModel) {
  429. if (data == nil) {
  430. let alert = NSAlert()
  431. alert.alertStyle = .critical
  432. alert.messageText = "没有找到背景模型"
  433. alert.runModal()
  434. return
  435. }
  436. let panel = NSOpenPanel()
  437. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  438. button.state = .on
  439. panel.accessoryView = button
  440. panel.canChooseFiles = false
  441. panel.canChooseDirectories = true
  442. panel.canCreateDirectories = true
  443. panel.beginSheetModal(for: self.window!) { [self] response in
  444. if response == .cancel {
  445. return
  446. }
  447. let outputFolderPath = panel.url?.path
  448. self.backgroundFile(outputFolderPath: outputFolderPath!, data: data as! KMBackgroundModel, filesData: self.filesData!)
  449. }
  450. }
  451. func backgroundFile(outputFolderPath: String, data: KMBackgroundModel, filesData: [KMBatchProcessingTableViewModel]?) {
  452. if filesData?.count != 0 {
  453. for item in filesData! {
  454. DispatchQueue.global().async {
  455. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  456. if ((fileName.isEmpty)) {
  457. fileName = NSLocalizedString("Untitled", comment: "")
  458. }
  459. let path = outputFolderPath + "/" + fileName + ".pdf"
  460. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  461. if document != nil {
  462. let property = document!.background()
  463. property!.scale = data.scale
  464. property!.rotation = CGFloat(-data.rotation)
  465. property!.opacity = data.opacity
  466. property?.xOffset = data.horizontalSpace
  467. property?.yOffset = data.verticalSpace
  468. property?.horizontalAlignment = UInt(data.horizontalMode)
  469. property?.verticalAlignment = UInt(data.verticalMode)
  470. if (data.type == .color) {
  471. property?.color = data.color
  472. property?.type = .color
  473. } else if (data.type == .file) {
  474. property?.setImage(NSImage(contentsOfFile: data.imagePath))
  475. property?.type = .image
  476. }
  477. var pageRangeType: Int = 0
  478. var pageRangeString: String = "0"
  479. switch item.pageRange.type {
  480. case .allPage:
  481. pageRangeType = 0
  482. case .oddPage:
  483. pageRangeType = 1
  484. case .evenPage:
  485. pageRangeType = 2
  486. case.custom:
  487. pageRangeString = item.pageRange.selectPages.description
  488. case .currentPage:
  489. pageRangeType = 0
  490. }
  491. data.pageRangeType = pageRangeType
  492. data.pageRangeString = pageRangeString
  493. let pagesString = KMWatermarkAdjectiveTools.findPagesString(data)
  494. if (pagesString.isEmpty) {
  495. property?.pageString = "0-\(document!.pageCount-1)"
  496. } else {
  497. property?.pageString = pagesString
  498. }
  499. property?.update()
  500. let result = document!.write(to: URL(fileURLWithPath: path))
  501. if (result) {
  502. KMPrint("backgroundFile成功")
  503. } else {
  504. KMPrint("backgroundFile失败")
  505. }
  506. }
  507. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  508. }
  509. }
  510. }
  511. }
  512. func headAndFooterApplay(data: KMBatchSettingItemViewModel) {
  513. if (data == nil) {
  514. let alert = NSAlert()
  515. alert.alertStyle = .critical
  516. alert.messageText = "没有找到"
  517. alert.runModal()
  518. return
  519. }
  520. let panel = NSOpenPanel()
  521. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  522. button.state = .on
  523. panel.accessoryView = button
  524. panel.canChooseFiles = false
  525. panel.canChooseDirectories = true
  526. panel.canCreateDirectories = true
  527. panel.beginSheetModal(for: self.window!) { [self] response in
  528. if response == .cancel {
  529. return
  530. }
  531. let outputFolderPath = panel.url?.path
  532. self.headAndFooterFile(outputFolderPath: outputFolderPath!, data: data as! KMHeaderFooterModel, filesData: self.filesData!)
  533. }
  534. }
  535. func headAndFooterFile(outputFolderPath: String, data: KMHeaderFooterModel, filesData: [KMBatchProcessingTableViewModel]?) {
  536. if filesData?.count != 0 {
  537. for item in filesData! {
  538. DispatchQueue.global().async {
  539. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  540. if ((fileName.isEmpty)) {
  541. fileName = NSLocalizedString("Untitled", comment: "")
  542. }
  543. let path = outputFolderPath + "/" + fileName + ".pdf"
  544. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  545. if document != nil {
  546. var property = document!.headerFooter()
  547. var fontSize = 0.0
  548. var fontName: String = ""
  549. switch data.textFont {
  550. case .font(name: let name, size: let size):
  551. fontSize = size
  552. fontName = name
  553. break
  554. default:
  555. break
  556. }
  557. let font = NSFont.boldSystemFont(ofSize:fontSize)
  558. let style = NSMutableParagraphStyle()
  559. style.alignment = .center
  560. style.lineBreakMode = .byCharWrapping
  561. let size: NSSize = "text".boundingRect(with: NSSize(width: 1000, height: 1000), options: NSString.DrawingOptions(rawValue: 3), attributes: [NSAttributedString.Key.font : font, NSAttributedString.Key.paragraphStyle : style]).size
  562. property?.margin = NSEdgeInsetsMake(max(data.topMargin-size.height, 0), data.leftMargin, max(data.bottomMargin-size.height, 0), data.rightMargin)
  563. let strings = KMHeaderFooterPreviewController.parseModel(model: data, pageCount: Int(document!.pageCount))
  564. var count: Int = 0
  565. var color: NSColor!
  566. switch data.textColor {
  567. case .color(red: let red, green: let green, blue: let blue, alpha: let alpha):
  568. color = NSColor(red: red, green: green, blue: blue, alpha: alpha)
  569. default:
  570. break
  571. }
  572. if (color == nil) {
  573. color = NSColor.black
  574. }
  575. for text in strings {
  576. property?.setText(text, at: UInt(count))
  577. property?.setTextColor(color, at: UInt(count))
  578. property?.setFontSize(fontSize, at: UInt(count))
  579. property?.setFontName(fontName, at: UInt(count))
  580. count += 1
  581. }
  582. var pageRangeType: Int = 0
  583. var pageRangeString: String = "0"
  584. switch item.pageRange.type {
  585. case .allPage:
  586. pageRangeType = 0
  587. case .oddPage:
  588. pageRangeType = 1
  589. case .evenPage:
  590. pageRangeType = 2
  591. case.custom:
  592. pageRangeString = item.pageRange.selectPages.description
  593. case .currentPage:
  594. pageRangeType = 0
  595. }
  596. data.pageRangeType = pageRangeType
  597. data.pageRangeString = pageRangeString
  598. let pagesString = KMWatermarkAdjectiveTools.findPagesString(data)
  599. if (pagesString.isEmpty) {
  600. property?.pageString = "0-\(document!.pageCount-1)"
  601. } else {
  602. property?.pageString = pagesString
  603. }
  604. property?.update()
  605. if (FileManager.default.fileExists(atPath: path)) {
  606. try?FileManager.default.removeItem(atPath: path)
  607. }
  608. let result = document!.write(to: URL(fileURLWithPath: path))
  609. if (result) {
  610. KMPrint("headAndFooterFile成功")
  611. } else {
  612. KMPrint("headAndFooterFile失败")
  613. }
  614. }
  615. }
  616. }
  617. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  618. }
  619. }
  620. func batesApplay(data: KMBatchSettingItemViewModel) {
  621. if (data == nil) {
  622. let alert = NSAlert()
  623. alert.alertStyle = .critical
  624. alert.messageText = "没有找到"
  625. alert.runModal()
  626. return
  627. }
  628. let panel = NSOpenPanel()
  629. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  630. button.state = .on
  631. panel.accessoryView = button
  632. panel.canChooseFiles = false
  633. panel.canChooseDirectories = true
  634. panel.canCreateDirectories = true
  635. panel.beginSheetModal(for: self.window!) { [self] response in
  636. if response == .cancel {
  637. return
  638. }
  639. let outputFolderPath = panel.url?.path
  640. self.batesFile(outputFolderPath: outputFolderPath!, data: data as! KMBatesModel, filesData: self.filesData!)
  641. }
  642. }
  643. func batesFile(outputFolderPath: String, data: KMBatesModel, filesData: [KMBatchProcessingTableViewModel]?) {
  644. if filesData?.count != 0 {
  645. for item in filesData! {
  646. DispatchQueue.global().async {
  647. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  648. if ((fileName.isEmpty)) {
  649. fileName = NSLocalizedString("Untitled", comment: "")
  650. }
  651. let path = outputFolderPath + "/" + fileName + ".pdf"
  652. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  653. if document != nil {
  654. var property = document!.bates()
  655. var fontSize = 0.0
  656. var fontName: String = ""
  657. switch data.textFont {
  658. case .font(name: let name, size: let size):
  659. fontName = name
  660. fontSize = size
  661. break
  662. default:
  663. break
  664. }
  665. let font = NSFont.boldSystemFont(ofSize:fontSize)
  666. let style = NSMutableParagraphStyle()
  667. style.alignment = .center
  668. style.lineBreakMode = .byCharWrapping
  669. let size: NSSize = "text".boundingRect(with: NSSize(width: 1000, height: 1000), options: NSString.DrawingOptions(rawValue: 3), attributes: [NSAttributedString.Key.font : font, NSAttributedString.Key.paragraphStyle : style]).size
  670. property?.margin = NSEdgeInsetsMake(max(data.topMargin-size.height, 0), data.leftMargin, max(data.bottomMargin-size.height, 0), data.rightMargin)
  671. let strings = [data.topLeftString,
  672. data.topCenterString,
  673. data.topRightString,
  674. data.bottomLeftString,
  675. data.bottomCenterString,
  676. data.bottomRightString]
  677. var count: Int = 0
  678. var color: NSColor!
  679. switch data.textColor {
  680. case .color(red: let red, green: let green, blue: let blue, alpha: let alpha):
  681. color = NSColor(red: red, green: green, blue: blue, alpha: alpha)
  682. default:
  683. break
  684. }
  685. if (color == nil) {
  686. color = NSColor.black
  687. }
  688. for text in strings {
  689. property?.setText(text, at: UInt(count))
  690. property?.setTextColor(color, at: UInt(count))
  691. property?.setFontSize(fontSize, at: UInt(count))
  692. property?.setFontName(fontName, at: UInt(count))
  693. count += 1
  694. }
  695. var pageRangeType: Int = 0
  696. var pageRangeString: String = "0"
  697. switch item.pageRange.type {
  698. case .allPage:
  699. pageRangeType = 0
  700. case .oddPage:
  701. pageRangeType = 1
  702. case .evenPage:
  703. pageRangeType = 2
  704. case.custom:
  705. pageRangeString = item.pageRange.selectPages.description
  706. case .currentPage:
  707. pageRangeType = 0
  708. }
  709. data.pageRangeType = pageRangeType
  710. data.pageRangeString = pageRangeString
  711. let pagesString = KMWatermarkAdjectiveTools.findPagesString(data)
  712. if (pagesString.isEmpty) {
  713. property?.pageString = "0-\(document!.pageCount-1)"
  714. } else {
  715. property?.pageString = pagesString
  716. }
  717. property?.update()
  718. if (FileManager.default.fileExists(atPath: path)) {
  719. try?FileManager.default.removeItem(atPath: path)
  720. }
  721. let result = document!.write(to: URL(fileURLWithPath: path))
  722. if (result) {
  723. KMPrint("batesFile成功")
  724. } else {
  725. KMPrint("batesFile失败")
  726. }
  727. }
  728. }
  729. }
  730. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  731. }
  732. }
  733. func removeApplay(data: KMBatchSettingItemViewModel) {
  734. if (data == nil) {
  735. let alert = NSAlert()
  736. alert.alertStyle = .critical
  737. alert.messageText = "没有找到"
  738. alert.runModal()
  739. return
  740. }
  741. let panel = NSOpenPanel()
  742. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  743. button.state = .on
  744. panel.accessoryView = button
  745. panel.canChooseFiles = false
  746. panel.canChooseDirectories = true
  747. panel.canCreateDirectories = true
  748. panel.beginSheetModal(for: self.window!) { [self] response in
  749. if response == .cancel {
  750. return
  751. }
  752. let outputFolderPath = panel.url?.path
  753. self.removeFile(outputFolderPath: outputFolderPath!, data: data as! KMBatchRemoveViewModel, filesData: self.filesData!)
  754. }
  755. }
  756. func removeFile(outputFolderPath: String, data: KMBatchRemoveViewModel, filesData: [KMBatchProcessingTableViewModel]?) {
  757. if filesData?.count != 0 {
  758. for item in filesData! {
  759. // DispatchQueue.global().async {
  760. var fileName = item.filePath.deletingPathExtension.lastPathComponent
  761. if ((fileName.isEmpty)) {
  762. fileName = NSLocalizedString("Untitled", comment: "")
  763. }
  764. let path = outputFolderPath + "/" + fileName + ".pdf"
  765. let document = CPDFDocument.init(url: URL(fileURLWithPath: item.filePath))
  766. if document != nil {
  767. if (document!.allowsPrinting == false || document!.allowsCopying == false) {
  768. let alert = NSAlert()
  769. alert.alertStyle = .critical
  770. alert.messageText = "此文档不允许修改"
  771. alert.runModal()
  772. return
  773. }
  774. if (data.options.contains(.security)) {
  775. }
  776. if (data.options.contains(.batesNumber)) {
  777. let property = document!.bates()
  778. property?.clear()
  779. }
  780. if (data.options.contains(.headerAndFooter)) {
  781. let property = document!.headerFooter()
  782. property?.clear()
  783. }
  784. if (data.options.contains(.background)) {
  785. let property = document!.background()
  786. property?.clear()
  787. }
  788. if (data.options.contains(.watermark)) {
  789. let array: Array<CPDFWatermark> = document!.watermarks() ?? []
  790. for model in array {
  791. document!.removeWatermark(model)
  792. }
  793. }
  794. if (FileManager.default.fileExists(atPath: path)) {
  795. try?FileManager.default.removeItem(atPath: path)
  796. }
  797. let result = document!.write(to: URL(fileURLWithPath: path))
  798. if (result) {
  799. KMPrint("removeFile成功")
  800. } else {
  801. KMPrint("removeFile失败")
  802. }
  803. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: outputFolderPath)])
  804. }
  805. // }
  806. }
  807. }
  808. }
  809. }