KMMergeWindowController.swift 20 KB

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