Pārlūkot izejas kodu

【综合】页面编辑-插入 新增扫描仪、图片、剪贴板

niehaoyu 7 mēneši atpakaļ
vecāks
revīzija
8a8f1777d5

+ 152 - 0
PDF Office/PDF Master/Class/PDFTools/PageEdit/Controller/KMPDFEditViewController.swift

@@ -7,6 +7,7 @@
 
 
 typealias KMPDFEditViewControllerSelectionDidChange = (_ selectedIndexs: Set<IndexPath>) -> ()
+typealias KMIndexChooseBlock = (_ index: Int) -> Void
 
 class KMPDFEditViewController: KMPDFThumbViewBaseController {
     
@@ -177,6 +178,12 @@ class KMPDFEditViewController: KMPDFThumbViewBaseController {
                     self.insertBlankPageAction()
                 } else if (index == KMPageEditType.insert_custom_page) {
                     self.item_insertCustomPage(sender: nil)
+                } else if (index == KMPageEditType.insert_fromImage) {
+                    self.item_insertFromImage(sender: nil)
+                } else if (index == KMPageEditType.insert_fromClipboard) {
+                    self.item_insertFromClipboard(sender: nil)
+                } else if (index == KMPageEditType.insert_fromScanner) {
+                    self.item_insertFromScanner(sender: nil)
                 } else if (index == KMPageEditType.extract_selected_pages) {
                     self.extractSelectPageItemAction()
                 } else if (index == KMPageEditType.split_selected_pages) {
@@ -1174,6 +1181,151 @@ class KMPDFEditViewController: KMPDFThumbViewBaseController {
         self.km_beginSheet(windowC: windowC)
     }
     
+    @objc func item_insertFromImage(sender: NSMenuItem?) {
+        if IAPProductsManager.default().isAvailableAllFunction() == false {
+            KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
+            return
+        }
+        
+        let openPanel = NSOpenPanel()
+        openPanel.allowedFileTypes = KMImageToPDFMethod.supportedImageTypes()
+        openPanel.allowsMultipleSelection = true
+        openPanel.message = KMLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on keyboard and click on the target files one by one.", nil)
+        openPanel.canChooseDirectories = false
+        openPanel.allowsMultipleSelection = false
+        openPanel.beginSheetModal(for: NSWindow.currentWindow()) { [self] (result) in
+            if result == NSApplication.ModalResponse.OK {
+                if let fileURL = openPanel.urls.first {
+//                    self.choosePositionWindow {[weak self] index in
+//                        /// 插入位置
+                        if let imag = NSImage(contentsOfFile: fileURL.path ) {
+                            let index = self.getInsertIndex() + 1
+                            let document = CPDFDocument()
+                            _ = document?.km_insertPage(imag.size, withImage: fileURL.path , at: 0)
+                            if let page: CPDFPage = (document?.page(at: 0)) {
+                                self.insertPages(pages: [page], at: IndexSet(integer: index))
+                            }
+                            let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
+                            self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
+                        }
+//                    }
+                }
+            }
+        }
+        
+    }
+    
+    func choosePositionWindow(completion: @escaping KMIndexChooseBlock) -> Void {
+//        guard let doc = self.pdfDocument else {
+//            NSSound.beep()
+//            return
+//        }
+//        let windowC = KMFileInsertPositionWindowController(document: doc)
+//        windowC.currentPage = self.getSelecteIndex() + 1
+//        windowC.insertLocation = 3
+//        windowC.callback = { [weak self] pdfDoc, _, insertI in
+//            if insertI >= 0 {
+//                if (completion != nil) {
+//                    completion(insertI);
+//                }
+//            }
+//            self?.km_endSheet()
+//        }
+//        self.km_beginSheet(windowC: windowC)
+    }
+    
+    @objc func item_insertFromClipboard(sender: NSMenuItem?) {
+        if IAPProductsManager.default().isAvailableAllFunction() == false {
+            KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
+            return
+        }
+//        self.choosePositionWindow {[weak self] index in
+            /// 插入位置
+            var error: NSError?
+            guard let document: CPDFDocument = self.openDocumentWithImageFromPasteboard(NSPasteboard.general, error: &error) else {
+                return
+            }
+        let index = self.getInsertIndex() + 1
+            if let page: CPDFPage = (document.page(at: 0)) {
+                self.insertPages(pages: [page], at: IndexSet(integer: index))
+            }
+            let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
+            self.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
+//        }
+    }
+    
+    @objc func item_insertFromScanner(sender: NSMenuItem?) {
+        if IAPProductsManager.default().isAvailableAllFunction() == false {
+            KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
+            return
+        }
+        
+        let vc = KMDeviceBrowserWindowController.shared
+        vc.type = .scanner
+        vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
+//            self?.choosePositionWindow {[weak self] index in
+                /// 插入位置
+                if let imag = NSImage(contentsOfFile: url.path! ) {
+                    let index = (self?.getInsertIndex())! + 1
+                    let document = CPDFDocument()
+                    _ = document?.km_insertPage(imag.size, withImage: url.path! , at: 0)
+                    if let page: CPDFPage = (document?.page(at: 0)) {
+                        self?.insertPages(pages: [page], at: IndexSet(integer: index))
+                    }
+                    let ips: Set<IndexPath> = [IndexPath(item: index, section: 0)]
+                    self?.thumbnailView.collectionView.scrollToItems(at: ips, scrollPosition: .centeredVertically)
+                }
+//            }
+            vc.close()
+        }
+        vc.showWindow(NSApp.mainWindow)
+    }
+    
+    func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> CPDFDocument? {
+        var document: CPDFDocument? = nil
+        var data: Data? = nil
+        
+        if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
+            data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
+        } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
+            data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
+        } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
+            data = convertTIFFDataToPDF(pboard.data(forType: NSPasteboard.PasteboardType.tiff) ?? Data())
+        } else {
+            let images = pboard.readObjects(forClasses: [NSImage.self], options: [:])
+            let strings = pboard.readObjects(forClasses: [NSAttributedString.self], options: [:])
+            if images?.count ?? 0 > 0 {
+                data = convertTIFFDataToPDF((images![0] as AnyObject).tiffRepresentation!)
+            } else if strings?.count ?? 0 > 0 {
+                data = KMOCTool.convertStringsToPDF(withString: strings ?? [""]) // convertStringsToPDF(strings!)
+            }
+        }
+        
+        if let data = data {
+            document = CPDFDocument(data: data)
+            
+        } else if let outError = outError {
+            outError.pointee = NSError(domain: "SKDocumentErrorDomain", code: 3, userInfo: [NSLocalizedDescriptionKey: NSLocalizedString("Unable to load data from clipboard", comment: "Error description")])
+        }
+    
+        return document
+    }
+    
+    func convertTIFFDataToPDF(_ tiffData: Data) -> Data? {
+        guard let imsrc = CGImageSourceCreateWithData(tiffData as CFData, [kCGImageSourceTypeIdentifierHint: kUTTypeTIFF] as CFDictionary), CGImageSourceGetCount(imsrc) > 0, let cgImage = CGImageSourceCreateImageAtIndex(imsrc, 0, nil) else { return nil }
+        let pdfData = NSMutableData(capacity: tiffData.count)
+        let consumer = CGDataConsumer(data: pdfData! as CFMutableData)!
+        
+        var rect = CGRect(x: 0, y: 0, width: CGFloat(cgImage.width), height: CGFloat(cgImage.height))
+        let ctxt = CGContext(consumer: consumer, mediaBox: &rect, nil)
+        ctxt!.beginPDFPage(nil)
+        ctxt!.draw(cgImage, in: rect)
+        ctxt!.endPDFPage()
+        ctxt!.closePDF()
+        
+        return pdfData as? Data
+    }
+    
     func extractSelectPageItemAction() {
         if IAPProductsManager.default().isAvailableAllFunction() == false {
             KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)

+ 48 - 3
PDF Office/PDF Master/Class/PDFTools/PageEdit/View/KMPDFEditToolbar.swift

@@ -44,6 +44,24 @@ enum KMPageEditType: Int {
         }
     }
     
+    static var insert_fromImage: Int {
+        get {
+            return self.insert.rawValue + 1003
+        }
+    }
+    
+    static var insert_fromClipboard: Int {
+        get {
+            return self.insert.rawValue + 1004
+        }
+    }
+    
+    static var insert_fromScanner: Int {
+        get {
+            return self.insert.rawValue + 1005
+        }
+    }
+    
     static var extract_selected_pages: Int {
         get {
             return self.extract.rawValue + 2000
@@ -97,9 +115,12 @@ class KMPDFEditToolbar: NSView {
     var pageRangeValueDidChange: KMValueDidChangeBlock?
     
     lazy var insertItemStrings: [String] = {
-       return [NSLocalizedString("Blank Page", comment: ""),
-               NSLocalizedString("Blank Page - Custom...", comment: ""),
-               NSLocalizedString("From PDF", comment: "")]
+        return [NSLocalizedString("Blank Page", comment: ""),
+                NSLocalizedString("Blank Page - Custom...", comment: ""),
+                NSLocalizedString("From PDF", comment: ""),
+                NSLocalizedString("From Image", comment: ""),
+                NSLocalizedString("New From Clipboard", comment: ""),
+                NSLocalizedString("Import From Scanner", comment: "")]
     }()
     
     private weak var popover: NSPopover?
@@ -368,6 +389,27 @@ class KMPDFEditToolbar: NSView {
         FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageEdit", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageEdit_Insert"])
     }
     
+    @objc func item_insertFromImage(sender: NSMenuItem?) {
+        guard let callback = self.itemClick else {
+            return
+        }
+        callback(self, KMPageEditType.insert_fromImage)
+    }
+    
+    @objc func item_insertFromClipboard(sender: NSMenuItem?) {
+        guard let callback = self.itemClick else {
+            return
+        }
+        callback(self, KMPageEditType.insert_fromClipboard)
+    }
+    
+    @objc func item_insertFromScanner(sender: NSMenuItem?) {
+        guard let callback = self.itemClick else {
+            return
+        }
+        callback(self, KMPageEditType.insert_fromScanner)
+    }
+    
     @objc private func _splitAction(sender: NSMenuItem) {
         if (sender.tag == 1) {
             guard let callback = self.itemClick else {
@@ -526,6 +568,9 @@ extension KMPDFEditToolbar: KMToolbarViewDelegate {
             _ = subMenu.addItem(title: self.insertItemStrings[0], action: #selector(item_insertBlankPage) , target: self)
             _ = subMenu.addItem(title: self.insertItemStrings[1], action: #selector(item_insertCustomPage) , target: self)
             _ = subMenu.addItem(title: self.insertItemStrings[2], action: #selector(item_insertFile) , target: self)
+            _ = subMenu.addItem(title: self.insertItemStrings[3], action: #selector(item_insertFromImage) , target: self)
+            _ = subMenu.addItem(title: self.insertItemStrings[4], action: #selector(item_insertFromClipboard) , target: self)
+            _ = subMenu.addItem(title: self.insertItemStrings[5], action: #selector(item_insertFromScanner) , target: self)
             item?.menuFormRepresentation = menuItem
         } else if (identifier == KMToolbarPageEditExtractItemIdentifier) {
             item?.image = NSImage(named: KMImageNameUXIconSubtoolbarPageExtract)

+ 1 - 0
PDF Office/PDF Master/Strings/de.lproj/Localizable.strings

@@ -2895,3 +2895,4 @@
 
 "Please reset the font weight via the drop-down box" = "Bitte setzen Sie die Schriftstärke über das Dropdown-Feld zurück";
 "General Properties" = "Attribute";
+"From Image"="Vom image";

+ 1 - 0
PDF Office/PDF Master/Strings/es.lproj/Localizable.strings

@@ -2987,3 +2987,4 @@
 
 "Please reset the font weight via the drop-down box" = "Restablezca el peso de la fuente a través del cuadro desplegable";
 "General Properties" = "Atributos";
+"From Image"="desde imagen";

+ 1 - 0
PDF Office/PDF Master/Strings/fr.lproj/Localizable.strings

@@ -2858,3 +2858,4 @@
 
 "Please reset the font weight via the drop-down box" = "Veuillez réinitialiser l'épaisseur de la police via la liste déroulante";
 "General Properties" = "Les attributs";
+"From Image"="de l'image";

+ 1 - 0
PDF Office/PDF Master/Strings/it.lproj/Localizable.strings

@@ -2783,3 +2783,4 @@
 
 "Please reset the font weight via the drop-down box" = "Reimpostare lo spessore del carattere tramite la casella a discesa";
 "General Properties" = "Attributi";
+"From Image"="dall'immagine";

+ 1 - 0
PDF Office/PDF Master/Strings/ja.lproj/Localizable.strings

@@ -3050,3 +3050,4 @@
 
 "Please reset the font weight via the drop-down box" = "ドロップダウンボックスからフォントの太さをリセットしてください";
 "General Properties" = "属性";
+"From Image"="イメージから";

+ 1 - 0
PDF Office/PDF Master/Strings/nl.lproj/Localizable.strings

@@ -3060,3 +3060,4 @@
 
 "Please reset the font weight via the drop-down box" = "Stel de lettergrootte opnieuw in via de vervolgkeuzelijst";
 "General Properties" = "Kenmerken";
+"From Image"="uit beeld";

+ 1 - 0
PDF Office/PDF Master/Strings/pl.lproj/Localizable.strings

@@ -2999,3 +2999,4 @@
 
 "Please reset the font weight via the drop-down box" = "Zresetuj grubość czcionki za pomocą rozwijanego pola";
 "General Properties" = "Atrybuty";
+"From Image"="z obrazu";

+ 1 - 0
PDF Office/PDF Master/Strings/ru.lproj/Localizable.strings

@@ -2923,3 +2923,4 @@
 
 "Please reset the font weight via the drop-down box" = "Пожалуйста, сбросьте толщину шрифта в раскрывающемся списке.";
 "General Properties" = "Атрибуты";
+"From Image"="из изображения";

+ 1 - 0
PDF Office/PDF Master/Strings/zh-Hans.lproj/Localizable.strings

@@ -3960,3 +3960,4 @@
 
 "Please reset the font weight via the drop-down box" = "请通过下拉框重设字重";
 "General Properties" = "属性";
+"From Image"="从图像";

+ 1 - 0
PDF Office/PDF Master/Strings/zh-Hant.lproj/Localizable.strings

@@ -4090,3 +4090,4 @@
 
 "Please reset the font weight via the drop-down box" = "請透過下拉框重設字重";
 "General Properties" = "屬性";
+"From Image"="來自影像";