KMMergeWindowController.swift 18 KB

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