KMPrintPresenter.swift 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. //
  2. // KMPrintPresenter.swift
  3. // PDF Master
  4. //
  5. // Created by lizhe on 2022/12/21.
  6. //
  7. import Cocoa
  8. import PDFKit
  9. //MARK: CPDFKit page 方法无法使用 暂时使用系统方法
  10. class KMPrintPresenter: NSObject {
  11. lazy var printData: KMPrintModel = KMPrintModel() {
  12. didSet {
  13. self.reloadData()
  14. }
  15. }
  16. var document: CPDFDocument?
  17. fileprivate weak var delegate: KMPrintPresenterDeleage?
  18. /**
  19. 初始化presenter 绑定数据
  20. */
  21. func initPresenter(delegate: KMPrintPresenterDeleage, data: KMPrintModel, document: CPDFDocument) {
  22. self.delegate = delegate
  23. self.document = document
  24. self.printData = data
  25. // DispatchQueue.main.async {
  26. // let pdfDocument = self.updatePrintDocument(documentURL: document.documentURL, data: self.printData)
  27. // self.printData.url = pdfDocument.documentURL
  28. // }
  29. }
  30. /**
  31. 刷新数据
  32. */
  33. func reloadData() {
  34. guard let document = document else { return }
  35. let pdfDocument = self.updatePrintDocument(documentURL: document.documentURL, data: self.printData)
  36. self.printData.url = pdfDocument.documentURL
  37. }
  38. /**
  39. @abstract 解除绑定
  40. */
  41. func free() {
  42. delegate = nil
  43. }
  44. }
  45. protocol KMPrintPresenterDeleage: NSObject {
  46. func showData(presenter: KMPrintPresenter, document: CPDFDocument)
  47. }
  48. protocol KMPrintPresenterDocument: NSObject {}
  49. extension KMPrintPresenter: KMPrintPresenterDocument {
  50. /**
  51. @abstract 获取打印document
  52. @param url 源文件url
  53. @param data 数据
  54. @retrun document
  55. */
  56. func updatePrintDocument(documentURL: URL, data: KMPrintModel) -> CPDFDocument {
  57. // 获取基本参数
  58. let printModel: KMPrintModel = data
  59. //获取总page
  60. let pages = self.fetchPages(documentURL, printModel.page)
  61. //绘制PDF
  62. let filePath = self.drawPages(nil, printModel, pages)
  63. let result = CPDFDocument(url: URL(fileURLWithPath: filePath))!
  64. if self.delegate != nil {
  65. self.delegate?.showData(presenter: self, document: result)
  66. }
  67. KMPrint("保存地址" + filePath)
  68. return result
  69. }
  70. /**
  71. @abstract 插入page
  72. @param paperSet 纸张设置
  73. @param pageSet page设置
  74. @param pages page数组
  75. */
  76. func drawPages(_ toFilePath: String?,
  77. _ printModel: KMPrintModel,
  78. _ pages: [KMPrintDrawPage]) -> String {
  79. /**
  80. 参数
  81. */
  82. //纸张大小
  83. let paperSize: CGSize = self.fetchPaperSize(printModel.paper)
  84. //总页数
  85. let paperCount: Int = self.fetchTotalPaperCount(paperSize, pages, printModel.page)
  86. //每页page数
  87. let pageOfPaperCount: Int = self.fetchPageOfPaper(printModel.page)
  88. //获取每张纸的page
  89. let drawPages: [[KMPrintDrawPage]] = self.fetchDrawPages(paperSize, printModel.page, paperCount, pageOfPaperCount, pages)
  90. //导出地址
  91. let filePath = KMPrintPresenter.fetchSaveFilePath(toFilePath)
  92. /**
  93. 绘制每张纸的内容
  94. */
  95. //创建画布
  96. let context: CGContext = self.createContext(filePath, paperSize)
  97. for drawPage in drawPages {
  98. context.beginPDFPage(nil)
  99. self.drawPageToContext(context, drawPage, printModel)
  100. context.endPDFPage()
  101. }
  102. context.closePDF()
  103. return filePath
  104. }
  105. /**
  106. 获取绘制的pages
  107. @pageModel page参数
  108. @param paperCount 纸张数量
  109. @param pageOfPaperCount 每张纸的page数量
  110. @param pages 所有page数量
  111. */
  112. func fetchDrawPages(_ paperSize: CGSize, _ pageModel: KMPrintPageModel,_ paperCount: Int, _ pageOfPaperCount: Int, _ pages: [KMPrintDrawPage]) -> [[KMPrintDrawPage]] {
  113. guard pages.count != 0 else {
  114. return []
  115. }
  116. //一个page重复获取次数
  117. var pageRepetitionCount = 1
  118. if (pageModel.operation.type == .poster) {
  119. if (pageModel.operation.poster.type == .tile) {
  120. pageRepetitionCount = Int(pageModel.operation.poster.tilePoint.x * pageModel.operation.poster.tilePoint.y)
  121. } else if (pageModel.operation.poster.type == .breakUp) {
  122. pageRepetitionCount = Int(pageModel.operation.pageOfPaper.point.x * pageModel.operation.pageOfPaper.point.y)
  123. }
  124. }
  125. var drawPages:[[KMPrintDrawPage]] = []
  126. for i in 0...(paperCount - 1) {
  127. //获取多页page
  128. var tempPags: [KMPrintDrawPage] = []
  129. for j in 0...(pageOfPaperCount - 1) {
  130. let pageIndex = i / pageRepetitionCount
  131. if (pageIndex * pageOfPaperCount + j < pages.count) {
  132. let originDrawPage = (pages[pageIndex * pageOfPaperCount + j])
  133. let drawPage = KMPrintDrawPage()
  134. drawPage.page = originDrawPage.page
  135. var pageCropRect = self.fetchPageCropRect(paperSize,i % pageRepetitionCount, pageModel, drawPage)
  136. var pageShowRect = pageCropRect
  137. if (pageModel.operation.type == .poster) {
  138. if (pageModel.operation.poster.type == .tile) {
  139. pageShowRect = self.fetchPageShowRect(paperSize, i % pageRepetitionCount, pageModel, drawPage)
  140. } else if (pageModel.operation.poster.type == .breakUp) {
  141. pageShowRect = pageCropRect
  142. }
  143. }
  144. drawPage.cropRect = pageCropRect
  145. drawPage.showRect = pageShowRect
  146. tempPags.append(drawPage)
  147. }
  148. }
  149. drawPages.append(tempPags)
  150. }
  151. return drawPages
  152. }
  153. /**
  154. 获取pages
  155. @param type 页面类型
  156. @param contentType annoation类型
  157. @param selectPages 当type 为custom时 传入选中page的下标
  158. */
  159. static func fetchSaveFilePath(_ filePath: String?) -> String {
  160. var saveFilePath = filePath ?? ""
  161. if saveFilePath.count == 0 {
  162. saveFilePath = NSTemporaryDirectory() + "/PDFMasterTest/test2.pdf"
  163. }
  164. if !FileManager.default.fileExists(atPath: NSTemporaryDirectory() + "/PDFMasterTest") {
  165. try?FileManager.default.createDirectory(atPath: NSTemporaryDirectory() + "/PDFMasterTest", withIntermediateDirectories: true)
  166. }
  167. if FileManager.default.fileExists(atPath: saveFilePath) {
  168. try?FileManager.default.removeItem(atPath: saveFilePath)
  169. }
  170. return saveFilePath
  171. }
  172. /**
  173. 获取pages
  174. @param type 页面类型
  175. @param contentType annoation类型
  176. @param selectPages 当type 为custom时 传入选中page的下标
  177. */
  178. static func creatDocument(_ url: URL) -> CPDFDocument {
  179. if FileManager.default.fileExists(atPath: NSTemporaryDirectory() + "/PDFMasterTest") {
  180. try?FileManager.default.createDirectory(atPath: NSTemporaryDirectory() + "/PDFMasterTest", withIntermediateDirectories: true)
  181. }
  182. let document = CPDFDocument(url: url)!
  183. // document.importPages(IndexSet(integer: 0), from: document, at: 0)
  184. let count = document.pageCount
  185. for _ in 0...(count - 1) {
  186. document.removePage(at: 0)
  187. }
  188. return document
  189. }
  190. /**
  191. 获取pages
  192. @param type 页面类型
  193. @param contentType annoation类型
  194. @param selectPages 当type 为custom时 传入选中page的下标
  195. */
  196. func fetchPages(_ documentURL: URL, _ pageModel: KMPrintPageModel) -> [KMPrintDrawPage] {
  197. let document = PDFDocument.init(url: documentURL)!
  198. var pageIndexs: [Int] = []
  199. let range = pageModel.range
  200. let contentType = pageModel.contentType
  201. let reversePrintOrder = range.reversePrintOrder
  202. switch range.type {
  203. case .allPage:
  204. for index in 0...document.pageCount - 1 {
  205. pageIndexs.append(index)
  206. }
  207. case .evenPage:
  208. for index in 0...document.pageCount - 1 {
  209. if index % 2 == 0 {
  210. pageIndexs.append(index)
  211. }
  212. }
  213. case .oddPage:
  214. for index in 0...document.pageCount - 1 {
  215. if index % 2 != 0 {
  216. pageIndexs.append(index)
  217. }
  218. }
  219. case .currentPage:
  220. pageIndexs.append(0)
  221. case .custom:
  222. pageIndexs.append(0)
  223. default:
  224. pageIndexs.append(0)
  225. }
  226. var pagesArray: [KMPrintDrawPage] = []
  227. for index in pageIndexs {
  228. let page = document.page(at: index)!
  229. let drawPage = KMPrintDrawPage()
  230. drawPage.page = page
  231. self.dealPageContent(contentType, [drawPage])
  232. if reversePrintOrder {
  233. pagesArray.insert(drawPage, at: 0)
  234. } else {
  235. pagesArray.append(drawPage)
  236. }
  237. }
  238. return pagesArray
  239. }
  240. /**
  241. 处理page annoation 内容
  242. @param contentType annoation类型
  243. @param pages page
  244. */
  245. func dealPageContent (_ contentType: KMPrintContentType, _ pages: [KMPrintDrawPage]) -> Void {
  246. for page in pages {
  247. let annoations: [PDFAnnotation] = page.page.annotations
  248. //内容处理
  249. switch contentType {
  250. case .document:
  251. for annoation in annoations {
  252. annoation.page!.removeAnnotation(annoation)
  253. }
  254. case .documentAndStamp:
  255. for annoation in annoations {
  256. if !self.isAnnoationStamp(type: annoation.type!) {
  257. annoation.page!.removeAnnotation(annoation)
  258. }
  259. }
  260. case .documentAndMarkup:
  261. for annoation in annoations {
  262. if !self.isAnnoationMarkup(type: annoation.type!) {
  263. annoation.page!.removeAnnotation(annoation)
  264. }
  265. }
  266. case .documentAndForm:
  267. for annoation in annoations {
  268. if !self.isAnnoationForm(type: annoation.type!) {
  269. annoation.page!.removeAnnotation(annoation)
  270. }
  271. }
  272. default:
  273. KMPrint("未找到")
  274. break
  275. }
  276. }
  277. }
  278. /**
  279. @abstract 获取context
  280. @param size纸张大小
  281. */
  282. func createContext(_ saveFilePath: String, _ size: CGSize) -> CGContext {
  283. var mediaBox: CGRect = NSMakeRect(0, 0, size.width, size.height)
  284. let url = CFURLCreateWithFileSystemPath(nil, saveFilePath as CFString, .cfurlposixPathStyle, false)
  285. let content: CGContext = CGContext.init(url!, mediaBox: &mediaBox, nil)!
  286. return content
  287. }
  288. /**
  289. @abstract 绘制page
  290. @param context
  291. @pages page数组 [CPDFPage]
  292. */
  293. func drawPageToContext(_ context: CGContext, _ pages: [KMPrintDrawPage], _ data: KMPrintModel, _ drawPageRect: CGRect = NSZeroRect) {
  294. //左下角有坐标系原点
  295. /**
  296. paper
  297. */
  298. let paperSize: CGSize = self.fetchPaperSize(data.paper)//纸张大小
  299. let paperItemSize: CGSize = self.fetchPaperItemSize(data.paper) //页面paper大小(去除边框)
  300. let paperInset: NSEdgeInsets = data.paper.info.inset //绘制paper大小
  301. let border: Bool = data.page.operation.multipage.isBorder //是否存在边框
  302. /**
  303. page
  304. */
  305. let pageOrder: KMPrintPageOperation.Multipage.Order = .horizontal //页面顺序
  306. let pageSize: CGSize = self.fetchPageItemSize(data.page, paperItemSize) //page大小
  307. let showModel: KMPrintPageOperation.Size = self.fetchShowModel(data.page)
  308. let autoRotate = self.fetchAutoRotate(data.page)
  309. let autoSize: Bool = self.fetchAutoSize(data.page)
  310. //行列
  311. let columnAndRow = self.fetchPageColumnAndRow(data.page) //行 列数量
  312. let columnAndRowSpace = CGPoint(x: data.page.operation.multipage.lineSpacing, y: data.page.operation.multipage.columnsSpacing) //行 列之间的空间
  313. for i in 0..<Int(columnAndRow.x) {
  314. for j in 0..<(Int(columnAndRow.y)) {
  315. let index = j + i * Int(columnAndRow.y)
  316. if index < pages.count {
  317. //参数
  318. let page: KMPrintDrawPage = pages[index]
  319. let rect = page.showRect
  320. //裁剪当前Page
  321. page.page.setBounds(page.cropRect, for: .cropBox)
  322. let pageItemSize = rect.size
  323. let rotate = page.page.rotation
  324. var scale = self.fetchPageScale(page, pageSize, autoRotate, autoSize)
  325. if data.page.operation.type == .size {
  326. if showModel.model == .custom {
  327. scale *= showModel.scale
  328. } else if showModel.model == .full {
  329. scale = 1
  330. }
  331. } else if (data.page.operation.type == .poster) {
  332. if (data.page.operation.poster.type == .tile) {
  333. scale = data.page.operation.poster.scale
  334. }
  335. }
  336. //当前item的自身中心点
  337. let center = CGPoint(x: (pageSize.width - pageItemSize.width * scale) / 2.0 ,
  338. y: (pageSize.height - pageItemSize.height * scale) / 2.0)
  339. var origin = rect.origin
  340. //多页Page自动旋转
  341. // if autoSize {
  342. switch pageOrder {
  343. case .horizontal:
  344. origin.x = (pageSize.width + columnAndRowSpace.x) * CGFloat(i) + paperInset.left + center.x
  345. //页面内容高度 + 下边的行间距 - 第几个cell的高度 +居中
  346. origin.y = paperSize.height - (pageSize.height + columnAndRowSpace.y) * (CGFloat(j) + 1) + center.y + columnAndRowSpace.y
  347. case .horizontalReverseSequence:
  348. origin.x = paperSize.width - (pageSize.width + columnAndRowSpace.x) * (CGFloat(i) + 1) + center.x + columnAndRowSpace.x
  349. origin.y = paperSize.height - (pageSize.height + columnAndRowSpace.y) * (CGFloat(j) + 1) + center.y + paperInset.bottom + columnAndRowSpace.y
  350. case .vertical:
  351. origin.x = (pageSize.width + columnAndRowSpace.x) * CGFloat(i) + paperInset.left + center.x
  352. origin.y = paperSize.height - (pageSize.height + columnAndRowSpace.y) * (CGFloat(j) + 1) + center.y + paperInset.bottom + columnAndRowSpace.y
  353. case .verticalReverseSequence:
  354. origin.x = paperSize.width - (pageSize.width + columnAndRowSpace.x) * (CGFloat(i) + 1) + center.x + columnAndRowSpace.x
  355. origin.y = paperSize.height - (pageSize.height + columnAndRowSpace.y) * (CGFloat(j) + 1) + center.y + paperInset.bottom + columnAndRowSpace.y
  356. default:
  357. KMPrint("未找到")
  358. break
  359. }
  360. // }
  361. NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
  362. NSGraphicsContext.saveGraphicsState()
  363. //平移
  364. context.translateBy(x: origin.x, y: origin.y)
  365. //缩放
  366. context.scaleBy(x: CGFloat(scale), y: CGFloat(scale))
  367. page.page.draw(with: PDFDisplayBox.cropBox, to: context)
  368. page.page.transform(context, for: PDFDisplayBox.cropBox)
  369. if border {
  370. var dirtyRect = rect
  371. //CGRectMake(origin.x, origin.y, 100, 100)
  372. if rotate == 90 ||
  373. rotate == 270 {
  374. dirtyRect = NSMakeRect(dirtyRect.origin.x, dirtyRect.origin.y, dirtyRect.size.height, dirtyRect.size.width)
  375. }
  376. context.addRect(dirtyRect)
  377. context.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1.0)
  378. context.strokePath()
  379. }
  380. NSGraphicsContext.restoreGraphicsState()
  381. // page.setBounds(NSRect(x: 0, y: 0, width: pageRect.size.width, height: pageRect.size.height), for: .cropBox)
  382. }
  383. }
  384. }
  385. }
  386. func drawLabelTextContextSize(context: CGContext) {
  387. let pageSize = CGSize(width: 0, height: 0)
  388. let KBlankA4W = pageSize.width
  389. let KBlankA4H = pageSize.height
  390. var contextString: String
  391. // if let labelString = PDFPrint.labelString, !labelString.isEmpty {
  392. // contextString = labelString
  393. // } else {
  394. let date = Date()
  395. let formatter = DateFormatter()
  396. formatter.dateFormat = "YYYY-MM-dd hh:mm:ss"
  397. contextString = "(\("1"),\("1")) \("filePath.lastPathComponent") \(formatter.string(from: date))"
  398. // }
  399. let fontSize = 12.0 * (max(KBlankA4W, KBlankA4H) / 842)
  400. let font = NSFont.systemFont(ofSize: fontSize)
  401. let color = NSColor.black
  402. var size = NSSize.zero
  403. var style = NSMutableParagraphStyle()
  404. style.alignment = .center
  405. style.lineBreakMode = .byCharWrapping
  406. var attributes = [NSAttributedString.Key: Any]()
  407. attributes[.paragraphStyle] = style
  408. attributes[.foregroundColor] = color
  409. attributes[.font] = font
  410. size = contextString.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude),
  411. options: [.usesLineFragmentOrigin, .usesFontLeading],
  412. attributes: attributes).size
  413. // if PDFPrint.splitType == .pageNumber {
  414. contextString.draw(in: CGRect(x: 10 + 10,
  415. y: KBlankA4H - 10 + size.height,
  416. width: size.width, height: size.height),
  417. withAttributes: attributes)
  418. // } else {
  419. // contextString.draw(in: CGRect(x: PDFPrint.edgeInsets.left + 10,
  420. // y: KBlankA4H - PDFPrint.edgeInsets.top + size.height,
  421. // width: size.width, height: size.height),
  422. // withAttributes: attributes)
  423. // }
  424. }
  425. }
  426. protocol KMPrintPresenterPage {}
  427. extension KMPrintPresenter: KMPrintPresenterPage {
  428. /**
  429. 获取pages
  430. @param type 页面类型
  431. @param contentType annoation类型
  432. @param selectPages 当type 为custom时 传入选中page的下标
  433. */
  434. func fetchPageCropRect(_ paperSize: CGSize, _ index: Int, _ pageModel: KMPrintPageModel, _ page: KMPrintDrawPage) -> CGRect {
  435. var newRect = page.page.bounds(for: .cropBox)
  436. if (pageModel.operation.type == .poster) {
  437. let originSize = newRect.size
  438. var cropPoint = CGPoint(x: 1, y: 1)
  439. var scale = 1.0
  440. if (pageModel.operation.poster.type == .tile) {
  441. cropPoint = pageModel.operation.poster.tilePoint
  442. // scale = pageModel.operation.poster.scale
  443. } else if (pageModel.operation.poster.type == .breakUp) {
  444. cropPoint = pageModel.operation.pageOfPaper.point
  445. }
  446. let width = originSize.width / cropPoint.x
  447. let height = originSize.height / cropPoint.y
  448. let column: Int = Int(cropPoint.x) //行
  449. let row: Int = Int(cropPoint.y) //列
  450. for i in 0...column - 1 {
  451. for j in 0...row - 1 {
  452. if i + j + i * (row - 1) == index {
  453. newRect.origin.x = CGFloat(i) * width * scale
  454. newRect.origin.y = ((originSize.height - CGFloat(j) * height - height)) * scale
  455. newRect.size.width = width * scale
  456. newRect.size.height = height * scale
  457. return newRect
  458. }
  459. }
  460. }
  461. }
  462. return newRect
  463. }
  464. func fetchPageShowRect(_ paperSize: CGSize, _ index: Int, _ pageModel: KMPrintPageModel, _ page: KMPrintDrawPage) -> CGRect {
  465. var newRect = NSZeroRect
  466. var pageRect = CGRect(x: 0, y: 0, width: paperSize.width, height: paperSize.height)
  467. if (pageModel.operation.type == .poster) {
  468. let pageSize = page.page.bounds(for: .cropBox)
  469. var cropPoint = CGPoint(x: 1, y: 1)
  470. var scale = 1.0
  471. if (pageModel.operation.poster.type == .tile) {
  472. cropPoint = pageModel.operation.poster.tilePoint
  473. scale = pageModel.operation.poster.scale
  474. } else if (pageModel.operation.poster.type == .breakUp) {
  475. cropPoint = pageModel.operation.pageOfPaper.point
  476. }
  477. if (cropPoint.x == 1 && cropPoint.y == 1) {
  478. } else {
  479. let originPaperSize = CGSize(width: paperSize.width * cropPoint.x, height: paperSize.height * cropPoint.y)
  480. let pageWidth = pageSize.width * scale
  481. let pageHeight = pageSize.height * scale
  482. let pageOrigin = CGPoint(x: (originPaperSize.width - pageWidth) / 2, y: (originPaperSize.height - pageHeight) / 2)
  483. let width = originPaperSize.width / cropPoint.x
  484. let height = originPaperSize.height / cropPoint.y
  485. let column: Int = Int(cropPoint.x) //行
  486. let row: Int = Int(cropPoint.y) //列
  487. for i in 0...column - 1 {
  488. for j in 0...row - 1 {
  489. if i + j + i * (row - 1) == index {
  490. newRect.origin.x = CGFloat(i) * width
  491. newRect.origin.y = ((originPaperSize.height - CGFloat(j) * height - height))
  492. newRect.size.width = width
  493. newRect.size.height = height
  494. if (pageOrigin.x > newRect.origin.x) {
  495. pageRect.origin.x = pageOrigin.x
  496. pageRect.size.width = newRect.size.width - pageOrigin.x
  497. } else if (originPaperSize.width - pageOrigin.x > newRect.origin.x) {
  498. pageRect.origin.x = 0
  499. pageRect.size.width = newRect.size.width - pageOrigin.x
  500. } else {
  501. pageRect.origin.x = 0
  502. pageRect.size.width = newRect.size.width
  503. }
  504. if (originPaperSize.height - pageOrigin.y < newRect.origin.y + newRect.size.height) {
  505. pageRect.origin.y = 0
  506. pageRect.size.height = newRect.size.height - pageOrigin.y
  507. } else if (pageOrigin.y > newRect.origin.y) {
  508. pageRect.origin.y = pageOrigin.y
  509. pageRect.size.height = newRect.size.height - pageOrigin.y
  510. } else {
  511. pageRect.origin.y = newRect.origin.y - pageOrigin.y
  512. pageRect.size.height = newRect.size.height
  513. }
  514. return pageRect
  515. }
  516. }
  517. }
  518. }
  519. }
  520. return pageRect
  521. }
  522. func fetchPageColumnAndRow(_ pageModel: KMPrintPageModel) -> CGPoint {
  523. var point = NSZeroPoint
  524. let pageOrder: KMPrintPageOperation.Multipage.Order = pageModel.operation.multipage.orderType //页面顺序
  525. switch pageModel.operation.type {
  526. case .multipage:
  527. point.x = pageModel.operation.pageOfPaper.point.x
  528. point.y = pageModel.operation.pageOfPaper.point.y
  529. default:
  530. point.x = 1
  531. point.y = 1
  532. }
  533. //如果是横向参数需切换
  534. if pageOrder == .horizontal ||
  535. pageOrder == .horizontalReverseSequence {
  536. let temp = point.x
  537. point.x = point.y
  538. point.y = temp
  539. }
  540. return point
  541. }
  542. func fetchAutoRotate(_ pageModel: KMPrintPageModel) -> Bool {
  543. var autoRotate = false
  544. switch pageModel.operation.type {
  545. case .multipage:
  546. autoRotate = pageModel.operation.multipage.isAutoRotate
  547. case .pamphlet:
  548. autoRotate = pageModel.operation.pamphlet.isAutoRotate
  549. default:
  550. autoRotate = false
  551. }
  552. return autoRotate
  553. }
  554. func fetchAutoSize(_ pageModel: KMPrintPageModel) -> Bool {
  555. var autoSize = false
  556. switch pageModel.operation.type {
  557. case .size:
  558. autoSize = true
  559. default:
  560. autoSize = false
  561. }
  562. return autoSize
  563. }
  564. func fetchShowModel(_ pageModel: KMPrintPageModel) -> KMPrintPageOperation.Size {
  565. var model = KMPrintPageOperation.Size()
  566. switch pageModel.operation.type {
  567. case .size:
  568. model = pageModel.operation.size
  569. default:
  570. model = KMPrintPageOperation.Size()
  571. }
  572. return model
  573. }
  574. func fetchPageItemSize(_ pageModel: KMPrintPageModel, _ paperSize: CGSize) -> CGSize {
  575. var size = NSZeroSize
  576. let columnAndRow = self.fetchPageColumnAndRow(pageModel) //行 列数量
  577. let lineSpacing = pageModel.operation.multipage.lineSpacing
  578. let columnsSpacing = pageModel.operation.multipage.columnsSpacing
  579. let columnAndRowSpace = CGPoint(x: lineSpacing, y: columnsSpacing) //行 列之间的空间
  580. //page大小
  581. if pageModel.operation.type == .multipage {
  582. size = CGSize(width: (paperSize.width - CGFloat((columnAndRow.x - 1)) * CGFloat(columnAndRowSpace.x)) / columnAndRow.x,
  583. height: (paperSize.height - CGFloat((columnAndRow.y - 1)) * CGFloat(columnAndRowSpace.y)) / columnAndRow.y)
  584. } else {
  585. size = CGSize(width: (paperSize.width - CGFloat((columnAndRow.x - 1)) * CGFloat(columnAndRowSpace.x)) / columnAndRow.x,
  586. height: (paperSize.height - CGFloat((columnAndRow.y - 1)) * CGFloat(columnAndRowSpace.y)) / columnAndRow.y)
  587. }
  588. return size
  589. }
  590. func fetchPageScale(_ page: KMPrintDrawPage, _ pageItemSize: CGSize, _ autoRotate: Bool, _ autoSize: Bool) -> CGFloat {
  591. var scale = 1.0
  592. let originSize = page.page.bounds(for: .cropBox)
  593. var rotate = page.page.rotation
  594. //取出page横竖时能显示的最大Rect
  595. if autoRotate {
  596. //page旋转度数为0度或者180度时,在指定的大小内,能显示的比例
  597. let scale1 = min(pageItemSize.width / originSize.width, pageItemSize.height / originSize.height)
  598. //page旋转度数为90度或者270度时,在指定的大小内,能显示的比例
  599. let scale2 = min(pageItemSize.width / originSize.height, pageItemSize.height / originSize.width)
  600. scale = max(scale1, scale2)
  601. if scale1 > scale2 {
  602. //高为竖直排列时,显示最大,则需将page时90度或者270度需要进行旋转
  603. if rotate == 90 || rotate == 270 {
  604. rotate = rotate - 90
  605. }
  606. } else {
  607. //宽为竖直排列时,显示最大,则需将page时0度或者180度需要进行旋转
  608. if rotate == 0 || rotate == 180 {
  609. rotate = rotate - 90
  610. }
  611. }
  612. } else {
  613. scale = min(pageItemSize.width / originSize.width, pageItemSize.height / originSize.height)
  614. }
  615. if (autoSize) {
  616. } else {
  617. scale = min(scale, 1)
  618. }
  619. return scale
  620. }
  621. func fetchPageRotate(_ page: KMPrintDrawPage, _ pageItemSize: CGSize, _ autoRotate: Bool) -> CGFloat {
  622. var scale = 1.0
  623. let originSize = page.page.bounds(for: .cropBox)
  624. var rotate = page.page.rotation
  625. //取出page横竖时能显示的最大Rect
  626. if autoRotate {
  627. //page旋转度数为0度或者180度时,在指定的大小内,能显示的比例
  628. let scale1 = min(pageItemSize.width / originSize.width, pageItemSize.height / originSize.height)
  629. //page旋转度数为90度或者270度时,在指定的大小内,能显示的比例
  630. let scale2 = min(pageItemSize.width / originSize.height, pageItemSize.height / originSize.width)
  631. scale = max(scale1, scale2)
  632. if scale1 > scale2 {
  633. //高为竖直排列时,显示最大,则需将page时90度或者270度需要进行旋转
  634. if rotate == 90 || rotate == 270 {
  635. rotate = rotate - 90
  636. }
  637. } else {
  638. //宽为竖直排列时,显示最大,则需将page时0度或者180度需要进行旋转
  639. if rotate == 0 || rotate == 180 {
  640. rotate = rotate - 90
  641. }
  642. }
  643. } else {
  644. scale = min(pageItemSize.width / originSize.width, pageItemSize.height / originSize.height)
  645. }
  646. return scale
  647. }
  648. func fetchPageLite(pageModel: KMPrintPageModel) {
  649. }
  650. }
  651. protocol KMPrintPresenterPaper {}
  652. extension KMPrintPresenter: KMPrintPresenterPaper {
  653. /**
  654. 获取每张纸的page
  655. @param type 页面类型
  656. @param contentType annoation类型
  657. @param selectPages 当type 为custom时 传入选中page的下标
  658. */
  659. func fetchPageOfPaper(_ pageModel: KMPrintPageModel) -> Int {
  660. var count = 1
  661. switch pageModel.operation.type {
  662. case .multipage:
  663. count = Int(pageModel.operation.pageOfPaper.point.x * pageModel.operation.pageOfPaper.point.y)
  664. case .poster:
  665. count = Int(pageModel.operation.pageOfPaper.point.x * pageModel.operation.pageOfPaper.point.y)
  666. default:
  667. count = 1
  668. }
  669. return count
  670. }
  671. /**
  672. 获取总纸张数
  673. @param pages page总数
  674. @param contentType annoation类型
  675. @param selectPages 当type 为custom时 传入选中page的下标
  676. */
  677. func fetchTotalPaperCount (_ paperSize: CGSize, _ pages: [KMPrintDrawPage], _ pageModel: KMPrintPageModel) -> Int {
  678. var count = 1
  679. let pageOfPaper = self.fetchPageOfPaper(pageModel)
  680. switch pageModel.operation.type {
  681. case .multipage:
  682. count = Int(ceilf(Float(pages.count / pageOfPaper)))
  683. case .poster:
  684. if (pageModel.operation.poster.type == .tile) {
  685. //1 2 4 9 16
  686. let scale = pageModel.operation.poster.scale
  687. let pageSize = pages.first?.page.bounds(for: .cropBox).size ?? paperSize
  688. let point = self.fetchPosterPageCount(paperSize: paperSize, pageSize: pageSize, scale: scale)
  689. pageModel.operation.poster.tilePoint = point
  690. count = Int((point.x * point.y)) * pages.count
  691. } else if (pageModel.operation.poster.type == .breakUp) {
  692. count = Int((pageModel.operation.pageOfPaper.point.x * pageModel.operation.pageOfPaper.point.y)) * pages.count
  693. } else {
  694. count = Int(ceilf(Float(pages.count / pageOfPaper)))
  695. }
  696. default:
  697. count = Int(ceilf(Float(pages.count / pageOfPaper)))
  698. }
  699. return count
  700. }
  701. func fetchPosterPageCount(paperSize: CGSize, pageSize: CGSize, scale: CGFloat) -> CGPoint {
  702. var xCount: Int = 1
  703. var yCount: Int = 1
  704. var contain: Bool = true
  705. while (contain) {
  706. if (pageSize.width * scale < CGFloat(xCount) * paperSize.width &&
  707. pageSize.height * scale < CGFloat(yCount) * paperSize.height) {
  708. contain = false
  709. break
  710. }
  711. //增加行数 和 列数
  712. if xCount == yCount {
  713. xCount += 1
  714. } else {
  715. yCount += 1
  716. }
  717. }
  718. return CGPoint(x: xCount, y: yCount)
  719. }
  720. /**
  721. 获取pages
  722. @param type 页面类型
  723. @param contentType annoation类型
  724. @param selectPages 当type 为custom时 传入选中page的下标
  725. */
  726. func fetchPaperSize(_ paperModel: KMPrintPaperModel) -> CGSize {
  727. var paperSize = KMPrintPaperInfo.KMPaperType.paperSize(type: paperModel.info.type, unit: .px)
  728. let direction = paperModel.direction
  729. if direction == .vertical {
  730. paperSize = CGSize(width: paperSize.width, height: paperSize.height)
  731. } else if direction == .horizontal {
  732. paperSize = CGSize(width: paperSize.height, height: paperSize.width)
  733. }
  734. return paperSize
  735. }
  736. func fetchPaperItemSize(_ paperModel: KMPrintPaperModel) -> CGSize {
  737. var paperSize = self.fetchPaperSize(paperModel)
  738. let paperInset = paperModel.info.inset
  739. paperSize = CGSize(width: paperSize.width - paperInset.left - paperInset.right,
  740. height: paperSize.height - paperInset.bottom - paperInset.top)
  741. return paperSize
  742. }
  743. }
  744. protocol KMPrintPresenterDraw {}
  745. extension KMPrintPresenter: KMPrintPresenterDraw {
  746. // -(void)drawCutMarkContext:(CGContextRef)context contextSize:(CGSize)size
  747. // {
  748. // CGContextSetStrokeColorWithColor(context, [NSColor blackColor].CGColor);
  749. // CGContextSetLineWidth(context, 1.0);
  750. // CGContextSetLineCap(context, kCGLineCapSquare);
  751. //
  752. // if(self.columnIndex == 1 && self.lineIndex == 1) {
  753. // [self drawLeftBottomCutMarks:context size:size];
  754. // [self drawRightTopCutMarks:context size:size];
  755. // [self drawRightBottomCutMarks:context size:size];
  756. // } else if (self.lineIndex == 1 && self.columnIndex == self.vertArray.count) {
  757. // [self drawLeftTopCutMarks:context size:size];
  758. // [self drawRightTopCutMarks:context size:size];
  759. // [self drawRightBottomCutMarks:context size:size];
  760. // } else if (self.columnIndex == 1 && self.lineIndex == self.hourArray.count) {
  761. // [self drawLeftTopCutMarks:context size:size];
  762. // [self drawLeftBottomCutMarks:context size:size];
  763. // [self drawRightBottomCutMarks:context size:size];
  764. // } else if (self.columnIndex == self.vertArray.count && self.hourArray.count == self.lineIndex) {
  765. // [self drawLeftTopCutMarks:context size:size];
  766. // [self drawLeftBottomCutMarks:context size:size];
  767. // [self drawRightTopCutMarks:context size:size];
  768. // } else {
  769. // [self drawLeftTopCutMarks:context size:size];
  770. // [self drawLeftBottomCutMarks:context size:size];
  771. // [self drawRightTopCutMarks:context size:size];
  772. // [self drawRightBottomCutMarks:context size:size];
  773. // }
  774. // //绘制完成
  775. // CGContextStrokePath(context);
  776. // }
  777. //
  778. // //左上角切割标记
  779. // -(void)drawLeftTopCutMarks:(CGContextRef)context size:(CGSize)size
  780. // {
  781. // CGFloat KBlankA4H =size.height;
  782. // CGPoint point_LeftTop = CGPointZero;
  783. //
  784. // if (self.PDFPrint.splitType == kKMPDFPosterSplitType_PageNumber) {
  785. // point_LeftTop.x = self.PDFPrint.fullPageEdgeInsets.left;
  786. // } else {
  787. // point_LeftTop.x = self.PDFPrint.edgeInsets.left;
  788. // }
  789. //
  790. // point_LeftTop.y = KBlankA4H - self.PDFPrint.edgeInsets.top;
  791. //
  792. // CGContextMoveToPoint(context, 10,point_LeftTop.y);
  793. // CGContextAddLineToPoint(context,point_LeftTop.x, point_LeftTop.y);
  794. //
  795. // CGContextMoveToPoint(context, point_LeftTop.x - 10,KBlankA4H -10);
  796. // CGContextAddLineToPoint(context,point_LeftTop.x - 10,point_LeftTop.y);
  797. // }
  798. //
  799. // //右上角切割标记
  800. // -(void)drawRightTopCutMarks:(CGContextRef)context size:(CGSize)size
  801. // {
  802. // CGFloat KBlankA4W =size.width;
  803. // CGFloat KBlankA4H =size.height;
  804. //
  805. // CGPoint point_RightTop = CGPointZero;//右上角
  806. //
  807. // if (self.PDFPrint.splitType == kKMPDFPosterSplitType_PageNumber) {
  808. // point_RightTop.x = KBlankA4W - self.PDFPrint.fullPageEdgeInsets.right;
  809. // point_RightTop.y = KBlankA4H - self.PDFPrint.fullPageEdgeInsets.top;
  810. // } else {
  811. // point_RightTop.x = KBlankA4W - self.PDFPrint.edgeInsets.right;
  812. // point_RightTop.y = KBlankA4H - self.PDFPrint.edgeInsets.top;
  813. // }
  814. //
  815. // CGContextMoveToPoint(context,point_RightTop.x,point_RightTop.y);
  816. // CGContextAddLineToPoint(context,KBlankA4W - 10,point_RightTop.y);
  817. //
  818. // CGContextMoveToPoint(context,point_RightTop.x + 10,KBlankA4H - 10);
  819. // CGContextAddLineToPoint(context,point_RightTop.x + 10,point_RightTop.y);
  820. // }
  821. //
  822. // //左下角切割标记
  823. // -(void)drawLeftBottomCutMarks:(CGContextRef)context size:(CGSize)size
  824. // {
  825. // CGPoint point_LeftBottom = CGPointZero;//左下角
  826. // if (self.PDFPrint.splitType == kKMPDFPosterSplitType_PageNumber) {
  827. // point_LeftBottom.x = self.PDFPrint.fullPageEdgeInsets.left;
  828. // point_LeftBottom.y = self.PDFPrint.fullPageEdgeInsets.bottom;
  829. // } else {
  830. // point_LeftBottom.x = self.PDFPrint.edgeInsets.left;
  831. // point_LeftBottom.y = self.PDFPrint.edgeInsets.bottom;
  832. // }
  833. //
  834. // //左下角
  835. // CGContextMoveToPoint(context, 10,point_LeftBottom.y);
  836. // CGContextAddLineToPoint(context,point_LeftBottom.x, point_LeftBottom.y);
  837. //
  838. // CGContextMoveToPoint(context, point_LeftBottom.x- 10,10);
  839. // CGContextAddLineToPoint(context,point_LeftBottom.x - 10,point_LeftBottom.y);
  840. // }
  841. //
  842. // //右下角切割标记
  843. // -(void)drawRightBottomCutMarks:(CGContextRef)context size:(CGSize)size
  844. // {
  845. // CGFloat KBlankA4W =size.width;
  846. //
  847. // CGPoint point_RightBottom = CGPointZero;//右下角
  848. // if (self.PDFPrint.splitType == kKMPDFPosterSplitType_PageNumber) {
  849. // point_RightBottom.x = KBlankA4W - self.PDFPrint.fullPageEdgeInsets.right;
  850. // point_RightBottom.y = self.PDFPrint.fullPageEdgeInsets.bottom;
  851. // } else {
  852. // point_RightBottom.x = KBlankA4W - self.PDFPrint.edgeInsets.right;
  853. // point_RightBottom.y = self.PDFPrint.edgeInsets.bottom;
  854. // }
  855. //
  856. // CGContextMoveToPoint(context,KBlankA4W - 10,point_RightBottom.y);
  857. // CGContextAddLineToPoint(context,point_RightBottom.x,point_RightBottom.y);
  858. //
  859. // CGContextMoveToPoint(context,point_RightBottom.x+ 10,10);
  860. // CGContextAddLineToPoint(context,point_RightBottom.x+ 10,point_RightBottom.y);
  861. // }
  862. func drawString(_ pageModel: KMPrintPageModel, _ contextSize: CGSize) {
  863. var string = pageModel.operation.poster.tags.first ?? ""
  864. // if string.isEmpty {
  865. // string =
  866. // }
  867. }
  868. //
  869. // - (void)drawLabelTextContextSize:(CGSize)contextSize
  870. // {
  871. // CGFloat KBlankA4W =contextSize.width;
  872. // CGFloat KBlankA4H =contextSize.height;
  873. //
  874. // NSString *contextString = nil;
  875. // if (self.PDFPrint.labelString && self.PDFPrint.labelString.length > 0) {
  876. // contextString = self.PDFPrint.labelString;
  877. // } else {
  878. // NSDate *date = [NSDate date];
  879. // NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
  880. // [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
  881. // contextString = [NSString stringWithFormat:@"(%ld,%ld) %@ %@",self.columnIndex,self.lineIndex,[self.filePath lastPathComponent],[formatter stringFromDate:date]];
  882. // }
  883. //
  884. // CGFloat fontSize = 12.0 * (MAX(KBlankA4W, KBlankA4H)/842);
  885. // NSFont *font = [NSFont systemFontOfSize:fontSize];
  886. // NSColor *color = [NSColor blackColor];
  887. //
  888. // NSSize size = NSZeroSize;
  889. // NSMutableParagraphStyle *style = [[[NSMutableParagraphStyle alloc] init] autorelease];
  890. // [style setAlignment:NSCenterTextAlignment];
  891. // [style setLineBreakMode:NSLineBreakByCharWrapping];
  892. // NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
  893. // [dictionary setObject:style forKey:NSParagraphStyleAttributeName];
  894. // [dictionary setObject:color forKey:NSForegroundColorAttributeName];
  895. // [dictionary setObject:font forKey:NSFontAttributeName];
  896. // size = [contextString boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT)
  897. // options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
  898. // attributes:dictionary].size;
  899. //
  900. // if (self.PDFPrint.splitType == kKMPDFPosterSplitType_PageNumber) {
  901. // [contextString drawInRect:CGRectMake(self.PDFPrint.fullPageEdgeInsets.left +10,
  902. // KBlankA4H - self.PDFPrint.fullPageEdgeInsets.top + size.height,
  903. // size.width, size.height)
  904. // withAttributes:dictionary];
  905. // } else {
  906. // [contextString drawInRect:CGRectMake(self.PDFPrint.edgeInsets.left +10,
  907. // KBlankA4H - self.PDFPrint.edgeInsets.top + size.height,
  908. // size.width, size.height)
  909. // withAttributes:dictionary];
  910. // }
  911. //
  912. // }
  913. }
  914. protocol KMPrintPresenterPrivate {}
  915. extension KMPrintPresenter: KMPrintPresenterPrivate {
  916. func isAnnoationStamp(type: String) -> Bool {
  917. let annotationStamp: [String] = ["Square", "Stamp"]
  918. return annotationStamp.contains(type)
  919. }
  920. func isAnnoationMarkup(type: String) -> Bool {
  921. let annotationStamp: [String] = ["Widget", "Freehand", "Highlight", "Underline", "Squiggly", "Circle", "StrikeOut", "Ink"]
  922. return annotationStamp.contains(type)
  923. }
  924. func isAnnoationForm(type: String) -> Bool {
  925. let annotationStamp: [String] = ["FreeText"]
  926. return annotationStamp.contains(type)
  927. }
  928. }
  929. protocol KMPrintPresenterProtocol: NSObject {
  930. }
  931. ///**
  932. // @abstract 获取context
  933. // @param size纸张大小
  934. // */
  935. //func createContext(_ saveFilePath: String, size: CGSize) -> CGContext {
  936. // let s = CGSize(width: nearbyint(size.width), height: nearbyint(size.height))
  937. // let rep = NSBitmapImageRep.init(bitmapDataPlanes: nil,
  938. // pixelsWide: Int(s.width),
  939. // pixelsHigh: Int(s.height),
  940. // bitsPerSample: 8,
  941. // samplesPerPixel: 4,
  942. // hasAlpha: true,
  943. // isPlanar: false,
  944. // colorSpaceName: NSColorSpaceName.calibratedRGB,
  945. // bytesPerRow: 0,
  946. // bitsPerPixel: 0)!
  947. // let context: CGContext = NSGraphicsContext.init(bitmapImageRep: rep)!.cgContext
  948. // return context
  949. //}