KMMergeWindowController.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. var size = 0.0
  131. for file in files {
  132. size = size + file.fileSize
  133. }
  134. if !IAPProductsManager.default().isAvailableAllFunction() && (files.count > 2 || size > 20 * 1024 * 1024) {
  135. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  136. return
  137. }
  138. var filesCount = 1
  139. if self.oriDucumentUrl != nil {
  140. filesCount = 0
  141. }
  142. if files.count <= filesCount {
  143. let alert = NSAlert.init()
  144. alert.alertStyle = .critical
  145. alert.messageText = NSLocalizedString("To start merging, please select at least 2 files.", comment: "")
  146. alert.runModal()
  147. return
  148. }
  149. // _isSuccessfully = NO;
  150. // [self.nCancelVC setEnabled:NO];
  151. // self.canMerge = NO;
  152. //
  153. var rootPDFOutlineArray: [PDFOutline] = []
  154. var allPage = true //只有是全部才支持大纲的合并
  155. for file in files {
  156. if file.fetchSelectPages().count == 0 {
  157. let alert = NSAlert.init()
  158. alert.alertStyle = .critical
  159. alert.messageText = "\(file.filePath.lastPathComponent) + \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  160. alert.runModal()
  161. return
  162. }
  163. allPage = file.bAllPage
  164. let tDocument = PDFDocument(url: NSURL(fileURLWithPath: file.filePath) as URL)!
  165. var outlineArray: [PDFOutline] = []
  166. // if file.isLocked {
  167. tDocument.unlock(withPassword: file.password)
  168. // }
  169. if tDocument.outlineRoot != nil {
  170. rootPDFOutlineArray.append((tDocument.outlineRoot)!)
  171. self.fetchAllOfChildren((tDocument.outlineRoot)!, containerArray: &outlineArray)
  172. outlineArray.removeObject((tDocument.outlineRoot)!)
  173. } else {
  174. let rootOutline = PDFOutline.init()
  175. tDocument.outlineRoot = rootOutline
  176. if tDocument.outlineRoot != nil {
  177. rootPDFOutlineArray.append(tDocument.outlineRoot!)
  178. }
  179. }
  180. for number in file.fetchSelectPages() {
  181. let page = tDocument.page(at: number - 1)
  182. // if pageIndex != nil {
  183. // self.oldPDFDocument.insert(page!, at: pageIndex!)
  184. // pageIndex = pageIndex! + 1
  185. // } else {
  186. self.oldPDFDocument.insert(page!, at: self.oldPDFDocument.pageCount)
  187. // }
  188. // self.insertIndexSet.addIndex:(self.pdfDocument.pageCount - 1)
  189. }
  190. }
  191. let fileName = (files.first?.filePath.deletingPathExtension.lastPathComponent ?? "") + "_Merged"
  192. DispatchQueue.main.async {
  193. self.oldPDFDocument.outlineRoot = PDFOutline.init()
  194. // if allPage {
  195. var insertIndex = 0
  196. for i in 0..<rootPDFOutlineArray.count {
  197. let rootOutline = rootPDFOutlineArray[i]
  198. for j in 0..<rootOutline.numberOfChildren {
  199. self.oldPDFDocument.outlineRoot?.insertChild(rootOutline.child(at: j)!, at: insertIndex)
  200. insertIndex = insertIndex + 1
  201. }
  202. }
  203. self.handleReDraw()
  204. if self.oriDucumentUrl != nil {
  205. let newPath = self.oldPDFDocument.documentURL!.path
  206. var options: [PDFDocumentWriteOption : Any] = [:]
  207. var success = false
  208. let password = self.password
  209. let pdf = self.oldPDFDocument
  210. if pdf.isEncrypted {
  211. options.updateValue(password, forKey: .userPasswordOption)
  212. options.updateValue(password, forKey: .ownerPasswordOption)
  213. success = pdf.write(toFile: newPath, withOptions: options)
  214. } else {
  215. success = pdf.write(toFile: newPath)
  216. }
  217. // var success = self.oldPDFDocument.write(toFile: self.oldPDFDocument.documentURL!.path)
  218. if success {
  219. self.mergeAction?(self, self.oldPDFDocument.documentURL!.path)
  220. } else {
  221. print("合并失败")
  222. }
  223. } else {
  224. let savePanelAccessoryViewController = KMSavePanelAccessoryController.init()
  225. let savePanel = NSSavePanel()
  226. savePanel.nameFieldStringValue = fileName
  227. savePanel.allowedFileTypes = ["pdf"]
  228. savePanel.accessoryView = savePanelAccessoryViewController.view
  229. // self.savePanelAccessoryViewController = savePanelAccessoryViewController;
  230. savePanel.beginSheetModal(for: self.window!) { result in
  231. if result == .OK {
  232. self.cancelAction?()
  233. var outputSavePanel = savePanel.url?.path
  234. DispatchQueue.main.async {
  235. var success = self.oldPDFDocument.write(toFile: outputSavePanel!)
  236. if !success {
  237. success = ((try?self.oldPDFDocument.dataRepresentation()?.write(to: URL(string: outputSavePanel!)!)) != nil)
  238. }
  239. if success {
  240. if savePanelAccessoryViewController.needOpen {
  241. NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { document, open, error in
  242. }
  243. } else {
  244. NSWorkspace.shared.activateFileViewerSelecting([NSURL(fileURLWithPath: outputSavePanel!) as URL])
  245. }
  246. } else {
  247. let alert = NSAlert.init()
  248. alert.alertStyle = .critical
  249. alert.messageText = "\(String(describing: files.first?.filePath.lastPathComponent)) + \(NSLocalizedString("Failed to merge!", comment: ""))"
  250. alert.runModal()
  251. }
  252. }
  253. }
  254. }
  255. }
  256. // }
  257. }
  258. }
  259. func fetchAllOfChildren(_ aOutline: PDFOutline, containerArray aMArray: inout [PDFOutline]) {
  260. if !aMArray.contains(aOutline) {
  261. aMArray.append(aOutline)
  262. }
  263. for i in 0..<aOutline.numberOfChildren {
  264. if let childOutline = aOutline.child(at: i) {
  265. aMArray.append(childOutline)
  266. fetchAllOfChildren(childOutline, containerArray: &aMArray)
  267. }
  268. }
  269. }
  270. func handleReDraw() {
  271. if mergeView.originalSizeButton.state == .on {
  272. } else {
  273. let size = self.mergeView.newPageSize
  274. if size.width < 0 {
  275. return
  276. }
  277. var pagesArray: [PDFPage] = []
  278. let pageCount = self.oldPDFDocument.pageCount
  279. for i in 0..<pageCount {
  280. pagesArray.append(self.oldPDFDocument.page(at: 0)!)
  281. self.oldPDFDocument.removePage(at: 0)
  282. }
  283. for i in 0..<pageCount {
  284. let page: KMMergePDFPage = KMMergePDFPage.init()
  285. page.setBounds(CGRectMake(0, 0, size.width, size.height), for: .mediaBox)
  286. page.drawingPage = pagesArray[i]
  287. self.oldPDFDocument.insert(page, at: i)
  288. }
  289. if self.oldPDFDocument.outlineRoot != nil {
  290. let childCount = self.oldPDFDocument.outlineRoot?.numberOfChildren
  291. var outlineArray: [PDFOutline] = []
  292. for i in 0..<childCount! {
  293. outlineArray.append((self.oldPDFDocument.outlineRoot?.child(at: i))!)
  294. }
  295. for outline in outlineArray {
  296. outline.removeFromParent()
  297. }
  298. }
  299. }
  300. }
  301. }
  302. class KMMergePDFPage: PDFPage {
  303. var drawingPage: PDFPage?
  304. override func draw(with box: PDFDisplayBox, to context: CGContext) {
  305. super.draw(with: box, to: context)
  306. let pageSize = self.bounds(for: .cropBox).size
  307. self.drawPage(with: context, page: self.drawingPage!, pageSize: pageSize)
  308. }
  309. func drawPage(with context: CGContext, page: PDFPage, pageSize: CGSize) {
  310. var originalSize = page.bounds(for: .cropBox).size
  311. // 如果页面的旋转角度为90或者270,宽高交换
  312. if page.rotation % 180 != 0 {
  313. originalSize = CGSize(width: originalSize.height, height: originalSize.width)
  314. }
  315. let wRatio = pageSize.width / originalSize.width
  316. let hRatio = pageSize.height / originalSize.height
  317. let ratio = min(wRatio, hRatio)
  318. context.saveGState()
  319. let xTransform = (pageSize.width - originalSize.width * ratio) / 2
  320. let yTransform = (pageSize.height - originalSize.height * ratio) / 2
  321. context.translateBy(x: xTransform, y: yTransform)
  322. context.scaleBy(x: ratio, y: ratio)
  323. if #available(macOS 10.12, *) {
  324. page.draw(with: .cropBox, to: context)
  325. page.transformContext(for: .cropBox)
  326. } else {
  327. NSGraphicsContext.saveGraphicsState()
  328. NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
  329. page.draw(with: .cropBox)
  330. NSGraphicsContext.restoreGraphicsState()
  331. page.transformContext(for: .cropBox)
  332. }
  333. context.restoreGState()
  334. }
  335. }