KMMergeWindowController.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. //
  2. // KMMergeWindowController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2023/11/8.
  6. //
  7. import Cocoa
  8. typealias KMMergeWindowControllerCancelAction = (_ controller: KMMergeWindowController) -> Void
  9. typealias KMMergeWindowControllerAddFilesAction = (_ controller: KMMergeWindowController) -> Void
  10. typealias KMMergeWindowControllerMergeAction = (_ controller: KMMergeWindowController, _ filePath: String) -> Void
  11. typealias KMMergeWindowControllerClearAction = (_ controller: KMMergeWindowController) -> Void
  12. class KMMergeWindowController: KMNBaseWindowController {
  13. @IBOutlet weak var mergeView: KMMergeView!
  14. var cancelAction: KMCommonBlock?
  15. var oldPDFDocument: PDFDocument = PDFDocument()
  16. var password: String = ""
  17. var oriDucumentUrl: URL? {
  18. didSet {
  19. oldPDFDocument = PDFDocument(url: oriDucumentUrl!)!
  20. oldPDFDocument.unlock(withPassword: self.password)
  21. }
  22. }
  23. var type: KMMergeViewType = .add
  24. var pageIndex: Int?
  25. var mergeAction: KMMergeWindowControllerMergeAction?
  26. override func windowDidLoad() {
  27. super.windowDidLoad()
  28. self.window!.title = NSLocalizedString("Merge PDF Files", comment: "");
  29. // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
  30. self.mergeView.type = self.type
  31. mergeView.addFilesAction = { [weak self] view in
  32. guard let self = self else { return }
  33. self.addFile()
  34. }
  35. mergeView.clearAction = { view in
  36. }
  37. mergeView.mergeAction = { [weak self] view, files, size in
  38. guard let self = self else { return }
  39. self.mergeFiles(files: files, size: size)
  40. }
  41. mergeView.cancelAction = { [weak self] view in
  42. guard let self = self else { return }
  43. self._clearImageData()
  44. self.cancelAction?(self)
  45. }
  46. //原始数据加载
  47. if oriDucumentUrl != nil && oriDucumentUrl?.path.count != 0 {
  48. let file = KMFileAttribute()
  49. file.filePath = oriDucumentUrl?.path ?? ""
  50. file.password = self.password
  51. self.mergeView.files = [file]
  52. }
  53. }
  54. }
  55. extension KMMergeWindowController {
  56. func addFile() {
  57. var size = 0.0
  58. let files = self.mergeView.files
  59. for file in files {
  60. size = size + file.fileSize
  61. }
  62. if !IAPProductsManager.default().isAvailableAllFunction() && (files.count >= 2 || size > 20 * 1024 * 1024) {
  63. let winC = KMPurchaseCompareWindowController.sharedInstance()
  64. if self.kEventTag == 1 {
  65. winC?.kEventName = "Onbrd_Merge_BuyNow"
  66. } else {
  67. winC?.kEventName = "Reading_Merge_BuyNow"
  68. }
  69. winC?.showWindow(nil)
  70. return
  71. }
  72. let openPanel = NSOpenPanel()
  73. openPanel.allowedFileTypes = KMTools.imageExtensions + KMTools.pdfExtensions
  74. openPanel.allowsMultipleSelection = true
  75. openPanel.message = NSLocalizedString("Select files to merge. To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", comment: "")
  76. openPanel.beginSheetModal(for: self.window!) { (result) in
  77. if result == NSApplication.ModalResponse.OK {
  78. var array: [URL] = []
  79. for fileURL in openPanel.urls {
  80. if KMTools.isImageType(fileURL.pathExtension) {
  81. if let image = NSImage(contentsOf: fileURL) {
  82. if let page = PDFPage(image: image) {
  83. let document = PDFDocument()
  84. document.insert(page, at: 0)
  85. var path = self._saveImagePath() + "/" + fileURL.deletingPathExtension().lastPathComponent + ".pdf"
  86. path = KMTools.getUniqueFilePath(filePath: path)
  87. let result = document.write(toFile: path)
  88. if result {
  89. let file = KMFileAttribute()
  90. file.filePath = path
  91. file.oriFilePath = fileURL.path
  92. file.myPDFDocument = document
  93. let attribe = try?FileManager.default.attributesOfItem(atPath: fileURL.path)
  94. let fileSize = attribe?[FileAttributeKey.size] as? CGFloat ?? 0
  95. size = fileSize + size
  96. if !IAPProductsManager.default().isAvailableAllFunction() && (files.count >= 2 || size > 20 * 1024 * 1024) {
  97. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  98. return
  99. }
  100. self.mergeView.files.append(file)
  101. }
  102. }
  103. } else {
  104. Task {
  105. _ = await KMAlertTool.runModel(message: NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: ""))
  106. }
  107. }
  108. } else {
  109. array.append(fileURL)
  110. }
  111. }
  112. let attribe = try?FileManager.default.attributesOfItem(atPath: openPanel.urls.first!.path)
  113. let fileSize = attribe?[FileAttributeKey.size] as? CGFloat ?? 0
  114. size = fileSize + size
  115. if !IAPProductsManager.default().isAvailableAllFunction() && (files.count >= 2 || size > 20 * 1024 * 1024) {
  116. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  117. return
  118. }
  119. self.mergeView.addFilePaths(urls: array)
  120. }
  121. }
  122. }
  123. private func _saveImagePath() -> String {
  124. let rootPath = KMDataManager.fetchAppSupportOfBundleIdentifierDirectory()
  125. let path = rootPath.appendingPathComponent("Merge").path
  126. if FileManager.default.fileExists(atPath: path) == false {
  127. try?FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false)
  128. }
  129. return path
  130. }
  131. private func _clearImageData() {
  132. let path = self._saveImagePath()
  133. if FileManager.default.fileExists(atPath: path) {
  134. try?FileManager.default.removeItem(atPath: path)
  135. }
  136. }
  137. func mergeFiles(files: [KMFileAttribute], size: CGSize = .zero) {
  138. var size = 0.0
  139. for file in files {
  140. size = size + file.fileSize
  141. }
  142. if !IAPProductsManager.default().isAvailableAllFunction() && (files.count >= 2 || size > 20 * 1024 * 1024) {
  143. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  144. return
  145. }
  146. var filesCount = 1
  147. if self.oriDucumentUrl != nil {
  148. filesCount = 0
  149. }
  150. if files.count <= filesCount {
  151. let alert = NSAlert.init()
  152. alert.alertStyle = .critical
  153. alert.messageText = NSLocalizedString("To start merging, please select at least 2 files.", comment: "")
  154. alert.runModal()
  155. return
  156. }
  157. var rootPDFOutlineArray: [PDFOutline] = []
  158. var allPage = true //只有是全部才支持大纲的合并
  159. for file in files {
  160. if file.fetchSelectPages().count == 0 {
  161. let alert = NSAlert.init()
  162. alert.alertStyle = .critical
  163. alert.messageText = "\(file.filePath.lastPathComponent) + \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  164. alert.runModal()
  165. return
  166. }
  167. allPage = file.bAllPage
  168. /*防止文件被地址变换后crash*/
  169. guard let tDocument = PDFDocument(url: NSURL(fileURLWithPath: file.filePath) as URL) else {
  170. print("文件不存在")
  171. let alert = NSAlert.init()
  172. alert.alertStyle = .critical
  173. alert.messageText = "\(file.filePath.lastPathComponent) + \(NSLocalizedString("File Not Exist", comment: ""))"
  174. alert.runModal()
  175. return
  176. }
  177. var outlineArray: [PDFOutline] = []
  178. tDocument.unlock(withPassword: file.password)
  179. if tDocument.outlineRoot != nil {
  180. rootPDFOutlineArray.append((tDocument.outlineRoot)!)
  181. self.fetchAllOfChildren((tDocument.outlineRoot)!, containerArray: &outlineArray)
  182. outlineArray.removeObject((tDocument.outlineRoot)!)
  183. } else {
  184. let rootOutline = PDFOutline.init()
  185. tDocument.outlineRoot = rootOutline
  186. if tDocument.outlineRoot != nil {
  187. rootPDFOutlineArray.append(tDocument.outlineRoot!)
  188. }
  189. }
  190. for number in file.fetchSelectPages() {
  191. let page = tDocument.page(at: number - 1)
  192. self.oldPDFDocument.insert(page!, at: self.oldPDFDocument.pageCount)
  193. }
  194. }
  195. var theFilepath = files.first?.filePath
  196. if let filepath = files.first?.oriFilePath {
  197. theFilepath = filepath
  198. }
  199. let fileName = (theFilepath?.deletingPathExtension.lastPathComponent ?? "") + "_Merged"
  200. DispatchQueue.main.async {
  201. if self.oldPDFDocument.outlineRoot == nil {
  202. self.oldPDFDocument.outlineRoot = PDFOutline.init()
  203. }
  204. var insertIndex = 0
  205. for i in 0..<rootPDFOutlineArray.count {
  206. let rootOutline = rootPDFOutlineArray[i]
  207. for j in 0..<rootOutline.numberOfChildren {
  208. self.oldPDFDocument.outlineRoot?.insertChild(rootOutline.child(at: j)!, at: insertIndex)
  209. insertIndex = insertIndex + 1
  210. }
  211. }
  212. self.handleReDraw()
  213. if self.oriDucumentUrl != nil {
  214. let newPath = self.oldPDFDocument.documentURL!.path
  215. var options: [PDFDocumentWriteOption : Any] = [:]
  216. var success = false
  217. let password = self.password
  218. let pdf = self.oldPDFDocument
  219. let savePanelAccessoryViewController = KMSavePanelAccessoryController.init()
  220. let savePanel = NSSavePanel()
  221. savePanel.nameFieldStringValue = fileName
  222. savePanel.allowedFileTypes = ["pdf"]
  223. savePanel.accessoryView = savePanelAccessoryViewController.view
  224. savePanel.beginSheetModal(for: self.window!) { result in
  225. if result == .OK {
  226. self._clearImageData()
  227. self.cancelAction?()
  228. var outputSavePanel = savePanel.url?.path ?? ""
  229. DispatchQueue.main.async {
  230. var success = false
  231. if pdf.isEncrypted {
  232. options.updateValue(password, forKey: .userPasswordOption)
  233. options.updateValue(password, forKey: .ownerPasswordOption)
  234. success = pdf.write(toFile: outputSavePanel, withOptions: options)
  235. } else {
  236. success = pdf.write(toFile: outputSavePanel)
  237. }
  238. if success {
  239. if savePanelAccessoryViewController.needOpen {
  240. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { document, open, error in
  241. }
  242. } else {
  243. NSWorkspace.shared.activateFileViewerSelecting([NSURL(fileURLWithPath: outputSavePanel) as URL])
  244. }
  245. } else {
  246. let alert = NSAlert.init()
  247. alert.alertStyle = .critical
  248. alert.messageText = "\(String(describing: files.first?.filePath.lastPathComponent)) + \(NSLocalizedString("Failed to merge!", comment: ""))"
  249. alert.runModal()
  250. }
  251. }
  252. }
  253. }
  254. } else {
  255. let savePanelAccessoryViewController = KMSavePanelAccessoryController.init()
  256. let savePanel = NSSavePanel()
  257. savePanel.nameFieldStringValue = fileName
  258. savePanel.allowedFileTypes = ["pdf"]
  259. savePanel.accessoryView = savePanelAccessoryViewController.view
  260. savePanel.beginSheetModal(for: self.window!) { result in
  261. if result == .OK {
  262. self._clearImageData()
  263. self.cancelAction?()
  264. var outputSavePanel = savePanel.url?.path
  265. DispatchQueue.main.async {
  266. var success = self.oldPDFDocument.write(toFile: outputSavePanel!)
  267. if !success {
  268. success = ((try?self.oldPDFDocument.dataRepresentation()?.write(to: URL(string: outputSavePanel!)!)) != nil)
  269. }
  270. if success {
  271. if savePanelAccessoryViewController.needOpen {
  272. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { document, open, error in
  273. }
  274. } else {
  275. NSWorkspace.shared.activateFileViewerSelecting([NSURL(fileURLWithPath: outputSavePanel!) as URL])
  276. }
  277. } else {
  278. let alert = NSAlert.init()
  279. alert.alertStyle = .critical
  280. alert.messageText = "\(String(describing: files.first?.filePath.lastPathComponent)) + \(NSLocalizedString("Failed to merge!", comment: ""))"
  281. alert.runModal()
  282. }
  283. }
  284. }
  285. }
  286. }
  287. }
  288. }
  289. func fetchAllOfChildren(_ aOutline: PDFOutline, containerArray aMArray: inout [PDFOutline]) {
  290. if !aMArray.contains(aOutline) {
  291. aMArray.append(aOutline)
  292. }
  293. for i in 0..<aOutline.numberOfChildren {
  294. if let childOutline = aOutline.child(at: i) {
  295. aMArray.append(childOutline)
  296. fetchAllOfChildren(childOutline, containerArray: &aMArray)
  297. }
  298. }
  299. }
  300. func handleReDraw() {
  301. if mergeView.originalSizeButton.state == .on {
  302. } else {
  303. let size = self.mergeView.newPageSize
  304. if size.width < 0 {
  305. return
  306. }
  307. var pagesArray: [PDFPage] = []
  308. let pageCount = self.oldPDFDocument.pageCount
  309. for i in 0..<pageCount {
  310. pagesArray.append(self.oldPDFDocument.page(at: 0)!)
  311. self.oldPDFDocument.removePage(at: 0)
  312. }
  313. for i in 0..<pageCount {
  314. let page: KMMergePDFPage = KMMergePDFPage.init()
  315. page.setBounds(NSMakeRect(0, 0, size.width, size.height), for: .mediaBox)
  316. page.drawingPage = pagesArray[i]
  317. self.oldPDFDocument.insert(page, at: i)
  318. }
  319. if self.oldPDFDocument.outlineRoot != nil {
  320. let childCount = self.oldPDFDocument.outlineRoot?.numberOfChildren
  321. var outlineArray: [PDFOutline] = []
  322. for i in 0..<childCount! {
  323. outlineArray.append((self.oldPDFDocument.outlineRoot?.child(at: i))!)
  324. }
  325. for outline in outlineArray {
  326. outline.removeFromParent()
  327. }
  328. }
  329. }
  330. }
  331. }
  332. class KMMergePDFPage: PDFPage {
  333. var drawingPage: PDFPage?
  334. override func draw(with box: PDFDisplayBox, to context: CGContext) {
  335. super.draw(with: box, to: context)
  336. let pageSize = self.bounds(for: .cropBox).size
  337. self.drawPage(with: context, page: self.drawingPage!, pageSize: pageSize)
  338. }
  339. func drawPage(with context: CGContext, page: PDFPage, pageSize: CGSize) {
  340. var originalSize = page.bounds(for: .cropBox).size
  341. // 如果页面的旋转角度为90或者270,宽高交换
  342. if page.rotation % 180 != 0 {
  343. originalSize = CGSize(width: originalSize.height, height: originalSize.width)
  344. }
  345. let wRatio = pageSize.width / originalSize.width
  346. let hRatio = pageSize.height / originalSize.height
  347. let ratio = min(wRatio, hRatio)
  348. context.saveGState()
  349. let xTransform = (pageSize.width - originalSize.width * ratio) / 2
  350. let yTransform = (pageSize.height - originalSize.height * ratio) / 2
  351. context.translateBy(x: xTransform, y: yTransform)
  352. context.scaleBy(x: ratio, y: ratio)
  353. if #available(macOS 10.12, *) {
  354. page.draw(with: .cropBox, to: context)
  355. page.transformContext(for: .cropBox)
  356. } else {
  357. NSGraphicsContext.saveGraphicsState()
  358. NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
  359. page.draw(with: .cropBox)
  360. NSGraphicsContext.restoreGraphicsState()
  361. page.transformContext(for: .cropBox)
  362. }
  363. context.restoreGState()
  364. }
  365. }