KMPrintWindowController.swift 19 KB

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