KMMergeWindowController.swift 18 KB

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