KMBatchAddBackgroundOperation.swift 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. //
  2. // KMBatchAddBackgroundOperation.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by liujiajie on 2023/12/11.
  6. //
  7. import Foundation
  8. class KMBatchAddBackgroundOperation: KMBatchOperation{
  9. var background: KMBackgroundModel?
  10. var pdfDocument: CPDFDocument!
  11. var password: String = ""
  12. init(file: KMBatchOperateFile, backgroundM: KMBackgroundModel) {
  13. super.init(file: file)
  14. self.background = backgroundM
  15. self.password = file.password
  16. }
  17. override func start() {
  18. self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: self.operateFile?.filePath ?? ""))
  19. if let data = self.pdfDocument?.isLocked, data {
  20. self.pdfDocument?.unlock(withPassword: self.operateFile?.password)
  21. }
  22. if !self.isCancelled {
  23. self.delegate?.fileBeginOperate?(self.operateFile!, info: self.operateFile!.addBackgroundInfo)
  24. willChangeValue(forKey: "isExecuting")
  25. self.hasExcuting = true
  26. didChangeValue(forKey: "isExecuting")
  27. let newArr = NSMutableArray()
  28. for i in 0..<(self.operateFile?.addBackgroundInfo.pagesArray?.count ?? 0) {
  29. let number = self.operateFile?.addBackgroundInfo.pagesArray![i]
  30. newArr.add(number!.intValue - 1)
  31. }
  32. if !FileManager.default.fileExists(atPath: self.operateFile!.filePath) {
  33. self.delegate?.fileOperateFailed?(self.operateFile!, error: self.errorWithMsg(KMLocalizedString("File Not Exist", nil)), info: self.operateFile!.addBackgroundInfo)
  34. self.willChangeValue(forKey: "isFinished")
  35. self.hasFinished = true
  36. self.didChangeValue(forKey: "isFinished")
  37. return
  38. }
  39. if self.pdfDocument == nil {
  40. self.delegate?.fileOperateFailed?(self.operateFile!, error: self.errorWithMsg(KMLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", nil)), info: self.operateFile!.addBackgroundInfo)
  41. self.willChangeValue(forKey: "isFinished")
  42. self.hasFinished = true
  43. self.didChangeValue(forKey: "isFinished")
  44. return
  45. }
  46. if !self.pdfDocument!.allowsPrinting || !self.pdfDocument!.allowsCopying {
  47. self.delegate?.fileOperateFailed?(self.operateFile!, error: self.errorWithMsg(KMLocalizedString("This is a secured document. Editing is not permitted.", nil)), info: self.operateFile!.addBackgroundInfo)
  48. self.willChangeValue(forKey: "isFinished")
  49. self.hasFinished = true
  50. self.didChangeValue(forKey: "isFinished")
  51. return
  52. }
  53. if newArr.count < 1 {
  54. let err = NSError(domain: "LocalError", code: 0, userInfo: [NSLocalizedDescriptionKey: KMLocalizedString("Invalid page range or the page number is out of range. Please try again.", nil)])
  55. self.delegate?.fileOperateFailed?(self.operateFile!, error: err, info: self.operateFile!.addBackgroundInfo)
  56. self.willChangeValue(forKey: "isFinished")
  57. self.hasFinished = true
  58. self.didChangeValue(forKey: "isFinished")
  59. }
  60. self.background?.pagesString = newArr.componentsJoined(by: ",")
  61. self.saveAsPDF(background: self.background!, path: (self.operateFile?.addBackgroundInfo.fetchDestinationFilepath())!)
  62. }else {
  63. willChangeValue(forKey: "isFinished")
  64. willChangeValue(forKey: "isExecuting")
  65. hasExcuting = false
  66. hasFinished = true
  67. didChangeValue(forKey: "isExecuting")
  68. didChangeValue(forKey: "isFinished")
  69. }
  70. }
  71. func saveAsPDF(background: KMBackgroundModel, path: String) {
  72. var filePath = self.pdfDocument?.documentURL?.path
  73. let password = self.password
  74. if filePath?.count ?? 0 < 1 {
  75. let str = String(format: "%@.pdf", KMLocalizedString("Untitled", nil))
  76. let writeSuccess = self.pdfDocument!.write(to: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  77. if writeSuccess {
  78. let newDocument: CPDFDocument = CPDFDocument(url: URL(fileURLWithPath: (kTempSavePath?.stringByAppendingPathComponent(str))!))
  79. filePath = newDocument.documentURL?.path
  80. } else {
  81. NSSound.beep()
  82. return
  83. }
  84. }
  85. guard let document = CPDFDocument(url: URL(fileURLWithPath: filePath!)) else {
  86. return
  87. }
  88. if password.count > 0 {
  89. document.unlock(withPassword: password)
  90. }
  91. let tBackground: CPDFBackground = document.background()
  92. tBackground.opacity = background.opacity
  93. tBackground.scale = background.scale
  94. tBackground.rotation = CGFloat(-background.rotation)
  95. tBackground.horizontalAlignment = UInt(background.horizontalMode)
  96. tBackground.verticalAlignment = UInt(background.verticalMode)
  97. tBackground.xOffset = background.horizontalSpace
  98. tBackground.yOffset = background.verticalSpace
  99. if background.imagePath.count != 0 {
  100. let image = NSImage(contentsOfFile: background.imagePath)!
  101. tBackground.setImage(image)
  102. tBackground.type = .image
  103. } else if let color = background.color {
  104. tBackground.color = color
  105. tBackground.type = .color
  106. }
  107. if background.pagesString.count != 0 {
  108. tBackground.pageString = background.pagesString
  109. } else {
  110. let pageString = "0-\(document.pageCount - 1)"
  111. tBackground.pageString = pageString
  112. }
  113. tBackground.update()
  114. // Save to temporary path
  115. let documentPath = NSTemporaryDirectory()
  116. let tempPath = (documentPath as NSString).appendingPathComponent((path as NSString).lastPathComponent)
  117. try? FileManager.default.removeItem(atPath: tempPath)
  118. let result = document.write(to: URL(fileURLWithPath: tempPath))
  119. if result {
  120. if FileManager.default.fileExists(atPath: path) {
  121. try? FileManager.default.removeItem(atPath: path)
  122. }
  123. try? FileManager.default.moveItem(atPath: tempPath, toPath: path)
  124. } else {
  125. try? FileManager.default.removeItem(atPath: tempPath)
  126. }
  127. if result {
  128. self.delegate?.fileOperateSuccessed?(self.operateFile!, info: self.operateFile!.addBackgroundInfo)
  129. }else {
  130. self.delegate?.fileOperateFailed?(self.operateFile!, error: self.errorWithMsg(KMLocalizedString("Failed", nil)), info: self.operateFile!.addBackgroundInfo)
  131. }
  132. self.willChangeValue(forKey: "isFinished")
  133. self.hasFinished = true
  134. self.didChangeValue(forKey: "isFinished")
  135. }
  136. override func cancel() {
  137. // super.cancel()
  138. if isExecuting {
  139. operateFile!.removeWatermarkInfo.status = .Waiting
  140. if FileManager.default.fileExists(atPath: (self.operateFile?.addBackgroundInfo.outPutPath)!) { try? FileManager.default.removeItem(atPath: (self.operateFile?.addBackgroundInfo.outPutPath)!)
  141. }
  142. self.delegate?.fileOperateCanceled?(self.operateFile!, info: self.operateFile!.addBackgroundInfo)
  143. willChangeValue(forKey: "isFinished")
  144. hasFinished = true
  145. didChangeValue(forKey: "isFinished")
  146. } else {
  147. willChangeValue(forKey: "isCancelled")
  148. hasCanceled = true
  149. didChangeValue(forKey: "isCancelled")
  150. }
  151. }
  152. }