KMMergeWindowController.swift 18 KB

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