KMPrintPresenter_C.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. //
  2. // KMPrintPresenter_C.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2022/12/21.
  6. //
  7. //
  8. import Cocoa
  9. class KMPrintPresenter_C: NSObject {
  10. lazy var printData: KMPrintModel! = KMPrintModel()
  11. var document: CPDFDocument?
  12. fileprivate weak var delegate: KMPrintPresenter_CDeleage?
  13. /**
  14. 初始化presenter
  15. */
  16. func initPresenter(delegate: KMPrintPresenter_CDeleage, data: KMPrintModel, document: CPDFDocument) {
  17. self.delegate = delegate
  18. self.printData = data
  19. self.updatePrintDocument(documentURL: document.documentURL, data: self.printData)
  20. }
  21. func reloadData() {
  22. self.updatePrintDocument(documentURL: self.document!.documentURL, data: self.printData)
  23. }
  24. /**
  25. @abstract 解除绑定
  26. */
  27. func free() {
  28. delegate = nil
  29. }
  30. }
  31. protocol KMPrintPresenter_CDeleage: NSObject {
  32. func showData(presenter: KMPrintPresenter_C, document: CPDFDocument)
  33. }
  34. protocol KMPrintPresenter_CDocument: NSObject {}
  35. extension KMPrintPresenter_C: KMPrintPresenter_CDocument {
  36. /**
  37. @abstract 获取打印document
  38. @param url 源文件url
  39. @param data 数据
  40. @retrun document
  41. */
  42. func updatePrintDocument(documentURL: URL, data: KMPrintModel) -> CPDFDocument {
  43. /**
  44. 获取基本参数
  45. */
  46. let printModel: KMPrintModel = data
  47. /**
  48. 绘制document
  49. */
  50. //创建预览document
  51. let previewDocument = self.creatDocument(url: documentURL)
  52. //获取总page
  53. let pages = self.fetchPages(documentURL: documentURL, range: printModel.page.range)
  54. //插入page
  55. let insertSuccess = self.insertPages(document: previewDocument, printModel: printModel, pages: pages)
  56. if insertSuccess {
  57. KMPrint("插入成功")
  58. } else {
  59. KMPrint("插入失败")
  60. }
  61. //重置document
  62. let filePath = self.saveDocument(document: previewDocument)
  63. if self.delegate != nil {
  64. self.delegate?.showData(presenter: self, document: previewDocument)
  65. }
  66. KMPrint("保存地址" + filePath)
  67. return previewDocument
  68. }
  69. /**
  70. @abstract 插入page
  71. @param paperSet 纸张设置
  72. @param pageSet page设置
  73. @param pages page数组
  74. */
  75. func insertPages(document: CPDFDocument,
  76. printModel: KMPrintModel,
  77. pages: [CPDFPage]) -> Bool {
  78. //每张纸包含的apge数量
  79. var pageOfPaperCount: Int = 1
  80. switch printModel.page.operation.type {
  81. case .multipage:
  82. pageOfPaperCount = Int(printModel.page.operation.pageOfPaper.point.x * printModel.page.operation.pageOfPaper.point.y)
  83. case .poster:
  84. pageOfPaperCount = Int(printModel.page.operation.pageOfPaper.point.x * printModel.page.operation.pageOfPaper.point.y)
  85. default:
  86. pageOfPaperCount = 1
  87. }
  88. //总页数
  89. let count: Int = Int(ceil(Double(pages.count / pageOfPaperCount)))
  90. let size = printModel.page.operation.size
  91. var insertPages: [CPDFPage] = []
  92. for i in 0...count {
  93. //获取多页page
  94. var drawPages: [CPDFPage] = []
  95. for j in 0...pageOfPaperCount {
  96. if i * pageOfPaperCount + j < pages.count {
  97. let drawPage = pages[i * pageOfPaperCount + j]
  98. drawPages.append(drawPage)
  99. }
  100. }
  101. //TODO: 暂时屏蔽
  102. let insertPage = KMPrintPage_C.init()
  103. insertPage.pages = drawPages
  104. insertPage.data = printModel
  105. insertPage.setBounds(CGRect(x: 0, y: 0, width: printModel.paper.info.size.width, height: printModel.paper.info.size.height), for: CPDFDisplayBox.mediaBox)
  106. insertPage.drawBlock = { [unowned self] box, context, pages, data in
  107. //绘制page
  108. self.drawPageToContext(context: context, pages: pages, data: data)
  109. }
  110. insertPages.append(insertPage)
  111. }
  112. var result = true
  113. if insertPages.count != 0 {
  114. for index in 0...insertPages.count - 1 {
  115. let page = insertPages[index]
  116. var success = false
  117. if (printModel.page.range.reversePrintOrder) {
  118. success = document.insertPageObject(page, at: 0)
  119. } else {
  120. success = document.insertPageObject(page, at: UInt(index))
  121. }
  122. if success {
  123. KMPrint("插入成功")
  124. } else {
  125. KMPrint("插入失败")
  126. result = false
  127. }
  128. }
  129. }
  130. // var result = true
  131. // if pages.count != 0 {
  132. // for index in 0...pages.count - 1 {
  133. // let page = pages[index]
  134. // let success = document.insertPageObject(page, at: UInt(index))
  135. // if success {
  136. // print("插入成功")
  137. // } else {
  138. // print("插入失败")
  139. // result = false
  140. // }
  141. // }
  142. // }
  143. return result
  144. }
  145. func creatDocument(url: URL) -> CPDFDocument {
  146. if FileManager.default.fileExists(atPath: NSTemporaryDirectory() + "/PDFReaderProTest") {
  147. try?FileManager.default.createDirectory(atPath: NSTemporaryDirectory() + "/PDFReaderProTest", withIntermediateDirectories: true)
  148. }
  149. let document = CPDFDocument(url: url)!
  150. // document.importPages(IndexSet(integer: 0), from: document, at: 0)
  151. let count = document.pageCount
  152. for _ in 0...count {
  153. document.removePage(at: 0)
  154. }
  155. return document
  156. }
  157. func saveDocument(document: CPDFDocument) -> String {
  158. let filePath = NSTemporaryDirectory() + "/PDFReaderProTest/test2.pdf"
  159. if FileManager.default.fileExists(atPath: filePath) {
  160. try?FileManager.default.removeItem(atPath: filePath)
  161. }
  162. let url: URL = NSURL(string: filePath)! as URL
  163. var success = document.write(to: url)
  164. if !success {
  165. success = NSData(data: document.dataRepresentation()).write(to: url, atomically: true)
  166. }
  167. if success {
  168. KMPrint("保存成功" + filePath)
  169. } else {
  170. KMPrint("保存失败")
  171. }
  172. return filePath
  173. }
  174. /**
  175. 获取pages
  176. @param type 页面类型
  177. @param selectPages 当type 为custom时 传入选中page的下标
  178. */
  179. func fetchPages(documentURL: URL, range: KMPrintPageRange) -> [CPDFPage] {
  180. let document = CPDFDocument.init(url: documentURL)!
  181. if document.pageCount < 1 {
  182. let page: CPDFPage = document.page(at: 0)
  183. return [page]
  184. } else {
  185. var pagesArray: [CPDFPage] = []
  186. switch range.type {
  187. case .allPage:
  188. for index in 0...document.pageCount - 1 {
  189. let page: CPDFPage = document.page(at: index)!
  190. pagesArray.append(page)
  191. }
  192. case .evenPage:
  193. for index in 0...document.pageCount - 1 {
  194. if index % 2 == 0 {
  195. let page: CPDFPage = document.page(at: index)!
  196. pagesArray.append(page)
  197. }
  198. }
  199. case .oddPage:
  200. for index in 0...document.pageCount - 1 {
  201. if index % 2 != 0 {
  202. let page: CPDFPage = document.page(at: index)!
  203. pagesArray.append(page)
  204. }
  205. }
  206. // case .currentPage:
  207. // let page = self.pdfView.currentPage()
  208. // if page != nil {
  209. // pagesArray.append(page!)
  210. // } else {
  211. // print("page不存在")
  212. // }
  213. case .custom:
  214. for index in range.selectPages {
  215. let page: CPDFPage = document.page(at: UInt(index - 1))
  216. pagesArray.append(page)
  217. }
  218. default:
  219. KMPrint("无匹配选项")
  220. }
  221. return pagesArray
  222. }
  223. }
  224. /**
  225. @abstract 获取context
  226. @param size纸张大小
  227. */
  228. func createContext(size: CGSize) -> CGContext {
  229. let s = CGSize(width: nearbyint(size.width), height: nearbyint(size.height))
  230. let rep = NSBitmapImageRep.init(bitmapDataPlanes: nil,
  231. pixelsWide: Int(s.width),
  232. pixelsHigh: Int(s.height),
  233. bitsPerSample: 8,
  234. samplesPerPixel: 4,
  235. hasAlpha: true,
  236. isPlanar: false,
  237. colorSpaceName: NSColorSpaceName.calibratedRGB,
  238. bytesPerRow: 0,
  239. bitsPerPixel: 0)!
  240. let context: CGContext = NSGraphicsContext.init(bitmapImageRep: rep)!.cgContext
  241. return context
  242. }
  243. /**
  244. @abstract 绘制page
  245. @param context
  246. @pages page数组 [CPDFPage]
  247. */
  248. func drawPageToContext(context: CGContext, pages: [CPDFPage], data: KMPrintModel) {
  249. /**
  250. paper
  251. */
  252. let paperDirection: KMPrintPaperDirectionType = .vertical //打印方向
  253. let paperSize: CGSize = CGSize(width: 595, height: 842) //页面paper大小
  254. var dealPaperSize: CGSize = paperSize //页面paper大小
  255. let paperInset: NSEdgeInsets = NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) //绘制paper大小
  256. var columnCount: Int = 2 //行
  257. var rowCount: Int = 2 //列
  258. let columnSpace: CGFloat = 2.0 //行间距
  259. let rowSpace: CGFloat = 2.0 //列间距
  260. let border: Bool = true
  261. /**
  262. page
  263. */
  264. let pageOrder: KMPrintPageOperation.Multipage.Order = .horizontal //页面顺序
  265. var pageSize: CGSize = CGSize(width: 100, height: 100) //page大小
  266. let contentType: KMPrintContentType = .document
  267. var scale: Float = 1.0 //缩放尺寸
  268. let autoRotate: Bool = false
  269. /**
  270. 计算
  271. */
  272. if paperDirection == .horizontal {
  273. dealPaperSize = CGSize(width: dealPaperSize.height, height: dealPaperSize.width)
  274. }
  275. //减去inset
  276. dealPaperSize = CGSize(width: dealPaperSize.width - paperInset.left - paperInset.right,
  277. height: dealPaperSize.height - paperInset.bottom - paperInset.top)
  278. //计算page尺寸(减去page之间的间隙)
  279. pageSize = CGSize(width: (dealPaperSize.width - CGFloat((columnCount - 1)) * CGFloat(columnSpace)) / CGFloat(columnCount),
  280. height: (dealPaperSize.height - CGFloat((rowCount - 1)) * CGFloat(rowSpace)) / CGFloat(rowCount))
  281. //如果是横向参数需切换
  282. if pageOrder == .horizontal ||
  283. pageOrder == .horizontalReverseSequence {
  284. let temp = columnCount
  285. columnCount = rowCount
  286. rowCount = temp
  287. }
  288. for i in 0...columnCount {
  289. for j in 0...rowCount {
  290. let index = j + i * columnCount
  291. if index < pages.count {
  292. //参数
  293. let page = pages[index]
  294. let rect = page.bounds(for: CPDFDisplayBox.cropBox)
  295. let originSize = rect.size
  296. var dealSize = originSize
  297. var rotate = page.rotation
  298. var annoations: [CPDFAnnotation] = page.annotations
  299. //处理
  300. switch contentType {
  301. case .document:
  302. annoations.removeAll()
  303. case .documentAndStamp:
  304. for annoation in annoations {
  305. if !(annoation.isKind(of: CPDFStampAnnotation.self)) {
  306. annoation.page.removeAnnotation(annoation)
  307. }
  308. }
  309. case .documentAndMarkup:
  310. for annoation in annoations {
  311. if !(annoation.isKind(of: CPDFMarkupAnnotation.self)) {
  312. annoation.page.removeAnnotation(annoation)
  313. }
  314. }
  315. default: break
  316. }
  317. if rotate == 90 ||
  318. rotate == 270 {
  319. dealSize = CGSize(width: originSize.height, height: originSize.width)
  320. }
  321. //取出page横竖时能显示的最大Rect
  322. if autoRotate {
  323. //page旋转度数为0度或者180度时,在指定的大小内,能显示的比例
  324. let scale1 = Float(min(pageSize.width / originSize.width, pageSize.height / originSize.height))
  325. //page旋转度数为90度或者270度时,在指定的大小内,能显示的比例
  326. let scale2 = Float(min(pageSize.width / originSize.height, pageSize.height / originSize.width))
  327. scale = max(scale1, scale2)
  328. if scale1 > scale2 {
  329. //高为竖直排列时,显示最大,则需将page时90度或者270度需要进行旋转
  330. if rotate == 90 ||
  331. rotate == 270 {
  332. rotate = rotate - 90
  333. }
  334. } else {
  335. //宽为竖直排列时,显示最大,则需将page时0度或者180度需要进行旋转
  336. if rotate == 0 ||
  337. rotate == 180 {
  338. rotate = rotate - 90
  339. }
  340. }
  341. if rotate == 90 ||
  342. rotate == 270 {
  343. dealSize = CGSize(width: originSize.height, height: originSize.width)
  344. } else {
  345. dealSize = CGSize(width: originSize.width, height: originSize.height)
  346. }
  347. } else {
  348. scale = Float(min(pageSize.width / dealSize.width, pageSize.height / dealSize.height))
  349. }
  350. scale = min(scale, 1)
  351. //居中
  352. let spaceX: CGFloat = (pageSize.width - dealSize.width * CGFloat(scale)) / 2
  353. let spaceY: CGFloat = (pageSize.height - dealSize.height * CGFloat(scale))/2
  354. var translateX: CGFloat = 0.0
  355. var translateY: CGFloat = 0.0
  356. switch pageOrder {
  357. case .horizontal:
  358. translateX = (pageSize.width + columnSpace) + CGFloat(j) + paperInset.left + spaceX
  359. //页面内容高度 + 下边的行间距 - 第几个cell的高度 +居中
  360. translateY = dealPaperSize.height + paperInset.bottom - (pageSize.height + rowSpace) * (CGFloat(i) + 1) + spaceY + rowSpace
  361. case .horizontalReverseSequence:
  362. translateX = dealPaperSize.width + paperInset.left - (pageSize.width + columnSpace) * (CGFloat(j) + 1) + spaceX + columnSpace
  363. translateY = dealPaperSize.height - (pageSize.height + rowSpace) * (CGFloat(i) + 1) + spaceY + paperInset.bottom + rowSpace
  364. case .vertical:
  365. translateX = (pageSize.width + columnSpace) * CGFloat(i) + paperInset.left + spaceX
  366. translateY = dealPaperSize.height - (pageSize.height + rowSpace) * (CGFloat(j) + 1) + spaceY + paperInset.bottom + rowSpace
  367. case .verticalReverseSequence:
  368. translateX = dealPaperSize.width + paperInset.left - (pageSize.width + columnSpace) * (CGFloat(i) + 1) + spaceX + columnSpace
  369. translateY = dealPaperSize.height - (pageSize.height + rowSpace) * (CGFloat(j) + 1) + spaceY + paperInset.bottom + rowSpace
  370. }
  371. context.saveGState()
  372. //平移
  373. context.translateBy(x: translateX, y: translateY)
  374. //缩放
  375. context.scaleBy(x: CGFloat(scale), y: CGFloat(scale))
  376. page.draw(with: CPDFDisplayBox.cropBox, to: context)
  377. page.transform(context, for: CPDFDisplayBox.cropBox)
  378. if border {
  379. var dirtyRect = rect
  380. if rotate == 90 ||
  381. rotate == 270 {
  382. dirtyRect = NSMakeRect(dirtyRect.origin.x, dirtyRect.origin.y, dirtyRect.size.height, dirtyRect.size.width)
  383. }
  384. context.addRect(dirtyRect)
  385. context.setStrokeColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
  386. context.strokePath()
  387. }
  388. context.restoreGState()
  389. }
  390. }
  391. }
  392. }
  393. }
  394. protocol KMPrintPresenter_CProtocol: NSObject {
  395. }