KMMergeWindowController.swift 20 KB

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