123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285 |
- //
- // KMHeaderFooterPreviewController.swift
- // PDF Master
- //
- // Created by tangchao on 2022/12/26.
- //
- import Cocoa
- /// 页眉页脚 预览控制器
- class KMHeaderFooterPreviewController: KMWatermarkAdjectivePreViewBaseController {
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- let itemTitles = [[NSLocalizedString("Add HeaderAndFooter", comment: ""), NSLocalizedString("Delete HeaderAndFooter", comment: "")], [NSLocalizedString("Batch", comment: "")]]
- var itemModels: Array<Array<KMWatermarkAdjectiveTopBarItemModel>> = []
- for items in itemTitles {
- var array: Array<KMWatermarkAdjectiveTopBarItemModel> = []
- for title in items {
- let model = KMWatermarkAdjectiveTopBarItemModel()
- model.iconName = ""
- model.itemTitle = title
- array.append(model)
- }
- itemModels.append(array)
- }
-
- self.topBarView.initItemData(itemArrays: itemModels)
- self.topBarView.selectTopItem(index: 0)
-
- let preView: KMWatermarkPDFView_OC = KMWatermarkPDFView_OC()
- self.preView = preView
- self.preView.frame = self.preViewBox.contentView!.bounds
- self.preView.autoresizingMask = [.width, .height]
- self.preViewBox.contentView?.addSubview(self.preView)
- self.preView.setDisplay(.singlePage)
-
- let controller = KMHeaderFooterPropertyMainController()
- controller.view.frame = self.rightBox.contentView!.bounds
- controller.view.autoresizingMask = [.width, .height]
- self.right_gotoViewController(viewController: controller)
- controller.modelDidChange = { [weak self] model in
- if (model == nil || (model as! KMHeaderFooterModel).hasVaild == false) {
- self!.topBarView.isCanApply(can: false)
- self!.model = nil
- } else {
- self!.topBarView.isCanApply(can: true)
- self!.model = model
- self?.model?.pageCount = Int((self?.preView.document.pageCount)!)
- }
-
- (self?.preView as! KMWatermarkPDFView_OC).model = model
- }
- }
-
- override func viewDidAppear() {
- super.viewDidAppear()
-
- (self.rightViewController as! KMHeaderFooterPropertyMainController).pageCount = Int(self.preView.document.pageCount)
- }
-
- override func topItemClick(index: Int) {
- if (index == 0) { /// 添加
- return
- }
- if (index == 2) { /// 批量
- KMBatchWindowController.openFile(nil, .HeaderAndFooter)
- return
- }
- if (index == 2) { /// 批量
- KMBatchWindowController.openFile(nil, .HeaderAndFooter)
- return
- }
-
- /// 移除
- self.beginLoading()
- self.deleteHeaderFooter(toPath: self.preView.document.documentURL.path) {
- result in
- self.endLoading()
- if (result) {
- DispatchQueue.main.async {
- self.preView.document = CPDFDocument(url: self.preView.document.documentURL)
- }
- } else {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("Failure", comment: "")
- alert.runModal()
- }
- }
- }
-
- override func applyAction() {
- if (self.model == nil) {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("Failure", comment: "")
- alert.runModal()
- return
- }
- self.beginLoading()
- self.addHeaderFooter(model: self.model! as! KMHeaderFooterModel, toPath: self.preView.document.documentURL.path, completion: {
- result in
- DispatchQueue.main.async {
- self.preView.layoutDocumentView()
- self.preView.setNeedsDisplayForVisiblePages()
- }
- self.endLoading()
- if (result) {
- guard let callback = self.itemClick else {
- return
- }
- callback(1, nil)
- } else {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("Failure", comment: "")
- alert.runModal()
- }
- })
- }
-
- private func addHeaderFooter(model: KMHeaderFooterModel, toPath: String, completion: @escaping (_ result: Bool) -> ()) {
- DispatchQueue.global().async {
- let document: CPDFDocument = self.preView.document
- var property = document.headerFooter()
-
- var fontSize = 0.0
- var fontName: String = ""
- switch model.textFont {
- case .font(name: let name, size: let size):
- fontSize = size
- fontName = name
- break
- default:
- break
- }
-
- let font = NSFont.boldSystemFont(ofSize:fontSize)
- let style = NSMutableParagraphStyle()
- style.alignment = .center
- style.lineBreakMode = .byCharWrapping
- let size: NSSize = "text".boundingRect(with: NSSize(width: 1000, height: 1000), options: NSString.DrawingOptions(rawValue: 3), attributes: [NSAttributedString.Key.font : font, NSAttributedString.Key.paragraphStyle : style]).size
-
- property?.margin = NSEdgeInsetsMake(max(model.topMargin-size.height, 0), model.leftMargin, max(model.bottomMargin-size.height, 0), model.rightMargin)
-
- let strings = KMHeaderFooterPreviewController.parseModel(model: model, pageCount: Int(self.preView.document.pageCount))
- var count: Int = 0
-
- var color: NSColor!
- switch model.textColor {
- case .color(red: let red, green: let green, blue: let blue, alpha: let alpha):
- color = NSColor(red: red, green: green, blue: blue, alpha: alpha)
- default:
- break
- }
-
- if (color == nil) {
- color = NSColor.black
- }
-
- for text in strings {
- property?.setText(text, at: UInt(count))
- property?.setTextColor(color, at: UInt(count))
- property?.setFontSize(fontSize, at: UInt(count))
- property?.setFontName(fontName, at: UInt(count))
- count += 1
- }
- let pagesString = self.findPagesString(model)
- if (pagesString.isEmpty) {
- property?.pageString = "0-\(document.pageCount-1)"
- } else {
- property?.pageString = pagesString
- }
-
- property?.update()
-
- /// 保存到临时路径
- let documentPath = NSTemporaryDirectory()
- let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
- if (FileManager.default.fileExists(atPath: tempPath)) {
- try?FileManager.default.removeItem(atPath: tempPath)
- }
-
- let result = document.write(to: URL(fileURLWithPath: tempPath))
- if (result) {
- if (FileManager.default.fileExists(atPath: toPath)) {
- try?FileManager.default.removeItem(atPath: toPath)
- }
-
- try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
- } else {
- try?FileManager.default.removeItem(atPath: tempPath)
- }
-
- DispatchQueue.main.async {
- completion(result)
- }
- }
- }
-
- func deleteHeaderFooter(toPath: String, completion: @escaping (_ result: Bool) -> ()) {
- if (self.preView.document.allowsPrinting == false || self.preView.document.allowsCopying == false) {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("This PDF document's user permissions does not allow modifying, content copying and printing.", comment: "")
- alert.runModal()
-
- completion(false)
- return
- }
-
- DispatchQueue.global().async {
- let document: CPDFDocument = self.preView.document
- var property = document.headerFooter()
- property?.clear()
-
- /// 保存到临时路径
- let documentPath = NSTemporaryDirectory()
- let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
- if (FileManager.default.fileExists(atPath: tempPath)) {
- try?FileManager.default.removeItem(atPath: tempPath)
- }
-
- let result = document.write(to: URL(fileURLWithPath: tempPath))
- if (result) {
- if (FileManager.default.fileExists(atPath: toPath)) {
- try?FileManager.default.removeItem(atPath: toPath)
- }
-
- try?FileManager.default.moveItem(atPath: tempPath, toPath: toPath)
- } else {
- try?FileManager.default.removeItem(atPath: tempPath)
- }
-
- DispatchQueue.main.async {
- completion(result)
- }
- }
- }
-
- static func parseModel(model: KMHeaderFooterModel, pageCount: Int) -> [String] {
- var topLeftString: String = ""
- if (!model.topLeftString.isEmpty) {
- var string = KMWatermarkAdjectiveTools.parsePageFormat(formatString: model.topLeftString, startPage: model.startString, pageCount: "\(pageCount)")
- string = KMWatermarkAdjectiveTools.parseDateFormat(formatString: string)
- topLeftString = string
- }
-
- var topCenterString: String = ""
- if (!model.topCenterString.isEmpty) {
- var string = KMWatermarkAdjectiveTools.parsePageFormat(formatString: model.topCenterString, startPage: model.startString, pageCount: "\(pageCount)")
- string = KMWatermarkAdjectiveTools.parseDateFormat(formatString: string)
- topCenterString = string
- }
-
- var topRightString: String = ""
- if (!model.topRightString.isEmpty) {
- var string = KMWatermarkAdjectiveTools.parsePageFormat(formatString: model.topRightString, startPage: model.startString, pageCount: "\(pageCount)")
- string = KMWatermarkAdjectiveTools.parseDateFormat(formatString: string)
- topRightString = string
- }
-
- var bottomLeftString: String = ""
- if (!model.bottomLeftString.isEmpty) {
- var string = KMWatermarkAdjectiveTools.parsePageFormat(formatString: model.bottomLeftString, startPage: model.startString, pageCount: "\(pageCount)")
- string = KMWatermarkAdjectiveTools.parseDateFormat(formatString: string)
- bottomLeftString = string
- }
- var bottomCenterString: String = ""
- if (!model.bottomCenterString.isEmpty) {
- var string = KMWatermarkAdjectiveTools.parsePageFormat(formatString: model.bottomCenterString, startPage: model.startString, pageCount: "\(pageCount)")
- string = KMWatermarkAdjectiveTools.parseDateFormat(formatString: string)
- bottomCenterString = string
- }
- var bottomRightString: String = ""
- if (!model.bottomRightString.isEmpty) {
- var string = KMWatermarkAdjectiveTools.parsePageFormat(formatString: model.bottomRightString, startPage: model.startString, pageCount: "\(pageCount)")
- string = KMWatermarkAdjectiveTools.parseDateFormat(formatString: string)
- bottomRightString = string
- }
-
- return [topLeftString, topCenterString, topRightString, bottomLeftString, bottomCenterString, bottomRightString]
- }
- }
|