KMMergeWindowController.swift 21 KB

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