KMPrintWindowController.swift 16 KB

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