KMMergeWindowController.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 = { [unowned self] view in
  58. self.addFile()
  59. }
  60. mergeView.clearAction = { [unowned self] view in
  61. }
  62. mergeView.mergeAction = { [unowned self] view, files, size in
  63. self.mergeFiles(files: files, size: size)
  64. }
  65. mergeView.cancelAction = { [unowned self] view in
  66. cancelAction?(self)
  67. }
  68. }
  69. }
  70. extension KMMergeWindowController {
  71. func addFile() {
  72. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  73. // //免費版只支援2個檔案做合併小于20M的文件合并
  74. // if (_files.count >= 2 || self.allFileSize > (20 * 1024 * 1024)) {
  75. // #if VERSION_DMG
  76. // [[KMPurchaseCompareWindowController sharedInstance] showWindow:nil];
  77. // #else
  78. // KMToolCompareWindowController * vc = [KMToolCompareWindowController toolCompareWithType:KMCompareWithToolType_PageEdit setSelectIndex:1];
  79. // [vc showWindow:nil];
  80. // #endif
  81. // return;
  82. // }
  83. //
  84. // }
  85. let openPanel = NSOpenPanel()
  86. openPanel.allowedFileTypes = ["pdf"]
  87. if KMPurchaseManager.manager.state == .subscription {
  88. openPanel.allowsMultipleSelection = true
  89. openPanel.message = NSLocalizedString("Select files to merge. To select multiple files press cmd ⌘ button on the keyboard and click on the target files one by one.", comment: "")
  90. } else {
  91. openPanel.allowsMultipleSelection = false
  92. openPanel.message = NSLocalizedString("Select files to merge, only one file can be selected at a time.", comment: "")
  93. }
  94. openPanel.beginSheetModal(for: self.window!) { (result) in
  95. if result == NSApplication.ModalResponse.OK {
  96. var array: [URL] = []
  97. for fileURL in openPanel.urls {
  98. array.append(fileURL)
  99. // if let filePath = fileURL.path {
  100. // if !FileManager.default.isExecutableFile(atPath: filePath) {
  101. // continue
  102. // }
  103. //
  104. // do {
  105. // let attrib = try FileManager.default.attributesOfItem(atPath: filePath)
  106. //// if let fileSize = attrib[FileAttributeKey.size] as? NSNumber {
  107. //// self.allFileSize += fileSize.floatValue
  108. //// }
  109. ////
  110. //// if !IAPProductsManager.defaultManager.isAvailableAllFunction {
  111. //// if self.allFileSize > (20 * 1024 * 1024) || self.files.count >= 2 {
  112. //// let vc = KMToolCompareWindowController.toolCompare(withType: .pageEdit, setSelectIndex: 1)
  113. //// vc?.showWindow(nil)
  114. //// self.allFileSize -= fileSize.floatValue
  115. //// self.addFiles(array)
  116. //// return
  117. //// }
  118. //// }
  119. // array.append(fileURL)
  120. // } catch {
  121. // print("Error getting file attributes: \(error)")
  122. // }
  123. // }
  124. }
  125. self.mergeView.addFilePaths(urls: array)
  126. }
  127. }
  128. }
  129. func mergeFiles(files: [KMFileAttribute], size: CGSize = CGSizeZero) {
  130. if !IAPProductsManager.default().isAvailableAllFunction() && files.count > 2 {
  131. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  132. return
  133. }
  134. var filesCount = 1
  135. if self.oriDucumentUrl != nil {
  136. filesCount = 0
  137. }
  138. if files.count <= filesCount {
  139. let alert = NSAlert.init()
  140. alert.alertStyle = .critical
  141. alert.messageText = NSLocalizedString("To start merging, please select at least 2 files.", comment: "")
  142. alert.runModal()
  143. return
  144. }
  145. // _isSuccessfully = NO;
  146. // [self.nCancelVC setEnabled:NO];
  147. // self.canMerge = NO;
  148. //
  149. var rootPDFOutlineArray: [PDFOutline] = []
  150. var allPage = true //只有是全部才支持大纲的合并
  151. for file in files {
  152. if file.fetchSelectPages().count == 0 {
  153. let alert = NSAlert.init()
  154. alert.alertStyle = .critical
  155. alert.messageText = "\(file.filePath.lastPathComponent) + \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  156. alert.runModal()
  157. return
  158. }
  159. allPage = file.bAllPage
  160. let tDocument = PDFDocument(url: NSURL(fileURLWithPath: file.filePath) as URL)!
  161. var outlineArray: [PDFOutline] = []
  162. // if file.isLocked {
  163. tDocument.unlock(withPassword: file.password)
  164. // }
  165. if tDocument.outlineRoot != nil {
  166. rootPDFOutlineArray.append((tDocument.outlineRoot)!)
  167. self.fetchAllOfChildren((tDocument.outlineRoot)!, containerArray: &outlineArray)
  168. outlineArray.removeObject((tDocument.outlineRoot)!)
  169. } else {
  170. let rootOutline = PDFOutline.init()
  171. tDocument.outlineRoot = rootOutline
  172. if tDocument.outlineRoot != nil {
  173. rootPDFOutlineArray.append(tDocument.outlineRoot!)
  174. }
  175. }
  176. for number in file.fetchSelectPages() {
  177. let page = tDocument.page(at: number - 1)
  178. // if pageIndex != nil {
  179. // self.oldPDFDocument.insert(page!, at: pageIndex!)
  180. // pageIndex = pageIndex! + 1
  181. // } else {
  182. self.oldPDFDocument.insert(page!, at: self.oldPDFDocument.pageCount)
  183. // }
  184. // self.insertIndexSet.addIndex:(self.pdfDocument.pageCount - 1)
  185. }
  186. }
  187. let fileName = (files.first?.filePath.deletingPathExtension.lastPathComponent ?? "") + "_Merged"
  188. DispatchQueue.main.async {
  189. self.oldPDFDocument.outlineRoot = PDFOutline.init()
  190. // if allPage {
  191. var insertIndex = 0
  192. for i in 0..<rootPDFOutlineArray.count {
  193. let rootOutline = rootPDFOutlineArray[i]
  194. for j in 0..<rootOutline.numberOfChildren {
  195. self.oldPDFDocument.outlineRoot?.insertChild(rootOutline.child(at: j)!, at: insertIndex)
  196. insertIndex = insertIndex + 1
  197. }
  198. }
  199. self.handleReDraw()
  200. if self.oriDucumentUrl != nil {
  201. let newPath = self.oldPDFDocument.documentURL!.path
  202. var options: [PDFDocumentWriteOption : Any] = [:]
  203. var success = false
  204. let password = self.password
  205. let pdf = self.oldPDFDocument
  206. if pdf.isEncrypted {
  207. options.updateValue(password, forKey: .userPasswordOption)
  208. options.updateValue(password, forKey: .ownerPasswordOption)
  209. success = pdf.write(toFile: newPath, withOptions: options)
  210. } else {
  211. success = pdf.write(toFile: newPath)
  212. }
  213. // var success = self.oldPDFDocument.write(toFile: self.oldPDFDocument.documentURL!.path)
  214. if success {
  215. self.mergeAction?(self, self.oldPDFDocument.documentURL!.path)
  216. } else {
  217. print("合并失败")
  218. }
  219. } else {
  220. let savePanelAccessoryViewController = KMSavePanelAccessoryController.init()
  221. let savePanel = NSSavePanel()
  222. savePanel.nameFieldStringValue = fileName
  223. savePanel.allowedFileTypes = ["pdf"]
  224. savePanel.accessoryView = savePanelAccessoryViewController.view
  225. // self.savePanelAccessoryViewController = savePanelAccessoryViewController;
  226. savePanel.beginSheetModal(for: self.window!) { result in
  227. if result == .OK {
  228. var outputSavePanel = savePanel.url?.path
  229. DispatchQueue.main.async {
  230. var success = self.oldPDFDocument.write(toFile: outputSavePanel!)
  231. if !success {
  232. success = ((try?self.oldPDFDocument.dataRepresentation()?.write(to: URL(string: outputSavePanel!)!)) != nil)
  233. }
  234. if success {
  235. if savePanelAccessoryViewController.needOpen {
  236. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { document, open, error in
  237. }
  238. } else {
  239. NSWorkspace.shared.activateFileViewerSelecting([NSURL(fileURLWithPath: outputSavePanel!) as URL])
  240. }
  241. } else {
  242. let alert = NSAlert.init()
  243. alert.alertStyle = .critical
  244. alert.messageText = "\(String(describing: files.first?.filePath.lastPathComponent)) + \(NSLocalizedString("Failed to merge!", comment: ""))"
  245. alert.runModal()
  246. }
  247. }
  248. }
  249. }
  250. }
  251. // }
  252. }
  253. }
  254. func fetchAllOfChildren(_ aOutline: PDFOutline, containerArray aMArray: inout [PDFOutline]) {
  255. if !aMArray.contains(aOutline) {
  256. aMArray.append(aOutline)
  257. }
  258. for i in 0..<aOutline.numberOfChildren {
  259. if let childOutline = aOutline.child(at: i) {
  260. aMArray.append(childOutline)
  261. fetchAllOfChildren(childOutline, containerArray: &aMArray)
  262. }
  263. }
  264. }
  265. func handleReDraw() {
  266. if mergeView.originalSizeButton.state == .on {
  267. } else {
  268. let size = self.mergeView.newPageSize
  269. if size.width < 0 {
  270. return
  271. }
  272. var pagesArray: [PDFPage] = []
  273. let pageCount = self.oldPDFDocument.pageCount
  274. for i in 0..<pageCount {
  275. pagesArray.append(self.oldPDFDocument.page(at: 0)!)
  276. self.oldPDFDocument.removePage(at: 0)
  277. }
  278. for i in 0..<pageCount {
  279. let page: KMMergePDFPage = KMMergePDFPage.init()
  280. page.setBounds(CGRectMake(0, 0, size.width, size.height), for: .mediaBox)
  281. page.drawingPage = pagesArray[i]
  282. self.oldPDFDocument.insert(page, at: i)
  283. }
  284. if self.oldPDFDocument.outlineRoot != nil {
  285. let childCount = self.oldPDFDocument.outlineRoot?.numberOfChildren
  286. var outlineArray: [PDFOutline] = []
  287. for i in 0..<childCount! {
  288. outlineArray.append((self.oldPDFDocument.outlineRoot?.child(at: i))!)
  289. }
  290. for outline in outlineArray {
  291. outline.removeFromParent()
  292. }
  293. }
  294. }
  295. }
  296. }
  297. class KMMergePDFPage: PDFPage {
  298. var drawingPage: PDFPage?
  299. override func draw(with box: PDFDisplayBox, to context: CGContext) {
  300. super.draw(with: box, to: context)
  301. let pageSize = self.bounds(for: .cropBox).size
  302. self.drawPage(with: context, page: self.drawingPage!, pageSize: pageSize)
  303. }
  304. func drawPage(with context: CGContext, page: PDFPage, pageSize: CGSize) {
  305. var originalSize = page.bounds(for: .cropBox).size
  306. // 如果页面的旋转角度为90或者270,宽高交换
  307. if page.rotation % 180 != 0 {
  308. originalSize = CGSize(width: originalSize.height, height: originalSize.width)
  309. }
  310. let wRatio = pageSize.width / originalSize.width
  311. let hRatio = pageSize.height / originalSize.height
  312. let ratio = min(wRatio, hRatio)
  313. context.saveGState()
  314. let xTransform = (pageSize.width - originalSize.width * ratio) / 2
  315. let yTransform = (pageSize.height - originalSize.height * ratio) / 2
  316. context.translateBy(x: xTransform, y: yTransform)
  317. context.scaleBy(x: ratio, y: ratio)
  318. if #available(macOS 10.12, *) {
  319. page.draw(with: .cropBox, to: context)
  320. page.transformContext(for: .cropBox)
  321. } else {
  322. NSGraphicsContext.saveGraphicsState()
  323. NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
  324. page.draw(with: .cropBox)
  325. NSGraphicsContext.restoreGraphicsState()
  326. page.transformContext(for: .cropBox)
  327. }
  328. context.restoreGState()
  329. }
  330. }