KMPrintWindowController.swift 22 KB

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