KMPrintWindowController.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. 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) ?? CGSizeZero
  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. var printOperation: NSPrintOperation = NSPrintOperation()
  319. let scalingMode: PDFPrintScalingMode = .pageScaleToFit
  320. if document.responds(to: NSSelectorFromString("printOperationForPrintInfo:scalingMode:autoRotate:")) {
  321. printOperation = document.printOperation(for: printInfo, scalingMode: scalingMode, autoRotate: false) ?? NSPrintOperation()
  322. }
  323. printOperation.printPanel.options = [.showsPreview, .showsCopies, .showsOrientation, .showsPageRange, .showsPaperSize, .showsCopies, .showsPrintSelection, .showsScaling]
  324. let controller = KMPrintAccessoryController_OC(nibName: "KMPrintAccessoryController_OC", bundle: nil)
  325. printOperation.printPanel.addAccessoryController(controller)
  326. printOperation.runModal(for: NSWindow.currentWindow(), delegate: self, didRun: nil, contextInfo: nil)
  327. }
  328. }
  329. static func openPrinter(document: PDFDocument) {
  330. let printInfo = NSPrintInfo.shared
  331. let printOperation: NSPrintOperation = document.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true)!
  332. printOperation.showsPrintPanel = true //是否弹出打印机设置界面
  333. printOperation.run()
  334. }
  335. }
  336. //MARK: - Print
  337. extension KMPrintWindowController {
  338. static func printImage(image: NSImage) {
  339. let pdfDocument : PDFDocument = PDFDocument()
  340. let newpage : PDFPage = PDFPage(image: image)!
  341. pdfDocument.insert(newpage, at: 0)
  342. KMPrintWindowController.showPrintWindowControll(inputData: nil, inputDocument: pdfDocument, inputPageRange: KMPrintPageRange())
  343. }
  344. static func cpdf_printImage(image: NSImage) {
  345. let pdfDocument : PDFDocument = PDFDocument()
  346. let newpage : PDFPage = PDFPage(image: image)!
  347. pdfDocument.insert(newpage, at: 0)
  348. KMPrintWindowController.openPrintView(document: pdfDocument)
  349. }
  350. }
  351. extension NetService {
  352. func textRecordField(field: String) -> String? {
  353. guard
  354. let data = self.txtRecordData(),
  355. let field = NetService.dictionary(fromTXTRecord: data)[field]
  356. else { return nil }
  357. return String(data: field, encoding: String.Encoding.utf8)
  358. }
  359. }
  360. extension KMPrintWindowController: KMPrintBottomViewDelegate {
  361. func savePDFAction() {
  362. KMPrint("保存PDF")
  363. // guard let url = self.presenter.printData.url else { return }
  364. guard let document = self.tempPDFDocument else { return }
  365. // guard let url = self.tempPDFDocument?.documentURL else { return }
  366. // let document = CPDFDocument(url: url)
  367. // NSPanel.savePanel_pdf_success(self.window!, document: document) { result in
  368. // NSWorkspace.shared.selectFile(result.path, inFileViewerRootedAtPath: "")
  369. // }
  370. //
  371. let savePanel = NSSavePanel()
  372. savePanel.allowedFileTypes = ["pdf"]
  373. savePanel.beginSheetModal(for: NSWindow.currentWindow(), completionHandler: { result in
  374. if result != .OK {
  375. // completion(result, nil)
  376. } else {
  377. document.write(to: savePanel.url!)
  378. NSWorkspace.shared.selectFile(savePanel.url?.path, inFileViewerRootedAtPath: "")
  379. // completion(result, success ? savePanel.url! : nil)
  380. }
  381. })
  382. }
  383. func printerAction() {
  384. KMPrint("调用打印机打印")
  385. guard let url = self.presenter.printData.url else { return }
  386. let document = PDFDocument.init(url: url)
  387. let printInfo = NSPrintInfo.shared
  388. let printOperation: NSPrintOperation = document!.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true)!
  389. let printPanel = printOperation.printPanel
  390. printPanel.options = [.showsOrientation, .showsPageRange, .showsPaperSize, .showsScaling, .showsPreview]
  391. printOperation.runModal(for: self.window!, delegate: self, didRun: nil, contextInfo: nil)
  392. }
  393. func cancelAction() {
  394. KMPrint("cancel")
  395. NSApp.mainWindow!.endSheet(self.window!)
  396. self.close()
  397. // self.window?.orderOut(self)
  398. }
  399. func printAction() {
  400. KMPrint("打印机直接打印")
  401. // guard let url = self.presenter.printData.url else { return }
  402. // let document = PDFDocument.init(url: url)
  403. guard let document = self.tempPDFDocument else { return }
  404. let printInfo = NSPrintInfo.shared
  405. let printOperation: NSPrintOperation = document.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true)!
  406. printOperation.showsPrintPanel = true //是否弹出打印机设置界面
  407. printOperation.run()
  408. }
  409. func posterAction() {
  410. self.changeTypeAction?(self, .poster)
  411. self.cancelAction()
  412. KMPrintWindowController.showNewPrintWindowControll(inputDocument: self.pdfDocument, inputPageRange: KMPrintPageRange(), printType: .poster)
  413. }
  414. func multipageAction() {
  415. self.changeTypeAction?(self, .multipage)
  416. self.cancelAction()
  417. KMPrintWindowController.showNewPrintWindowControll(inputDocument: self.pdfDocument, inputPageRange: KMPrintPageRange(), printType: .multipage)
  418. }
  419. func bookletAction() {
  420. self.changeTypeAction?(self, .pamphlet)
  421. self.cancelAction()
  422. KMPrintWindowController.showNewPrintWindowControll(inputDocument: self.pdfDocument, inputPageRange: KMPrintPageRange(), printType: .pamphlet)
  423. }
  424. }
  425. extension KMPrintWindowController: KMPrintChooseViewDelegate {
  426. func showData(sender: Any, data: KMPrintModel) {
  427. self.chooseData = data
  428. }
  429. func printerChange(sender: Any, data: KMPrintModel) {
  430. }
  431. func pageSetChange(sender: Any, data: KMPrintModel) {
  432. self.chooseData = data
  433. self.presenter.reloadData()
  434. }
  435. func pageNumberChange(sender: Any, data: KMPrintModel) {
  436. }
  437. func blackAndWhiteChange(sender: Any, data: KMPrintModel) {
  438. }
  439. func printOnBothSidesChange(sender: Any, data: KMPrintModel) {
  440. }
  441. func pageRangeChange(sender: Any, data: KMPrintModel) {
  442. self.chooseData = data
  443. self.presenter.reloadData()
  444. }
  445. func printDirectionChange(sender: Any, data: KMPrintModel) {
  446. self.chooseData = data
  447. self.presenter.reloadData()
  448. }
  449. func printContentChange(sender: Any, data: KMPrintModel) {
  450. self.chooseData = data
  451. self.presenter.reloadData()
  452. }
  453. func printReverseChange(sender: Any, data: KMPrintModel) {
  454. self.chooseData = data
  455. self.presenter.reloadData()
  456. }
  457. func printDealModelChange(sender: Any, data: KMPrintModel) {
  458. self.chooseData = data
  459. self.presenter.reloadData()
  460. }
  461. }
  462. extension KMPrintWindowController: KMPrintPresenterDeleage {
  463. func showData(presenter: KMPrintPresenter, document: PDFDocument) {
  464. self.tempPDFDocument = document
  465. self.preview.model = self.chooseData
  466. if isPrintPreView && self.preview.model?.page.operation.type == .poster {
  467. // self.preview.pdfDocument = pdfDocument
  468. } else {
  469. self.preview.pdfDocument = document
  470. }
  471. self.preview.updatePosterPreView()
  472. }
  473. }