KMPrintPresenter.swift 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  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.poster.pageOfPaper.point.x * pageModel.operation.poster.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 = true //是否存在边框
  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: 2, y: 2) //行 列之间的空间
  313. for i in 0...Int(columnAndRow.x) - 1 {
  314. for j in 0...(Int(columnAndRow.y) - 1) {
  315. let index = j + i * Int(columnAndRow.x)
  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(j) + paperInset.left + center.x
  345. //页面内容高度 + 下边的行间距 - 第几个cell的高度 +居中
  346. origin.y = paperSize.height - (pageSize.height + columnAndRowSpace.y) * (CGFloat(i) + 1) + center.y + columnAndRowSpace.y
  347. case .horizontalReverseSequence:
  348. origin.x = paperSize.width - (pageSize.width + columnAndRowSpace.x) * (CGFloat(j) + 1) + center.x + columnAndRowSpace.x
  349. origin.y = paperSize.height - (pageSize.height + columnAndRowSpace.y) * (CGFloat(i) + 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.saveGraphicsState()
  362. //平移
  363. context.translateBy(x: origin.x, y: origin.y)
  364. //缩放
  365. context.scaleBy(x: CGFloat(scale), y: CGFloat(scale))
  366. page.page.draw(with: PDFDisplayBox.cropBox, to: context)
  367. // page.transform(context, for: PDFDisplayBox.cropBox)
  368. if border {
  369. var dirtyRect = rect
  370. if rotate == 90 ||
  371. rotate == 270 {
  372. dirtyRect = NSMakeRect(dirtyRect.origin.x, dirtyRect.origin.y, dirtyRect.size.height, dirtyRect.size.width)
  373. }
  374. context.addRect(dirtyRect)
  375. context.setStrokeColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
  376. context.strokePath()
  377. }
  378. NSGraphicsContext.restoreGraphicsState()
  379. // page.setBounds(NSRect(x: 0, y: 0, width: pageRect.size.width, height: pageRect.size.height), for: .cropBox)
  380. }
  381. }
  382. }
  383. }
  384. func drawLabelTextContextSize(context: CGContext) {
  385. let pageSize = CGSize(width: 0, height: 0)
  386. let KBlankA4W = pageSize.width
  387. let KBlankA4H = pageSize.height
  388. var contextString: String
  389. // if let labelString = PDFPrint.labelString, !labelString.isEmpty {
  390. // contextString = labelString
  391. // } else {
  392. let date = Date()
  393. let formatter = DateFormatter()
  394. formatter.dateFormat = "YYYY-MM-dd hh:mm:ss"
  395. contextString = "(\("1"),\("1")) \("filePath.lastPathComponent") \(formatter.string(from: date))"
  396. // }
  397. let fontSize = 12.0 * (max(KBlankA4W, KBlankA4H) / 842)
  398. let font = NSFont.systemFont(ofSize: fontSize)
  399. let color = NSColor.black
  400. var size = NSSize.zero
  401. var style = NSMutableParagraphStyle()
  402. style.alignment = .center
  403. style.lineBreakMode = .byCharWrapping
  404. var attributes = [NSAttributedString.Key: Any]()
  405. attributes[.paragraphStyle] = style
  406. attributes[.foregroundColor] = color
  407. attributes[.font] = font
  408. size = contextString.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude),
  409. options: [.usesLineFragmentOrigin, .usesFontLeading],
  410. attributes: attributes).size
  411. // if PDFPrint.splitType == .pageNumber {
  412. contextString.draw(in: CGRect(x: 10 + 10,
  413. y: KBlankA4H - 10 + size.height,
  414. width: size.width, height: size.height),
  415. withAttributes: attributes)
  416. // } else {
  417. // contextString.draw(in: CGRect(x: PDFPrint.edgeInsets.left + 10,
  418. // y: KBlankA4H - PDFPrint.edgeInsets.top + size.height,
  419. // width: size.width, height: size.height),
  420. // withAttributes: attributes)
  421. // }
  422. }
  423. }
  424. protocol KMPrintPresenterPage {}
  425. extension KMPrintPresenter: KMPrintPresenterPage {
  426. /**
  427. 获取pages
  428. @param type 页面类型
  429. @param contentType annoation类型
  430. @param selectPages 当type 为custom时 传入选中page的下标
  431. */
  432. func fetchPageCropRect(_ paperSize: CGSize, _ index: Int, _ pageModel: KMPrintPageModel, _ page: KMPrintDrawPage) -> CGRect {
  433. var newRect = page.page.bounds(for: .cropBox)
  434. if (pageModel.operation.type == .poster) {
  435. let originSize = newRect.size
  436. var cropPoint = CGPoint(x: 1, y: 1)
  437. var scale = 1.0
  438. if (pageModel.operation.poster.type == .tile) {
  439. cropPoint = pageModel.operation.poster.tilePoint
  440. // scale = pageModel.operation.poster.scale
  441. } else if (pageModel.operation.poster.type == .breakUp) {
  442. cropPoint = pageModel.operation.poster.pageOfPaper.point
  443. }
  444. let width = originSize.width / cropPoint.x
  445. let height = originSize.height / cropPoint.y
  446. let column: Int = Int(cropPoint.x) //行
  447. let row: Int = Int(cropPoint.y) //列
  448. for i in 0...column - 1 {
  449. for j in 0...row - 1 {
  450. if i + j + i * (row - 1) == index {
  451. newRect.origin.x = CGFloat(i) * width * scale
  452. newRect.origin.y = ((originSize.height - CGFloat(j) * height - height)) * scale
  453. newRect.size.width = width * scale
  454. newRect.size.height = height * scale
  455. return newRect
  456. }
  457. }
  458. }
  459. }
  460. return newRect
  461. }
  462. func fetchPageShowRect(_ paperSize: CGSize, _ index: Int, _ pageModel: KMPrintPageModel, _ page: KMPrintDrawPage) -> CGRect {
  463. var newRect = NSZeroRect
  464. var pageRect = CGRect(x: 0, y: 0, width: paperSize.width, height: paperSize.height)
  465. if (pageModel.operation.type == .poster) {
  466. let pageSize = page.page.bounds(for: .cropBox)
  467. var cropPoint = CGPoint(x: 1, y: 1)
  468. var scale = 1.0
  469. if (pageModel.operation.poster.type == .tile) {
  470. cropPoint = pageModel.operation.poster.tilePoint
  471. scale = pageModel.operation.poster.scale
  472. } else if (pageModel.operation.poster.type == .breakUp) {
  473. cropPoint = pageModel.operation.poster.pageOfPaper.point
  474. }
  475. if (cropPoint.x == 1 && cropPoint.y == 1) {
  476. } else {
  477. let originPaperSize = CGSize(width: paperSize.width * cropPoint.x, height: paperSize.height * cropPoint.y)
  478. let pageWidth = pageSize.width * scale
  479. let pageHeight = pageSize.height * scale
  480. let pageOrigin = CGPoint(x: (originPaperSize.width - pageWidth) / 2, y: (originPaperSize.height - pageHeight) / 2)
  481. let width = originPaperSize.width / cropPoint.x
  482. let height = originPaperSize.height / cropPoint.y
  483. let column: Int = Int(cropPoint.x) //行
  484. let row: Int = Int(cropPoint.y) //列
  485. for i in 0...column - 1 {
  486. for j in 0...row - 1 {
  487. if i + j + i * (row - 1) == index {
  488. newRect.origin.x = CGFloat(i) * width
  489. newRect.origin.y = ((originPaperSize.height - CGFloat(j) * height - height))
  490. newRect.size.width = width
  491. newRect.size.height = height
  492. if (pageOrigin.x > newRect.origin.x) {
  493. pageRect.origin.x = pageOrigin.x
  494. pageRect.size.width = newRect.size.width - pageOrigin.x
  495. } else if (originPaperSize.width - pageOrigin.x > newRect.origin.x) {
  496. pageRect.origin.x = 0
  497. pageRect.size.width = newRect.size.width - pageOrigin.x
  498. } else {
  499. pageRect.origin.x = 0
  500. pageRect.size.width = newRect.size.width
  501. }
  502. if (originPaperSize.height - pageOrigin.y < newRect.origin.y + newRect.size.height) {
  503. pageRect.origin.y = 0
  504. pageRect.size.height = newRect.size.height - pageOrigin.y
  505. } else if (pageOrigin.y > newRect.origin.y) {
  506. pageRect.origin.y = pageOrigin.y
  507. pageRect.size.height = newRect.size.height - pageOrigin.y
  508. } else {
  509. pageRect.origin.y = newRect.origin.y - pageOrigin.y
  510. pageRect.size.height = newRect.size.height
  511. }
  512. return pageRect
  513. }
  514. }
  515. }
  516. }
  517. }
  518. return pageRect
  519. }
  520. func fetchPageColumnAndRow(_ pageModel: KMPrintPageModel) -> CGPoint {
  521. var point = NSZeroPoint
  522. let pageOrder: KMPrintPageOperation.Multipage.Order = pageModel.operation.multipage.orderType //页面顺序
  523. switch pageModel.operation.type {
  524. case .multipage:
  525. point.x = pageModel.operation.multipage.pageOfPaper.point.x
  526. point.y = pageModel.operation.multipage.pageOfPaper.point.y
  527. default:
  528. point.x = 1
  529. point.y = 1
  530. }
  531. //如果是横向参数需切换
  532. if pageOrder == .horizontal ||
  533. pageOrder == .horizontalReverseSequence {
  534. let temp = point.x
  535. point.x = point.y
  536. point.y = temp
  537. }
  538. return point
  539. }
  540. func fetchAutoRotate(_ pageModel: KMPrintPageModel) -> Bool {
  541. var autoRotate = false
  542. switch pageModel.operation.type {
  543. case .multipage:
  544. autoRotate = pageModel.operation.multipage.isAutoRotate
  545. case .pamphlet:
  546. autoRotate = pageModel.operation.pamphlet.isAutoRotate
  547. default:
  548. autoRotate = false
  549. }
  550. return autoRotate
  551. }
  552. func fetchAutoSize(_ pageModel: KMPrintPageModel) -> Bool {
  553. var autoSize = false
  554. switch pageModel.operation.type {
  555. case .size:
  556. autoSize = true
  557. default:
  558. autoSize = false
  559. }
  560. return autoSize
  561. }
  562. func fetchShowModel(_ pageModel: KMPrintPageModel) -> KMPrintPageOperation.Size {
  563. var model = KMPrintPageOperation.Size()
  564. switch pageModel.operation.type {
  565. case .size:
  566. model = pageModel.operation.size
  567. default:
  568. model = KMPrintPageOperation.Size()
  569. }
  570. return model
  571. }
  572. func fetchPageItemSize(_ pageModel: KMPrintPageModel, _ paperSize: CGSize) -> CGSize {
  573. var size = NSZeroSize
  574. let columnAndRow = self.fetchPageColumnAndRow(pageModel) //行 列数量
  575. let columnAndRowSpace = CGPoint(x: 2, y: 2) //行 列之间的空间
  576. //page大小
  577. size = CGSize(width: (paperSize.width - CGFloat((columnAndRow.x - 1)) * CGFloat(columnAndRowSpace.x)) / columnAndRow.x,
  578. height: (paperSize.height - CGFloat((columnAndRow.y - 1)) * CGFloat(columnAndRowSpace.y)) / columnAndRow.y)
  579. return size
  580. }
  581. func fetchPageScale(_ page: KMPrintDrawPage, _ pageItemSize: CGSize, _ autoRotate: Bool, _ autoSize: Bool) -> CGFloat {
  582. var scale = 1.0
  583. let originSize = page.page.bounds(for: .cropBox)
  584. var rotate = page.page.rotation
  585. //取出page横竖时能显示的最大Rect
  586. if autoRotate {
  587. //page旋转度数为0度或者180度时,在指定的大小内,能显示的比例
  588. let scale1 = min(pageItemSize.width / originSize.width, pageItemSize.height / originSize.height)
  589. //page旋转度数为90度或者270度时,在指定的大小内,能显示的比例
  590. let scale2 = min(pageItemSize.width / originSize.height, pageItemSize.height / originSize.width)
  591. scale = max(scale1, scale2)
  592. if scale1 > scale2 {
  593. //高为竖直排列时,显示最大,则需将page时90度或者270度需要进行旋转
  594. if rotate == 90 || rotate == 270 {
  595. rotate = rotate - 90
  596. }
  597. } else {
  598. //宽为竖直排列时,显示最大,则需将page时0度或者180度需要进行旋转
  599. if rotate == 0 || rotate == 180 {
  600. rotate = rotate - 90
  601. }
  602. }
  603. } else {
  604. scale = min(pageItemSize.width / originSize.width, pageItemSize.height / originSize.height)
  605. }
  606. if (autoSize) {
  607. } else {
  608. scale = min(scale, 1)
  609. }
  610. return scale
  611. }
  612. func fetchPageRotate(_ page: KMPrintDrawPage, _ pageItemSize: CGSize, _ autoRotate: Bool) -> CGFloat {
  613. var scale = 1.0
  614. let originSize = page.page.bounds(for: .cropBox)
  615. var rotate = page.page.rotation
  616. //取出page横竖时能显示的最大Rect
  617. if autoRotate {
  618. //page旋转度数为0度或者180度时,在指定的大小内,能显示的比例
  619. let scale1 = min(pageItemSize.width / originSize.width, pageItemSize.height / originSize.height)
  620. //page旋转度数为90度或者270度时,在指定的大小内,能显示的比例
  621. let scale2 = min(pageItemSize.width / originSize.height, pageItemSize.height / originSize.width)
  622. scale = max(scale1, scale2)
  623. if scale1 > scale2 {
  624. //高为竖直排列时,显示最大,则需将page时90度或者270度需要进行旋转
  625. if rotate == 90 || rotate == 270 {
  626. rotate = rotate - 90
  627. }
  628. } else {
  629. //宽为竖直排列时,显示最大,则需将page时0度或者180度需要进行旋转
  630. if rotate == 0 || rotate == 180 {
  631. rotate = rotate - 90
  632. }
  633. }
  634. } else {
  635. scale = min(pageItemSize.width / originSize.width, pageItemSize.height / originSize.height)
  636. }
  637. return scale
  638. }
  639. func fetchPageLite(pageModel: KMPrintPageModel) {
  640. }
  641. }
  642. protocol KMPrintPresenterPaper {}
  643. extension KMPrintPresenter: KMPrintPresenterPaper {
  644. /**
  645. 获取每张纸的page
  646. @param type 页面类型
  647. @param contentType annoation类型
  648. @param selectPages 当type 为custom时 传入选中page的下标
  649. */
  650. func fetchPageOfPaper(_ pageModel: KMPrintPageModel) -> Int {
  651. var count = 1
  652. switch pageModel.operation.type {
  653. case .multipage:
  654. count = Int(pageModel.operation.multipage.pageOfPaper.point.x * pageModel.operation.multipage.pageOfPaper.point.y)
  655. case .poster:
  656. count = Int(pageModel.operation.multipage.pageOfPaper.point.x * pageModel.operation.multipage.pageOfPaper.point.y)
  657. default:
  658. count = 1
  659. }
  660. return count
  661. }
  662. /**
  663. 获取总纸张数
  664. @param pages page总数
  665. @param contentType annoation类型
  666. @param selectPages 当type 为custom时 传入选中page的下标
  667. */
  668. func fetchTotalPaperCount (_ paperSize: CGSize, _ pages: [KMPrintDrawPage], _ pageModel: KMPrintPageModel) -> Int {
  669. var count = 1
  670. let pageOfPaper = self.fetchPageOfPaper(pageModel)
  671. switch pageModel.operation.type {
  672. case .multipage:
  673. count = Int(ceilf(Float(pages.count / pageOfPaper)))
  674. case .poster:
  675. if (pageModel.operation.poster.type == .tile) {
  676. //1 2 4 9 16
  677. let scale = pageModel.operation.poster.scale
  678. let pageSize = pages.first?.page.bounds(for: .cropBox).size ?? paperSize
  679. let point = self.fetchPosterPageCount(paperSize: paperSize, pageSize: pageSize, scale: scale)
  680. pageModel.operation.poster.tilePoint = point
  681. count = Int((point.x * point.y)) * pages.count
  682. } else if (pageModel.operation.poster.type == .breakUp) {
  683. count = Int((pageModel.operation.poster.pageOfPaper.point.x * pageModel.operation.poster.pageOfPaper.point.y)) * pages.count
  684. } else {
  685. count = Int(ceilf(Float(pages.count / pageOfPaper)))
  686. }
  687. default:
  688. count = Int(ceilf(Float(pages.count / pageOfPaper)))
  689. }
  690. return count
  691. }
  692. func fetchPosterPageCount(paperSize: CGSize, pageSize: CGSize, scale: CGFloat) -> CGPoint {
  693. var xCount: Int = 1
  694. var yCount: Int = 1
  695. var contain: Bool = true
  696. while (contain) {
  697. if (pageSize.width * scale < CGFloat(xCount) * paperSize.width &&
  698. pageSize.height * scale < CGFloat(yCount) * paperSize.height) {
  699. contain = false
  700. break
  701. }
  702. //增加行数 和 列数
  703. if xCount == yCount {
  704. xCount += 1
  705. } else {
  706. yCount += 1
  707. }
  708. }
  709. return CGPoint(x: xCount, y: yCount)
  710. }
  711. /**
  712. 获取pages
  713. @param type 页面类型
  714. @param contentType annoation类型
  715. @param selectPages 当type 为custom时 传入选中page的下标
  716. */
  717. func fetchPaperSize(_ paperModel: KMPrintPaperModel) -> CGSize {
  718. var paperSize = paperModel.info.size
  719. let direction = paperModel.direction
  720. if direction == .vertical {
  721. paperSize = CGSize(width: paperModel.info.size.width, height: paperModel.info.size.height)
  722. } else if direction == .horizontal {
  723. paperSize = CGSize(width: paperModel.info.size.height, height: paperModel.info.size.width)
  724. }
  725. return paperSize
  726. }
  727. func fetchPaperItemSize(_ paperModel: KMPrintPaperModel) -> CGSize {
  728. var paperSize = self.fetchPaperSize(paperModel)
  729. let paperInset = paperModel.info.inset
  730. paperSize = CGSize(width: paperSize.width - paperInset.left - paperInset.right,
  731. height: paperSize.height - paperInset.bottom - paperInset.top)
  732. return paperSize
  733. }
  734. }
  735. protocol KMPrintPresenterDraw {}
  736. extension KMPrintPresenter: KMPrintPresenterDraw {
  737. // -(void)drawCutMarkContext:(CGContextRef)context contextSize:(CGSize)size
  738. // {
  739. // CGContextSetStrokeColorWithColor(context, [NSColor blackColor].CGColor);
  740. // CGContextSetLineWidth(context, 1.0);
  741. // CGContextSetLineCap(context, kCGLineCapSquare);
  742. //
  743. // if(self.columnIndex == 1 && self.lineIndex == 1) {
  744. // [self drawLeftBottomCutMarks:context size:size];
  745. // [self drawRightTopCutMarks:context size:size];
  746. // [self drawRightBottomCutMarks:context size:size];
  747. // } else if (self.lineIndex == 1 && self.columnIndex == self.vertArray.count) {
  748. // [self drawLeftTopCutMarks:context size:size];
  749. // [self drawRightTopCutMarks:context size:size];
  750. // [self drawRightBottomCutMarks:context size:size];
  751. // } else if (self.columnIndex == 1 && self.lineIndex == self.hourArray.count) {
  752. // [self drawLeftTopCutMarks:context size:size];
  753. // [self drawLeftBottomCutMarks:context size:size];
  754. // [self drawRightBottomCutMarks:context size:size];
  755. // } else if (self.columnIndex == self.vertArray.count && self.hourArray.count == self.lineIndex) {
  756. // [self drawLeftTopCutMarks:context size:size];
  757. // [self drawLeftBottomCutMarks:context size:size];
  758. // [self drawRightTopCutMarks:context size:size];
  759. // } else {
  760. // [self drawLeftTopCutMarks:context size:size];
  761. // [self drawLeftBottomCutMarks:context size:size];
  762. // [self drawRightTopCutMarks:context size:size];
  763. // [self drawRightBottomCutMarks:context size:size];
  764. // }
  765. // //绘制完成
  766. // CGContextStrokePath(context);
  767. // }
  768. //
  769. // //左上角切割标记
  770. // -(void)drawLeftTopCutMarks:(CGContextRef)context size:(CGSize)size
  771. // {
  772. // CGFloat KBlankA4H =size.height;
  773. // CGPoint point_LeftTop = CGPointZero;
  774. //
  775. // if (self.PDFPrint.splitType == kKMPDFPosterSplitType_PageNumber) {
  776. // point_LeftTop.x = self.PDFPrint.fullPageEdgeInsets.left;
  777. // } else {
  778. // point_LeftTop.x = self.PDFPrint.edgeInsets.left;
  779. // }
  780. //
  781. // point_LeftTop.y = KBlankA4H - self.PDFPrint.edgeInsets.top;
  782. //
  783. // CGContextMoveToPoint(context, 10,point_LeftTop.y);
  784. // CGContextAddLineToPoint(context,point_LeftTop.x, point_LeftTop.y);
  785. //
  786. // CGContextMoveToPoint(context, point_LeftTop.x - 10,KBlankA4H -10);
  787. // CGContextAddLineToPoint(context,point_LeftTop.x - 10,point_LeftTop.y);
  788. // }
  789. //
  790. // //右上角切割标记
  791. // -(void)drawRightTopCutMarks:(CGContextRef)context size:(CGSize)size
  792. // {
  793. // CGFloat KBlankA4W =size.width;
  794. // CGFloat KBlankA4H =size.height;
  795. //
  796. // CGPoint point_RightTop = CGPointZero;//右上角
  797. //
  798. // if (self.PDFPrint.splitType == kKMPDFPosterSplitType_PageNumber) {
  799. // point_RightTop.x = KBlankA4W - self.PDFPrint.fullPageEdgeInsets.right;
  800. // point_RightTop.y = KBlankA4H - self.PDFPrint.fullPageEdgeInsets.top;
  801. // } else {
  802. // point_RightTop.x = KBlankA4W - self.PDFPrint.edgeInsets.right;
  803. // point_RightTop.y = KBlankA4H - self.PDFPrint.edgeInsets.top;
  804. // }
  805. //
  806. // CGContextMoveToPoint(context,point_RightTop.x,point_RightTop.y);
  807. // CGContextAddLineToPoint(context,KBlankA4W - 10,point_RightTop.y);
  808. //
  809. // CGContextMoveToPoint(context,point_RightTop.x + 10,KBlankA4H - 10);
  810. // CGContextAddLineToPoint(context,point_RightTop.x + 10,point_RightTop.y);
  811. // }
  812. //
  813. // //左下角切割标记
  814. // -(void)drawLeftBottomCutMarks:(CGContextRef)context size:(CGSize)size
  815. // {
  816. // CGPoint point_LeftBottom = CGPointZero;//左下角
  817. // if (self.PDFPrint.splitType == kKMPDFPosterSplitType_PageNumber) {
  818. // point_LeftBottom.x = self.PDFPrint.fullPageEdgeInsets.left;
  819. // point_LeftBottom.y = self.PDFPrint.fullPageEdgeInsets.bottom;
  820. // } else {
  821. // point_LeftBottom.x = self.PDFPrint.edgeInsets.left;
  822. // point_LeftBottom.y = self.PDFPrint.edgeInsets.bottom;
  823. // }
  824. //
  825. // //左下角
  826. // CGContextMoveToPoint(context, 10,point_LeftBottom.y);
  827. // CGContextAddLineToPoint(context,point_LeftBottom.x, point_LeftBottom.y);
  828. //
  829. // CGContextMoveToPoint(context, point_LeftBottom.x- 10,10);
  830. // CGContextAddLineToPoint(context,point_LeftBottom.x - 10,point_LeftBottom.y);
  831. // }
  832. //
  833. // //右下角切割标记
  834. // -(void)drawRightBottomCutMarks:(CGContextRef)context size:(CGSize)size
  835. // {
  836. // CGFloat KBlankA4W =size.width;
  837. //
  838. // CGPoint point_RightBottom = CGPointZero;//右下角
  839. // if (self.PDFPrint.splitType == kKMPDFPosterSplitType_PageNumber) {
  840. // point_RightBottom.x = KBlankA4W - self.PDFPrint.fullPageEdgeInsets.right;
  841. // point_RightBottom.y = self.PDFPrint.fullPageEdgeInsets.bottom;
  842. // } else {
  843. // point_RightBottom.x = KBlankA4W - self.PDFPrint.edgeInsets.right;
  844. // point_RightBottom.y = self.PDFPrint.edgeInsets.bottom;
  845. // }
  846. //
  847. // CGContextMoveToPoint(context,KBlankA4W - 10,point_RightBottom.y);
  848. // CGContextAddLineToPoint(context,point_RightBottom.x,point_RightBottom.y);
  849. //
  850. // CGContextMoveToPoint(context,point_RightBottom.x+ 10,10);
  851. // CGContextAddLineToPoint(context,point_RightBottom.x+ 10,point_RightBottom.y);
  852. // }
  853. func drawString(_ pageModel: KMPrintPageModel, _ contextSize: CGSize) {
  854. var string = pageModel.operation.poster.tags.first ?? ""
  855. // if string.isEmpty {
  856. // string =
  857. // }
  858. }
  859. //
  860. // - (void)drawLabelTextContextSize:(CGSize)contextSize
  861. // {
  862. // CGFloat KBlankA4W =contextSize.width;
  863. // CGFloat KBlankA4H =contextSize.height;
  864. //
  865. // NSString *contextString = nil;
  866. // if (self.PDFPrint.labelString && self.PDFPrint.labelString.length > 0) {
  867. // contextString = self.PDFPrint.labelString;
  868. // } else {
  869. // NSDate *date = [NSDate date];
  870. // NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
  871. // [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
  872. // contextString = [NSString stringWithFormat:@"(%ld,%ld) %@ %@",self.columnIndex,self.lineIndex,[self.filePath lastPathComponent],[formatter stringFromDate:date]];
  873. // }
  874. //
  875. // CGFloat fontSize = 12.0 * (MAX(KBlankA4W, KBlankA4H)/842);
  876. // NSFont *font = [NSFont systemFontOfSize:fontSize];
  877. // NSColor *color = [NSColor blackColor];
  878. //
  879. // NSSize size = NSZeroSize;
  880. // NSMutableParagraphStyle *style = [[[NSMutableParagraphStyle alloc] init] autorelease];
  881. // [style setAlignment:NSCenterTextAlignment];
  882. // [style setLineBreakMode:NSLineBreakByCharWrapping];
  883. // NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
  884. // [dictionary setObject:style forKey:NSParagraphStyleAttributeName];
  885. // [dictionary setObject:color forKey:NSForegroundColorAttributeName];
  886. // [dictionary setObject:font forKey:NSFontAttributeName];
  887. // size = [contextString boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT)
  888. // options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
  889. // attributes:dictionary].size;
  890. //
  891. // if (self.PDFPrint.splitType == kKMPDFPosterSplitType_PageNumber) {
  892. // [contextString drawInRect:CGRectMake(self.PDFPrint.fullPageEdgeInsets.left +10,
  893. // KBlankA4H - self.PDFPrint.fullPageEdgeInsets.top + size.height,
  894. // size.width, size.height)
  895. // withAttributes:dictionary];
  896. // } else {
  897. // [contextString drawInRect:CGRectMake(self.PDFPrint.edgeInsets.left +10,
  898. // KBlankA4H - self.PDFPrint.edgeInsets.top + size.height,
  899. // size.width, size.height)
  900. // withAttributes:dictionary];
  901. // }
  902. //
  903. // }
  904. }
  905. protocol KMPrintPresenterPrivate {}
  906. extension KMPrintPresenter: KMPrintPresenterPrivate {
  907. func isAnnoationStamp(type: String) -> Bool {
  908. let annotationStamp: [String] = ["Square", "Stamp"]
  909. return annotationStamp.contains(type)
  910. }
  911. func isAnnoationMarkup(type: String) -> Bool {
  912. let annotationStamp: [String] = ["Widget", "Freehand", "Highlight", "Underline", "Squiggly", "Circle", "StrikeOut", "Ink"]
  913. return annotationStamp.contains(type)
  914. }
  915. func isAnnoationForm(type: String) -> Bool {
  916. let annotationStamp: [String] = ["FreeText"]
  917. return annotationStamp.contains(type)
  918. }
  919. }
  920. protocol KMPrintPresenterProtocol: NSObject {
  921. }
  922. ///**
  923. // @abstract 获取context
  924. // @param size纸张大小
  925. // */
  926. //func createContext(_ saveFilePath: String, size: CGSize) -> CGContext {
  927. // let s = CGSize(width: nearbyint(size.width), height: nearbyint(size.height))
  928. // let rep = NSBitmapImageRep.init(bitmapDataPlanes: nil,
  929. // pixelsWide: Int(s.width),
  930. // pixelsHigh: Int(s.height),
  931. // bitsPerSample: 8,
  932. // samplesPerPixel: 4,
  933. // hasAlpha: true,
  934. // isPlanar: false,
  935. // colorSpaceName: NSColorSpaceName.calibratedRGB,
  936. // bytesPerRow: 0,
  937. // bitsPerPixel: 0)!
  938. // let context: CGContext = NSGraphicsContext.init(bitmapImageRep: rep)!.cgContext
  939. // return context
  940. //}