KMMergeWindowController.swift 18 KB

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