Browse Source

【UI替换】编辑工具 - 添加水印功能完善

lizhe 1 year ago
parent
commit
56095eab12

+ 2 - 2
PDF Office/PDF Master/Class/PDFTools/Watermark/Base/KMWatermarkAdjectiveBaseModel.swift

@@ -58,7 +58,7 @@ enum KMWatermarkAdjectiveText {
             break
         }
         
-        return NSFont(name: fontName, size: fontSize)!
+        return NSFont(name: fontName, size: fontSize) ?? NSFont(name: "Helvetica", size: 48)!
     }
     
     public func getTextFontName() -> String {
@@ -75,7 +75,7 @@ enum KMWatermarkAdjectiveText {
     }
     
     public func getTextFontSize() -> CGFloat {
-        var fontSize = 0.0
+        var fontSize = 48.0
         switch self.textFont {
         case .font(name: _, size: let size):
             fontSize = size

+ 2 - 2
PDF Office/PDF Master/Class/PDFTools/Watermark/Model/KMWatermarkModel.swift

@@ -16,9 +16,9 @@ import Cocoa
     var textFontSize: CGFloat = 48
     var waterTextColor: NSColor = NSColor.black
     var rotation: CGFloat = 0.0
-    var opacity: CGFloat = 0.0
+    var opacity: CGFloat = 1.0
     
-    var scale: CGFloat = 0.0
+    var scale: CGFloat = 1.0
     
     /**
      (Top:0 Middle:1 Bottom:2)

+ 211 - 19
PDF Office/PDF Master/Class/PDFTools/Watermark/New/View/KMWatermarkView.swift

@@ -94,7 +94,7 @@ class KMWatermarkView: KMBaseXibView, NSTextFieldDelegate, NSComboBoxDelegate, N
     var password: String = ""
     var originalWatermark: KMWatermarkModel = KMWatermarkModel()
     var watermark: KMWatermarkModel = KMWatermarkModel()
-    var type: KMWatermarkManagerType = .add
+    var type: KMWatermarkManagerType = .use
     var pdfDocument: CPDFDocument? {
         didSet {
             self.pdfView.document = pdfDocument
@@ -756,15 +756,24 @@ extension KMWatermarkView {
             savePanel.allowedFileTypes = ["pdf"]
             savePanel.accessoryView = savePanelAccessoryViewController.view
             
-//            savePanel.beginSheetModal(for: self.window!) { (result) in
-//                if result == NSApplication.ModalResponse.OK {
-//                    savePanelAccessoryViewController.retain()
-//                    let document = CPDFDocument(url: self.pdfdocument?.documentURL)
-//                    if let password = self.password {
-//                        document?.unlock(withPassword: password)
-//                    }
+            savePanel.beginSheetModal(for: self.window!) { [unowned self] result in
+                if result == NSApplication.ModalResponse.OK {
+//                    let document = CPDFDocument(url: self.pdfDocument?.documentURL)
+//                    document?.unlock(withPassword: self.pdfDocument?.password)
+                    
+                    self.addWatermark(model: self.watermark, toPath: savePanel.url!.path) { success in
+                        if success {
+                            if savePanelAccessoryViewController.openAutomaticButton.state == .on {
+                                NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
+                                    // Handle the completion if needed
+                                }
+                            } else {
+                                NSWorkspace.shared.activateFileViewerSelecting([savePanel.url!])
+                            }
+                        }
+                    }
+
 //
-//                    KMWatermarkManager.defaultManager
 //                    let obj = KMPDFWatermarkObject(pdfDocument: document)
 //                    obj?.addWatermark(self.watermark, toPath: savePanel.url!.path, completionHandler: { (isSuccessfully) in
 //                        DispatchQueue.main.async {
@@ -775,10 +784,8 @@ extension KMWatermarkView {
 //                                    NSDocumentController.shared.openDocument(withContentsOf: savePanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
 //                                        // Handle the completion if needed
 //                                    }
-//                                    self.dismissSheet(sender)
 //                                } else {
 //                                    NSWorkspace.shared.activateFileViewer(selecting: [savePanel.url!])
-//                                    self.dismissSheet(sender)
 //                                }
 //                            }
 //                        }
@@ -791,19 +798,17 @@ extension KMWatermarkView {
 //                            self.watermark.watermarkID = self.templateNameTextField.stringValue
 //                        }
 //
-//                        if KMWatermarkManager.defaultManager().watermarks.contains(self.originalWatermark) {
-//                            KMWatermarkManager.defaultManager().removeWatermark(withData: self.originalWatermark)
-//                            KMWatermarkManager.defaultManager().addWatermark(withData: self.watermark)
+//                        if KMWatermarkManager.defaultManager.watermarks.contains(self.originalWatermark) {
+//                            KMWatermarkManager.defaultManager.removeWatermark(withData: self.originalWatermark)
+//                            KMWatermarkManager.defaultManager.addWatermark(withData: self.watermark)
 //                        } else {
-//                            KMWatermarkManager.defaultManager().addWatermark(withData: self.watermark)
+//                            KMWatermarkManager.defaultManager.addWatermark(withData: self.watermark)
 //                        }
 //
 //                        NotificationCenter.default.post(name: NSNotification.Name("KMBatchOperateWatermarksNotification"), object: self)
 //                    }
-//                }
-//
-//                savePanelAccessoryViewController.release()
-//            }
+                }
+            }
         }
     }
     
@@ -966,3 +971,190 @@ extension KMWatermarkView {
         pdfView.needsDisplay = true
     }
 }
+
+extension KMWatermarkView {
+    func addWatermark(model: KMWatermarkModel, toPath: String, completion: @escaping (_ result: Bool) -> ()) {
+        DispatchQueue.global().async {
+            let waterDocument = CPDFDocument(url: self.pdfView.document.documentURL)
+            guard let waterDocument = waterDocument else { return }
+            var property: CPDFWatermark!
+            var scale: CGFloat = model.scale
+            if (!model.text.isEmpty) {
+                property = CPDFWatermark(document: waterDocument, type: .text)
+                property.text = model.text
+                property.textColor = model.getTextColor()
+                scale = model.getTextFontSize() / 24.0
+            } else {
+                property = CPDFWatermark(document: waterDocument, type: .image)
+                property.image = model.image
+            }
+            
+            property.scale = scale
+            property.rotation = -model.rotation
+            property.opacity = model.opacity
+            property.tx = model.horizontalSpace
+            property.ty = model.verticalSpace
+            property.isFront = model.isFront
+            var pageString: String = ""
+            if (model.pageRangeType == .all) {
+                for i in 0..<waterDocument.pageCount {
+                    pageString.append("\(i)")
+                    
+                    if (i != waterDocument.pageCount-1) {
+                        pageString.append(",")
+                    }
+                }
+            } else if (model.pageRangeType == .odd) {
+                for i in 0 ..< waterDocument.pageCount {
+                    if (i % 2 == 0) {
+                        pageString.append("\(i)")
+                    } else {
+                        continue
+                    }
+                    
+                    if (i != waterDocument.pageCount-1) {
+                        pageString.append(",")
+                    }
+                }
+            } else if (model.pageRangeType == .even) {
+                for i in 0 ..< waterDocument.pageCount {
+                    if (i % 2 == 1) {
+                        pageString.append("\(i)")
+                    } else {
+                        continue
+                    }
+                    
+                    if (i != waterDocument.pageCount-1) {
+                        pageString.append(",")
+                    }
+                }
+            } else {
+                pageString = model.pagesString
+            }
+            property.pageString = pageString
+            property.isTilePage = model.isTilePage
+            property.horizontalSpacing = model.tileHorizontalSpace / scale
+            property.verticalSpacing = model.tileVerticalSpace / scale
+            if (model.verticalMode == 0) {
+                property.verticalPosition = .top
+            } else if (model.verticalMode == 1) {
+                property.verticalPosition = .center
+            } else if (model.verticalMode == 2) {
+                property.verticalPosition = .bottom
+            }
+            
+            if (model.horizontalMode == 0) {
+                property.horizontalPosition = .left
+            } else if (model.horizontalMode == 1) {
+                property.horizontalPosition = .center
+            } else if (model.horizontalMode == 2) {
+                property.horizontalPosition = .right
+            }
+            model.watermark = property
+            
+            waterDocument.addWatermark(property)
+            
+            /// 保存到临时路径
+            let documentPath = NSTemporaryDirectory()
+            let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
+            if (FileManager.default.fileExists(atPath: tempPath)) {
+                try?FileManager.default.removeItem(atPath: tempPath)
+            }
+            
+            let result = waterDocument.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 loadAllWatermarks() {
+//            self.watermarkArray.removeAll()
+//            let watermarks: Array<CPDFWatermark> = self.preView.document.watermarks()
+//            for watermark in watermarks {
+//                let model = KMWatermarkModel()
+//                model.scale = watermark.scale
+//                model.rotation = -watermark.rotation
+//                model.opacity = watermark.opacity
+//                model.verticalSpace = watermark.tx
+//                model.horizontalSpace = watermark.ty
+//                model.pagesString = watermark.pageString
+////                model.textColor = watermark.textColor
+//                model.isFront = watermark.isFront
+//                model.isTilePage = watermark.isTilePage
+//                model.tileVerticalSpace = watermark.verticalSpacing
+//                model.tileHorizontalSpace = watermark.horizontalSpacing
+//                
+//                if (watermark.type == .text) {
+//                    model.text = watermark.text
+////                    model.textFont
+//                    model.scale = watermark.scale * 24
+//                } else if (watermark.type == .image) {
+//                    model.image = watermark.image
+//                }
+//                
+//                if (watermark.verticalPosition == .top) {
+//                    model.verticalMode = 0
+//                } else if (watermark.verticalPosition == .center) {
+//                    model.verticalMode = 1
+//                } else if (watermark.verticalPosition == .bottom) {
+//                    model.verticalMode = 2
+//                }
+//                
+//                if (watermark.horizontalPosition == .left) {
+//                    model.horizontalMode = 0
+//                } else if (watermark.horizontalPosition == .center) {
+//                    model.horizontalMode = 1
+//                } else if (watermark.horizontalPosition == .right) {
+//                    model.horizontalMode = 2
+//                }
+//                
+//                model.watermark = watermark
+//                self.watermarkArray.append(model)
+//            }
+//        }
+    }
+    
+    func deleteWatermarks(toPath: String, completion: @escaping (_ result: Bool) -> ()) -> () {
+        if (self.pdfView.document.watermarks().count <= 0) {
+            completion(false)
+        }
+        DispatchQueue.global().async {
+            let array: Array<CPDFWatermark> = self.pdfView.document.watermarks()
+            for model in array {
+                self.pdfView.document.removeWatermark(model)
+            }
+
+            /// 保存到临时路径
+            let documentPath = NSTemporaryDirectory()
+            let tempPath: String = "\(documentPath)/\(toPath.lastPathComponent)"
+            if (FileManager.default.fileExists(atPath: tempPath)) {
+                try?FileManager.default.removeItem(atPath: tempPath)
+            }
+
+            let result = self.pdfView.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)
+            }
+        }
+    }
+}

+ 4 - 0
PDF Office/PDF Master/Class/PDFTools/Watermark/New/View/KMWatermarkView.xib

@@ -113,6 +113,7 @@
                                                     <color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
                                                     <size key="minSize" width="247" height="58"/>
                                                     <size key="maxSize" width="262" height="10000000"/>
+                                                    <color key="insertionPointColor" name="textInsertionPointColor" catalog="System" colorSpace="catalog"/>
                                                 </textView>
                                             </subviews>
                                         </clipView>
@@ -355,6 +356,9 @@
                                     <stepper horizontalHuggingPriority="750" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="QCG-d1-VCP">
                                         <rect key="frame" x="194" y="126" width="19" height="28"/>
                                         <stepperCell key="cell" continuous="YES" alignment="left" minValue="-360" maxValue="360" id="ByH-8Q-fTO"/>
+                                        <connections>
+                                            <action selector="angleStepperAction:" target="-2" id="J6c-Sb-fKu"/>
+                                        </connections>
                                     </stepper>
                                     <slider verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="xgB-gi-FrZ">
                                         <rect key="frame" x="90" y="90" width="122" height="28"/>

+ 14 - 12
PDF Office/PDF Master/Class/PDFTools/Watermark/View/KMWatermarkPDFView.swift

@@ -87,23 +87,23 @@ class KMWatermarkPDFView: CPDFView {
         }
         NSGraphicsContext.saveGraphicsState()
         page.transform(context, for: .cropBox)
-//        if (self.watermarkModel.pagesString.count > 0) {
-//            let array = self.watermarkModel.pagesString.components(separatedBy: ",")
-//            let index: Int = Int(self.document.index(for: page))
-//            if (!array.contains("\(index)")) {
-//                return
-//            }
-//        }
+        if (self.watermark.pagesString.count > 0) {
+            let array = self.watermark.pagesString.components(separatedBy: ",")
+            let index: Int = Int(self.document.index(for: page))
+            if (!array.contains("\(index)")) {
+                return
+            }
+        }
         
         if (!self.watermark.text.isEmpty) {
-            var font = self.watermark.textFont
+            var font = self.watermark.getTextFont()
             if (font == nil) {
-//                font = NSFont(name: "Helvetica", size: 48)
+                font = NSFont(name: "Helvetica", size: 48)!
             }
             
             var color = NSColor.black
             if (self.watermark.textColor != nil) {
-//                color = self.watermarkModel.textColor
+                color = self.watermark.getTextColor()
             }
             
             var red: CGFloat = 0
@@ -116,9 +116,11 @@ class KMWatermarkPDFView: CPDFView {
             let style = NSMutableParagraphStyle()
             style.alignment = self.watermark.textAligement
             style.lineBreakMode = .byCharWrapping
-            let dict = [NSAttributedString.Key.paragraphStyle : style,
+            let dict = [
+                NSAttributedString.Key.paragraphStyle : style,
                         NSAttributedString.Key.foregroundColor : color,
-                        NSAttributedString.Key.font : font] as [NSAttributedString.Key : Any]
+//                        NSAttributedString.Key.font : font as Any
+            ] as [NSAttributedString.Key : Any]
             size = self.watermark.text.boundingRect(with: NSSize(width: 1000, height: 1000), options: NSString.DrawingOptions(rawValue: 3), attributes: dict).size
             
             let radian: CGFloat = self.watermark.rotation*(Double.pi/180.0)