KMPrintWindowController.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. //
  2. // KMPrintWindowController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2022/12/8.
  6. //
  7. import Cocoa
  8. import PDFKit
  9. typealias KMPrintWindowControllerPrintTypeChange = (_ controller: KMPrintWindowController, _ type: KMPrintModelType) -> Void
  10. class KMPrintWindowController: KMBaseWindowController, NetServiceBrowserDelegate {
  11. @IBOutlet weak var titleLabel: NSTextField!
  12. @IBOutlet weak var preview: KMPrintPreviewView!
  13. @IBOutlet weak var chooseView: KMPrintChooseView!
  14. @IBOutlet weak var settingView: KMPrintSettingView!
  15. @IBOutlet weak var bottomView: KMPrintBottomView!
  16. var tempPDFDocument: PDFDocument?
  17. var password: String = "" {
  18. didSet {
  19. self.preview.password = password
  20. self.presenter.password = password
  21. }
  22. }
  23. var isPrintPreView: Bool = true {
  24. didSet {
  25. self.preview.isPrintPreView = isPrintPreView
  26. }
  27. }
  28. var changeTypeAction: KMPrintWindowControllerPrintTypeChange?
  29. var chooseData: KMPrintModel = KMPrintModel() {
  30. didSet {
  31. self.reloadData()
  32. }
  33. }
  34. var inputType: DataNavigationViewButtonActionType?
  35. var presenter: KMPrintPresenter = KMPrintPresenter()
  36. var printType: KMPrintModelType = .size {
  37. didSet {
  38. self.chooseData.page.operation.type = printType
  39. self.reloadData()
  40. }
  41. }
  42. var inputPageRange: KMPrintPageRange = KMPrintPageRange() {
  43. didSet {
  44. self.chooseView.inputPageRange = inputPageRange
  45. self.preview.toPageIndex(UInt(inputPageRange.selectPages.first ?? 0))
  46. }
  47. }
  48. // var inputData: URL? {
  49. // didSet {
  50. // let pdfDocument = CPDFDocument.init(url: inputData)
  51. // self.chooseView.inputData = inputData
  52. //
  53. // if pdfDocument != nil {
  54. // self.preview.pdfDocument = pdfDocument
  55. // self.pdfDocument = pdfDocument
  56. //
  57. // self.presenter.initPresenter(delegate: self, data: self.chooseData, document: pdfDocument!)
  58. // }
  59. // }
  60. // }
  61. var inputDocument: CPDFDocument? {
  62. didSet {
  63. pdfDocument = inputDocument
  64. password = inputDocument?.password ?? ""
  65. // self.chooseView.inputData = URL(string: "")
  66. if pdfDocument != nil {
  67. self.preview.pdfDocument = PDFDocument(url: pdfDocument!.documentURL)
  68. self.presenter.initPresenter(delegate: self, data: self.chooseData, document: pdfDocument!)
  69. }
  70. }
  71. }
  72. deinit {
  73. KMPrint("KMImageToPDFWindowController 释放")
  74. }
  75. override func windowDidLoad() {
  76. super.windowDidLoad()
  77. // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
  78. self.window?.title = "Image to PDF"
  79. self.setup()
  80. self.reloadData()
  81. }
  82. override func interfaceThemeDidChanged(_ appearance: NSAppearance.Name) {
  83. if appearance == .darkAqua {
  84. self.window?.contentView?.layer?.backgroundColor = NSColor.init(hex: "#26282B").cgColor
  85. } else {
  86. self.window?.contentView?.layer?.backgroundColor = NSColor.white.cgColor
  87. }
  88. }
  89. func setup() {
  90. self.window?.contentView?.wantsLayer = true
  91. self.interfaceThemeDidChanged(self.window?.appearance?.name ?? .aqua)
  92. self.titleLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  93. self.titleLabel.textColor = KMAppearance.Layout.h0Color()
  94. self.titleLabel.stringValue = NSLocalizedString("Print", comment: "")
  95. self.bottomView.delegate = self
  96. self.chooseView.delegate = self
  97. self.settingView.pageSettingChange = { [unowned self] view, model in
  98. self.chooseData = model
  99. self.presenter.printData = model
  100. }
  101. self.settingView.printSettingChange = { [unowned self] view, model in
  102. self.chooseData = model
  103. self.presenter.printData = model
  104. }
  105. }
  106. func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) {
  107. KMPrint(service)
  108. // output: <NSNetService 0x1c0228960> local. _ipp._tcp. RICOH imagio MP C3302 [002673499B5F] -1
  109. }
  110. func reloadData() {
  111. guard let bottomView = bottomView else { return }
  112. self.preview.model = chooseData
  113. self.settingView.printModel = chooseData
  114. self.bottomView.type = printType
  115. self.settingView.type = printType
  116. }
  117. //MARK: 打开文件
  118. /**
  119. @abstract 选取文件跳转打印界面
  120. @param window 文档地址
  121. @param pageRange 打印范围
  122. */
  123. static func openFiles(window: NSWindow, pageRange: KMPrintPageRange = KMPrintPageRange()) {
  124. // KMBatchProcessingView.openfiles(window: window) { openPanel in
  125. //// openPanel.title = "选择图片"
  126. // openPanel.canChooseDirectories = false
  127. // openPanel.canChooseFiles = true
  128. // openPanel.allowsMultipleSelection = false
  129. // openPanel.allowedFileTypes = KMOCRModel.supportedTypes()
  130. // } completion: { (panel ,data) in
  131. // if data.count != 0 {
  132. // KMPrintWindowController.openFile(inputData: data.first, inputPageRange: pageRange)
  133. // }
  134. // }
  135. }
  136. /**
  137. @abstract 打印界面显示
  138. @param inputData 传入URL
  139. @param inputType 入口类型
  140. @param inputPageRange 页面范围,默认全部
  141. */
  142. static func openFile(inputData: URL?, inputType: DataNavigationViewButtonActionType = .Print, inputPageRange: KMPrintPageRange = KMPrintPageRange()) {
  143. KMPrintWindowController.showPrintWindowControll(inputData: inputData, inputDocument: nil, inputType: inputType,inputPageRange: inputPageRange)
  144. }
  145. /**
  146. @abstract 打印界面显示
  147. @param inputDocument 传入document
  148. @param inputType 入口类型 默认print
  149. @param inputPageRange 页面范围,默认全部
  150. */
  151. static func openDocument(inputDocument: CPDFDocument?, inputType: DataNavigationViewButtonActionType = .Print, inputPageRange: KMPrintPageRange) {
  152. KMPrintWindowController.showPrintWindowControll(inputData: nil, inputDocument: inputDocument, inputType: inputType,inputPageRange: inputPageRange)
  153. }
  154. static func showNewPrintWindowControll(inputDocument: CPDFDocument?, inputType: DataNavigationViewButtonActionType = .Print, inputPageRange: KMPrintPageRange, printType: KMPrintModelType = .size) {
  155. //订阅
  156. if !IAPProductsManager.default().isAvailableAllFunction(){
  157. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  158. return
  159. }
  160. if inputDocument != nil {
  161. guard let pdfDocument = PDFDocument(url: inputDocument!.documentURL) else { return }
  162. }
  163. let printWindowController: KMPrintWindowController = KMPrintWindowController.init(windowNibName: "KMPrintWindowController")
  164. printWindowController.printType = printType
  165. switch printType {
  166. case .size:
  167. printWindowController.window?.contentMinSize = CGSize(width: 600, height: 500)
  168. printWindowController.window?.contentMaxSize = CGSize(width: 600, height: 500)
  169. printWindowController.window?.setFrame(NSRect(x: 0, y: 0, width: 600, height: 500), display: true)
  170. case .poster:
  171. printWindowController.window?.contentMinSize = CGSize(width: 800, height: 500)
  172. printWindowController.window?.contentMaxSize = CGSize(width: 800, height: 500)
  173. printWindowController.window?.setFrame(NSRect(x: 0, y: 0, width: 800, height: 500), display: true)
  174. case .multipage:
  175. printWindowController.window?.contentMinSize = CGSize(width: 800, height: 700)
  176. printWindowController.window?.contentMaxSize = CGSize(width: 800, height: 700)
  177. printWindowController.window?.setFrame(NSRect(x: 0, y: 0, width: 800, height: 700), display: true)
  178. case .pamphlet:
  179. printWindowController.window?.contentMinSize = CGSize(width: 800, height: 600)
  180. printWindowController.window?.contentMaxSize = CGSize(width: 800, height: 600)
  181. printWindowController.window?.setFrame(NSRect(x: 0, y: 0, width: 800, height: 600), display: true)
  182. default:
  183. break
  184. }
  185. NSWindow.currentWindow().beginSheet(printWindowController.window!)
  186. if inputDocument != nil {
  187. printWindowController.inputDocument = inputDocument
  188. }
  189. printWindowController.inputType = inputType
  190. printWindowController.inputPageRange = inputPageRange
  191. }
  192. static func showPrintWindowControll(inputData: URL?, inputDocument: AnyObject?, inputType: DataNavigationViewButtonActionType = .Print, inputPageRange: KMPrintPageRange) {
  193. var document: PDFDocument?
  194. let filePath = KMPrintPresenter.fetchSaveFilePath("")
  195. var password: String = ""
  196. if inputDocument != nil {
  197. // if inputDocument != nil {
  198. if inputDocument is CPDFDocument {
  199. let success = inputDocument?.writeDecrypt(to: URL(fileURLWithPath: filePath))
  200. password = inputDocument?.password ?? ""
  201. if success != nil {
  202. document = PDFDocument(url: URL(fileURLWithPath: filePath))!
  203. }
  204. } else if inputDocument is PDFDocument {
  205. document = inputDocument as? PDFDocument
  206. }
  207. }
  208. if inputData != nil {
  209. document = PDFDocument.init(url: inputData!)!
  210. }
  211. //页面选取
  212. if ((inputPageRange.type == .currentPage ||
  213. inputPageRange.type == .custom) &&
  214. inputPageRange.selectPages.count != 0) {
  215. let printPresent = KMPrintPresenter()
  216. let filePath = KMPrintPresenter.fetchSaveFilePath("")
  217. let paperSize = (document?.page(at: 0)?.bounds(for: .cropBox).size) ?? CGSizeZero
  218. let context: CGContext = printPresent.createContext(filePath, paperSize)
  219. var pages: [PDFPage] = []
  220. for index in inputPageRange.selectPages {
  221. let page = document?.page(at: index)
  222. if page != nil {
  223. pages.append(page!)
  224. }
  225. }
  226. for drawPage in pages {
  227. context.beginPDFPage(nil)
  228. context.saveGState()
  229. var pageSize = drawPage.bounds(for: .cropBox).size
  230. if (drawPage.rotation == 90 || drawPage.rotation == 270) {
  231. let height = pageSize.height
  232. pageSize.height = pageSize.width
  233. pageSize.width = height
  234. }
  235. // 检查要自适应的大小是否大于参考矩形的大小
  236. let maxWidth = paperSize.width
  237. let maxHeight = paperSize.height
  238. var scaledSize = pageSize
  239. var ratio = 1.0
  240. if pageSize.width > maxWidth || pageSize.height > maxHeight {
  241. let widthRatio = maxWidth / pageSize.width
  242. let heightRatio = maxHeight / pageSize.height
  243. ratio = min(widthRatio, heightRatio)
  244. scaledSize = CGSize(width: pageSize.width * ratio, height: pageSize.height * ratio)
  245. }
  246. // 计算自适应后的矩形大小和位置
  247. let scaledWidth = scaledSize.width
  248. let scaledHeight = scaledSize.height
  249. let scaledRect = CGRect(x: (paperSize.width - scaledWidth) / 2, y: (paperSize.height - scaledHeight) / 2, width: scaledWidth, height: scaledHeight)
  250. context.translateBy(x: scaledRect.origin.x, y: scaledRect.origin.y)
  251. context.scaleBy(x: ratio, y: ratio)
  252. drawPage.draw(with: .cropBox, to: context)
  253. context.restoreGState()
  254. context.endPDFPage()
  255. }
  256. context.closePDF()
  257. document = PDFDocument(url: URL(fileURLWithPath: filePath))!
  258. }
  259. if document != nil {
  260. if inputDocument != nil {
  261. document?.unlock(withPassword: password)
  262. }
  263. if (inputDocument!.allowsPrinting == false) {
  264. KMPasswordInputWindow.openWindow(window: NSApp.mainWindow!, type: .owner, url: (inputDocument!.documentURL)!) { result , password in
  265. if (result == .cancel) {
  266. return
  267. }
  268. document!.unlock(withPassword: password!)
  269. KMPrintWindowController.openPrintView(document: document)
  270. }
  271. return
  272. } else {
  273. KMPrintWindowController.openPrintView(document: document)
  274. }
  275. }
  276. }
  277. static func openPrintView(document: PDFDocument?) {
  278. if (document != nil &&
  279. document!.allowsPrinting == true) {
  280. let printInfo = NSPrintInfo.shared
  281. var printOperation: NSPrintOperation = NSPrintOperation()
  282. let scalingMode: PDFPrintScalingMode = .pageScaleToFit
  283. if document!.responds(to: NSSelectorFromString("printOperationForPrintInfo:scalingMode:autoRotate:")) {
  284. printOperation = document!.printOperation(for: printInfo, scalingMode: scalingMode, autoRotate: false)!
  285. }
  286. printOperation.printPanel.options = [.showsPreview, .showsCopies, .showsOrientation, .showsPageRange, .showsPaperSize, .showsCopies, .showsPrintSelection, .showsScaling]
  287. let controller = KMPrintAccessoryController_OC(nibName: "KMPrintAccessoryController_OC", bundle: nil)
  288. printOperation.printPanel.addAccessoryController(controller)
  289. printOperation.runModal(for: NSApplication.shared.mainWindow!, delegate: self, didRun: nil, contextInfo: nil)
  290. }
  291. }
  292. }
  293. //MARK: - Print
  294. extension KMPrintWindowController {
  295. static func printImage(image: NSImage) {
  296. let pdfDocument : PDFDocument = PDFDocument()
  297. let newpage : PDFPage = PDFPage(image: image)!
  298. pdfDocument.insert(newpage, at: 0)
  299. KMPrintWindowController.showPrintWindowControll(inputData: nil, inputDocument: pdfDocument, inputPageRange: KMPrintPageRange())
  300. }
  301. static func cpdf_printImage(image: NSImage) {
  302. let pdfDocument : PDFDocument = PDFDocument()
  303. let newpage : PDFPage = PDFPage(image: image)!
  304. pdfDocument.insert(newpage, at: 0)
  305. KMPrintWindowController.openPrintView(document: pdfDocument)
  306. }
  307. }
  308. extension NetService {
  309. func textRecordField(field: String) -> String? {
  310. guard
  311. let data = self.txtRecordData(),
  312. let field = NetService.dictionary(fromTXTRecord: data)[field]
  313. else { return nil }
  314. return String(data: field, encoding: String.Encoding.utf8)
  315. }
  316. }
  317. extension KMPrintWindowController: KMPrintBottomViewDelegate {
  318. func savePDFAction() {
  319. KMPrint("保存PDF")
  320. // guard let url = self.presenter.printData.url else { return }
  321. guard let document = self.tempPDFDocument else { return }
  322. // guard let url = self.tempPDFDocument?.documentURL else { return }
  323. // let document = CPDFDocument(url: url)
  324. // NSPanel.savePanel_pdf_success(self.window!, document: document) { result in
  325. // NSWorkspace.shared.selectFile(result.path, inFileViewerRootedAtPath: "")
  326. // }
  327. //
  328. let savePanel = NSSavePanel()
  329. savePanel.allowedFileTypes = ["pdf"]
  330. savePanel.beginSheetModal(for: NSWindow.currentWindow(), completionHandler: { result in
  331. if result != .OK {
  332. // completion(result, nil)
  333. } else {
  334. document.write(to: savePanel.url!)
  335. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  336. // completion(result, success ? savePanel.url! : nil)
  337. }
  338. })
  339. }
  340. func printerAction() {
  341. KMPrint("调用打印机打印")
  342. guard let url = self.presenter.printData.url else { return }
  343. let document = PDFDocument.init(url: url)
  344. let printInfo = NSPrintInfo.shared
  345. let printOperation: NSPrintOperation = document!.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true)!
  346. let printPanel = printOperation.printPanel
  347. printPanel.options = [.showsOrientation, .showsPageRange, .showsPaperSize, .showsScaling, .showsPreview]
  348. printOperation.runModal(for: self.window!, delegate: self, didRun: nil, contextInfo: nil)
  349. }
  350. func cancelAction() {
  351. KMPrint("cancel")
  352. NSApp.mainWindow!.endSheet(self.window!)
  353. self.close()
  354. // self.window?.orderOut(self)
  355. }
  356. func printAction() {
  357. KMPrint("打印机直接打印")
  358. // guard let url = self.presenter.printData.url else { return }
  359. // let document = PDFDocument.init(url: url)
  360. guard let document = self.tempPDFDocument else { return }
  361. let printInfo = NSPrintInfo.shared
  362. let printOperation: NSPrintOperation = document.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true)!
  363. printOperation.showsPrintPanel = true //是否弹出打印机设置界面
  364. printOperation.run()
  365. }
  366. func posterAction() {
  367. self.changeTypeAction?(self, .poster)
  368. self.cancelAction()
  369. KMPrintWindowController.showNewPrintWindowControll(inputDocument: self.pdfDocument, inputPageRange: KMPrintPageRange(), printType: .poster)
  370. }
  371. func multipageAction() {
  372. self.changeTypeAction?(self, .multipage)
  373. self.cancelAction()
  374. KMPrintWindowController.showNewPrintWindowControll(inputDocument: self.pdfDocument, inputPageRange: KMPrintPageRange(), printType: .multipage)
  375. }
  376. func bookletAction() {
  377. self.changeTypeAction?(self, .pamphlet)
  378. self.cancelAction()
  379. KMPrintWindowController.showNewPrintWindowControll(inputDocument: self.pdfDocument, inputPageRange: KMPrintPageRange(), printType: .pamphlet)
  380. }
  381. }
  382. extension KMPrintWindowController: KMPrintChooseViewDelegate {
  383. func showData(sender: Any, data: KMPrintModel) {
  384. self.chooseData = data
  385. }
  386. func printerChange(sender: Any, data: KMPrintModel) {
  387. }
  388. func pageSetChange(sender: Any, data: KMPrintModel) {
  389. self.chooseData = data
  390. self.presenter.reloadData()
  391. }
  392. func pageNumberChange(sender: Any, data: KMPrintModel) {
  393. }
  394. func blackAndWhiteChange(sender: Any, data: KMPrintModel) {
  395. }
  396. func printOnBothSidesChange(sender: Any, data: KMPrintModel) {
  397. }
  398. func pageRangeChange(sender: Any, data: KMPrintModel) {
  399. self.chooseData = data
  400. self.presenter.reloadData()
  401. }
  402. func printDirectionChange(sender: Any, data: KMPrintModel) {
  403. self.chooseData = data
  404. self.presenter.reloadData()
  405. }
  406. func printContentChange(sender: Any, data: KMPrintModel) {
  407. self.chooseData = data
  408. self.presenter.reloadData()
  409. }
  410. func printReverseChange(sender: Any, data: KMPrintModel) {
  411. self.chooseData = data
  412. self.presenter.reloadData()
  413. }
  414. func printDealModelChange(sender: Any, data: KMPrintModel) {
  415. self.chooseData = data
  416. self.presenter.reloadData()
  417. }
  418. }
  419. extension KMPrintWindowController: KMPrintPresenterDeleage {
  420. func showData(presenter: KMPrintPresenter, document: PDFDocument) {
  421. self.tempPDFDocument = document
  422. self.preview.model = self.chooseData
  423. if isPrintPreView && self.preview.model?.page.operation.type == .poster {
  424. // self.preview.pdfDocument = pdfDocument
  425. } else {
  426. self.preview.pdfDocument = document
  427. }
  428. self.preview.updatePosterPreView()
  429. }
  430. }