KMMergeWindowController.swift 18 KB

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