KMPrintWindowController.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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(named: "#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 = { [weak self] view, model in
  102. self?.chooseData = model
  103. self?.presenter.printData = model
  104. }
  105. self.settingView.printSettingChange = { [weak 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. var filePath = ""
  230. var password: String = ""
  231. if inputDocument != nil {
  232. filePath = KMPrintPresenter.fetchSaveFilePath(fileName: inputDocument?.documentURL?.path.lastPathComponent ?? "text.pdf")
  233. // if inputDocument != nil {
  234. if inputDocument is CPDFDocument {
  235. let success = inputDocument?.writeDecrypt(to: URL(fileURLWithPath: filePath))
  236. password = inputDocument?.password ?? ""
  237. if success != nil {
  238. document = PDFDocument(url: URL(fileURLWithPath: filePath))!
  239. }
  240. } else if inputDocument is PDFDocument {
  241. document = inputDocument as? PDFDocument
  242. }
  243. }
  244. if inputData != nil {
  245. filePath = KMPrintPresenter.fetchSaveFilePath(fileName: inputData?.path.lastPathComponent ?? "text.pdf")
  246. document = PDFDocument.init(url: inputData!)!
  247. }
  248. if document != nil {
  249. //页面选取
  250. if ((inputPageRange.type == .currentPage ||
  251. inputPageRange.type == .custom) &&
  252. inputPageRange.selectPages.count != 0) {
  253. let printPresent = KMPrintPresenter()
  254. // let filePath = KMPrintPresenter.fetchSaveFilePath("")
  255. let paperSize = (document?.page(at: 0)?.bounds(for: .cropBox).size) ?? .zero
  256. let context: CGContext = printPresent.createContext(filePath, paperSize)
  257. var pages: [PDFPage] = []
  258. for index in inputPageRange.selectPages {
  259. let page = document?.page(at: index)
  260. if page != nil {
  261. pages.append(page!)
  262. }
  263. }
  264. for drawPage in pages {
  265. context.beginPDFPage(nil)
  266. context.saveGState()
  267. var pageSize = drawPage.bounds(for: .cropBox).size
  268. if (drawPage.rotation == 90 || drawPage.rotation == 270) {
  269. let height = pageSize.height
  270. pageSize.height = pageSize.width
  271. pageSize.width = height
  272. }
  273. // 检查要自适应的大小是否大于参考矩形的大小
  274. let maxWidth = paperSize.width
  275. let maxHeight = paperSize.height
  276. var scaledSize = pageSize
  277. var ratio = 1.0
  278. if pageSize.width > maxWidth || pageSize.height > maxHeight {
  279. let widthRatio = maxWidth / pageSize.width
  280. let heightRatio = maxHeight / pageSize.height
  281. ratio = min(widthRatio, heightRatio)
  282. scaledSize = CGSize(width: pageSize.width * ratio, height: pageSize.height * ratio)
  283. }
  284. // 计算自适应后的矩形大小和位置
  285. let scaledWidth = scaledSize.width
  286. let scaledHeight = scaledSize.height
  287. let scaledRect = CGRect(x: (paperSize.width - scaledWidth) / 2, y: (paperSize.height - scaledHeight) / 2, width: scaledWidth, height: scaledHeight)
  288. context.translateBy(x: scaledRect.origin.x, y: scaledRect.origin.y)
  289. context.scaleBy(x: ratio, y: ratio)
  290. drawPage.draw(with: .cropBox, to: context)
  291. context.restoreGState()
  292. context.endPDFPage()
  293. }
  294. context.closePDF()
  295. document = PDFDocument(url: URL(fileURLWithPath: filePath))!
  296. }
  297. if inputDocument != nil {
  298. document?.unlock(withPassword: password)
  299. }
  300. if (inputDocument!.allowsPrinting == false) {
  301. KMPasswordInputWindow.openWindow(window: NSApp.mainWindow!, type: .owner, url: (inputDocument!.documentURL)!) { result , resultPassword in
  302. if (result == .cancel) {
  303. return
  304. }
  305. document!.unlock(withPassword: resultPassword ?? "")
  306. KMPrintWindowController.openPrintView(document: document)
  307. }
  308. return
  309. } else {
  310. KMPrintWindowController.openPrintView(document: document)
  311. }
  312. }
  313. }
  314. static func openPrintView(document: PDFDocument?) {
  315. guard let document = document else { return }
  316. if (document.allowsPrinting == true) {
  317. let printInfo = NSPrintInfo.shared
  318. let scalingMode: PDFPrintScalingMode = .pageScaleToFit
  319. if document.responds(to: NSSelectorFromString("printOperationForPrintInfo:scalingMode:autoRotate:")) {
  320. if let printOperation = document.printOperation(for: printInfo, scalingMode: scalingMode, autoRotate: false) {
  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: NSWindow.currentWindow(), delegate: self, didRun: nil, contextInfo: nil)
  325. }
  326. } else {
  327. self.openPrinter(document: document)
  328. }
  329. }
  330. }
  331. static func openPrinter(document: PDFDocument) {
  332. let printInfo = NSPrintInfo.shared
  333. if let printOperation: NSPrintOperation = document.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true) {
  334. printOperation.showsPrintPanel = true //是否弹出打印机设置界面
  335. printOperation.run()
  336. }
  337. }
  338. }
  339. //MARK: - Print
  340. extension KMPrintWindowController {
  341. static func printImage(image: NSImage) {
  342. let pdfDocument : PDFDocument = PDFDocument()
  343. let newpage : PDFPage = PDFPage(image: image)!
  344. pdfDocument.insert(newpage, at: 0)
  345. KMPrintWindowController.showPrintWindowControll(inputData: nil, inputDocument: pdfDocument, inputPageRange: KMPrintPageRange())
  346. }
  347. static func cpdf_printImage(image: NSImage) {
  348. let pdfDocument : PDFDocument = PDFDocument()
  349. let newpage : PDFPage = PDFPage(image: image)!
  350. pdfDocument.insert(newpage, at: 0)
  351. KMPrintWindowController.openPrintView(document: pdfDocument)
  352. }
  353. }
  354. extension NetService {
  355. func textRecordField(field: String) -> String? {
  356. guard
  357. let data = self.txtRecordData(),
  358. let field = NetService.dictionary(fromTXTRecord: data)[field]
  359. else { return nil }
  360. return String(data: field, encoding: String.Encoding.utf8)
  361. }
  362. }
  363. extension KMPrintWindowController: KMPrintBottomViewDelegate {
  364. func savePDFAction() {
  365. KMPrint("保存PDF")
  366. // guard let url = self.presenter.printData.url else { return }
  367. guard let document = self.tempPDFDocument else { return }
  368. // guard let url = self.tempPDFDocument?.documentURL else { return }
  369. // let document = CPDFDocument(url: url)
  370. // NSPanel.savePanel_pdf_success(self.window!, document: document) { result in
  371. // NSWorkspace.shared.selectFile(result.path, inFileViewerRootedAtPath: "")
  372. // }
  373. //
  374. let savePanel = NSSavePanel()
  375. savePanel.allowedFileTypes = ["pdf"]
  376. savePanel.beginSheetModal(for: NSWindow.currentWindow(), completionHandler: { result in
  377. if result != .OK {
  378. // completion(result, nil)
  379. } else {
  380. document.write(to: savePanel.url!)
  381. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  382. // completion(result, success ? savePanel.url! : nil)
  383. }
  384. })
  385. }
  386. func printerAction() {
  387. KMPrint("调用打印机打印")
  388. guard let url = self.presenter.printData.url else { return }
  389. let document = PDFDocument.init(url: url)
  390. guard let document = document else { return }
  391. let printInfo = NSPrintInfo.shared
  392. if let printOperation: NSPrintOperation = document.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true) {
  393. let printPanel = printOperation.printPanel
  394. printPanel.options = [.showsOrientation, .showsPageRange, .showsPaperSize, .showsScaling, .showsPreview]
  395. printOperation.runModal(for: self.window!, delegate: self, didRun: nil, contextInfo: nil)
  396. }
  397. }
  398. func cancelAction() {
  399. KMPrint("cancel")
  400. NSApp.mainWindow!.endSheet(self.window!)
  401. self.close()
  402. // self.window?.orderOut(self)
  403. }
  404. func printAction() {
  405. KMPrint("打印机直接打印")
  406. // guard let url = self.presenter.printData.url else { return }
  407. // let document = PDFDocument.init(url: url)
  408. guard let document = self.tempPDFDocument else { return }
  409. let printInfo = NSPrintInfo.shared
  410. if let printOperation: NSPrintOperation = document.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true) {
  411. printOperation.showsPrintPanel = true //是否弹出打印机设置界面
  412. printOperation.run()
  413. }
  414. }
  415. func posterAction() {
  416. self.changeTypeAction?(self, .poster)
  417. self.cancelAction()
  418. KMPrintWindowController.showNewPrintWindowControll(inputDocument: self.pdfDocument, inputPageRange: KMPrintPageRange(), printType: .poster)
  419. }
  420. func multipageAction() {
  421. self.changeTypeAction?(self, .multipage)
  422. self.cancelAction()
  423. KMPrintWindowController.showNewPrintWindowControll(inputDocument: self.pdfDocument, inputPageRange: KMPrintPageRange(), printType: .multipage)
  424. }
  425. func bookletAction() {
  426. self.changeTypeAction?(self, .pamphlet)
  427. self.cancelAction()
  428. KMPrintWindowController.showNewPrintWindowControll(inputDocument: self.pdfDocument, inputPageRange: KMPrintPageRange(), printType: .pamphlet)
  429. }
  430. }
  431. extension KMPrintWindowController: KMPrintChooseViewDelegate {
  432. func showData(sender: Any, data: KMPrintModel) {
  433. self.chooseData = data
  434. }
  435. func printerChange(sender: Any, data: KMPrintModel) {
  436. }
  437. func pageSetChange(sender: Any, data: KMPrintModel) {
  438. self.chooseData = data
  439. self.presenter.reloadData()
  440. }
  441. func pageNumberChange(sender: Any, data: KMPrintModel) {
  442. }
  443. func blackAndWhiteChange(sender: Any, data: KMPrintModel) {
  444. }
  445. func printOnBothSidesChange(sender: Any, data: KMPrintModel) {
  446. }
  447. func pageRangeChange(sender: Any, data: KMPrintModel) {
  448. self.chooseData = data
  449. self.presenter.reloadData()
  450. }
  451. func printDirectionChange(sender: Any, data: KMPrintModel) {
  452. self.chooseData = data
  453. self.presenter.reloadData()
  454. }
  455. func printContentChange(sender: Any, data: KMPrintModel) {
  456. self.chooseData = data
  457. self.presenter.reloadData()
  458. }
  459. func printReverseChange(sender: Any, data: KMPrintModel) {
  460. self.chooseData = data
  461. self.presenter.reloadData()
  462. }
  463. func printDealModelChange(sender: Any, data: KMPrintModel) {
  464. self.chooseData = data
  465. self.presenter.reloadData()
  466. }
  467. }
  468. extension KMPrintWindowController: KMPrintPresenterDeleage {
  469. func showData(presenter: KMPrintPresenter, document: PDFDocument) {
  470. self.tempPDFDocument = document
  471. self.preview.model = self.chooseData
  472. if isPrintPreView && self.preview.model?.page.operation.type == .poster {
  473. // self.preview.pdfDocument = pdfDocument
  474. } else {
  475. self.preview.pdfDocument = document
  476. }
  477. self.preview.updatePosterPreView()
  478. }
  479. }