KMMergeWindowController.swift 16 KB

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