KMMergeWindowController.swift 22 KB

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