KMPrintWindowController.swift 14 KB

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