瀏覽代碼

[系统菜单] - 新建(从剪贴板、图片)PDF

liujiajie 1 年之前
父節點
當前提交
72ca7271ec

+ 257 - 0
PDF Office/PDF Master/Class/ChromiumTabs/KMBrowserWindowController.swift

@@ -1101,12 +1101,157 @@ extension KMBrowserWindowController: KMSystemFileMenuProtocol {
         }
     }
     
+    func isEncapsulatedPostScriptData(_ data: Data) -> Bool {
+        let epsHeaderData = Data(bytes: [69, 80, 83, 70, 45], count: 5)
+        let rg: Range = (14..<20)
+        return (data.count >= 20 && (data.range(of: epsHeaderData, options: .anchored, in: rg) != nil))
+    }
+    
+    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!.flush()
+        
+        return pdfData as? Data
+    }
+    
+    func openDocumentWithImageFromPasteboard(_ pboard: NSPasteboard, error outError: AutoreleasingUnsafeMutablePointer<NSError?>?) -> Any? {
+        var document: CPDFDocument? = nil
+        var data: Data? = nil
+        
+        if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.pdf.rawValue]) {
+//            pboard.types
+            data = pboard.data(forType: NSPasteboard.PasteboardType.pdf)
+        } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.postScript.rawValue]) {
+//            pboard.types
+            data = pboard.data(forType: NSPasteboard.PasteboardType.postScript)
+        } else if pboard.canReadItem(withDataConformingToTypes: [NSPasteboard.PasteboardType.tiff.rawValue]) {
+//            pboard.types
+            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 {
+            let documentC = NSDocumentController.shared
+
+            document = CPDFDocument(data: data)
+            
+            let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
+            let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
+            let filePath = savePath.deletingLastPathComponent
+            if FileManager.default.fileExists(atPath: filePath) == false {
+                try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
+            }
+             
+            document?.write(to: URL(fileURLWithPath: savePath))
+            NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
+                if error != nil {
+                    NSApp.presentError(error!)
+                } else {
+                    if document is KMMainDocument {
+                        let newDocument = document
+                        (newDocument as! KMMainDocument).isNewCreated = true
+                    }
+                }
+            }
+
+      
+        } 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 openDocument(withURLFromPasteboard pboard: NSPasteboard, showNotes: Bool, error outError: inout NSError?) -> Any? {
+        let theURLs = NSURL.readURLs(from: pboard)
+        let url = theURLs?.count ?? 0 > 0 ? theURLs?[0] : nil
+        let theURL: NSURL? = url as? NSURL
+        var documentC = NSDocumentController.shared
+        var document: NSDocument? = nil
+        if (theURL as AnyObject).isFileURL == true {
+            var _: NSError? = nil
+            let type = try? documentC.typeForContents(of: theURL as! URL)//ForContents(ofURL: theURL, error: &error)
+            
+            if showNotes == false || NSDocument.readableTypes.contains(type ?? "") {
+                documentC.openDocument(withContentsOf: theURL as! URL, display: true, completionHandler: { resultDocument, success, err in
+                    document = resultDocument
+                })//openDocument(withContentsOfURL: theURL, display: true, error: &outError)
+            } else if NSDocument.readableTypes.contains(type ?? "") {
+                for doc in documentC.documents {
+                    let sel = NSSelectorFromString("sourceFileURL")
+                    if doc.responds(to: sel) && doc.fileURL == theURL as? URL {
+                        document = doc
+                        break
+                    }
+                }
+                if let document: NSDocument = document {
+                    document.showWindows()
+                } else {
+                    var data: Data? = nil
+                    
+//                    if NSWorkspace.shared.type(type ?? "", conformsToType: KMPDFBundleDocumentType) {
+//                        let skimFileURL = FileManager.default.exte
+//                        data = skimFileURL != nil ? try? Data(contentsOf: skimFileURL!) : nil
+//                    } else {
+//                        data = SKNExtendedAttributeManager.shared().extendedAttributeNamed(SKIM_NOTES_KEY, atPath: theURL.path, traverseLink: true, error: &error)
+//                    }
+//                    let documentNew: KMMainDocument = self.browser.activeTabContents() as! KMMainDocument
+                    
+                    if let document = try? documentC.makeUntitledDocument(ofType: KMNotesDocumentType) {
+                        document.fileURL = URL(fileURLWithPath: theURL?.path ?? "")
+                        
+//                        if data == nil || document.read(fromData: data!, ofType: SKNotesDocumentType, error: &error) {
+                            documentC.addDocument(document)
+                            document.makeWindowControllers()
+                            document.showWindows()
+//                        } else {
+//                            document = nil
+//                            if let error = error {
+//                                outError = error
+//                            }
+//                        }
+                    }
+                }
+            }
+        }
+//        else if showNotes == false && theURL != nil {
+//            document = SKDownloadController.shared().addDownload(for: theURL!)
+//        } else if outError != nil {
+//            outError = NSError.readPasteboardError(withLocalizedDescription: NSLocalizedString("Unable to load data from clipboard", comment: "Error description"))
+//        }
+        
+        return document
+    }
+    
     @IBAction func newDocumentFromClipboard(_ sender: Any?) {
         KMPrint("newDocumentFromClipboard")
+        var error: NSError?
+        let pboard = NSPasteboard.general
+        var document = openDocumentWithImageFromPasteboard(pboard, error: &error)
+        
+        if document == nil{
+            document = openDocument(withURLFromPasteboard: pboard, showNotes: false, error: &error)
+        }
     }
     
     @IBAction func newDocumentFromImage(_ sender: Any?) {
         KMPrint("importFromWebPage")
+        createPDFFromImage()
     }
     
     @IBAction func importFromWebPage(_ sender: Any?) {
@@ -1136,6 +1281,118 @@ extension KMBrowserWindowController: KMSystemFileMenuProtocol {
 // MARK: - KMSystemViewMenuProtocol
 
 extension KMBrowserWindowController: KMSystemViewMenuProtocol {
+    func createPDFFromImage() {
+        let openPanel = NSOpenPanel()
+        openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
+        openPanel.allowsMultipleSelection = true
+        openPanel.message = NSLocalizedString("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.", comment: "")
+        openPanel.beginSheetModal(for: NSApp.mainWindow!) { response in
+            if response == .OK {
+                self.creatPdfFromImg(urls: openPanel.urls)
+            }
+        }
+    }
+    func creatPdfFromImg(urls: Array<URL>)  {
+//        let savePath = self.newDocumentTempSavePath("convertToPDF.pdf")
+        let pdf = CPDFDocument()
+        var isSucceed = true
+        
+        let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
+        let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
+        let filePath = savePath.deletingLastPathComponent
+        if FileManager.default.fileExists(atPath: filePath) == false {
+            try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
+        }
+        
+        for fileURL in urls {
+            if let imag = NSImage(contentsOfFile: fileURL.path ) {
+                _ = pdf?.km_insertPage(imag.size, withImage: fileURL.path , at: pdf?.pageCount ?? 0)
+                pdf?.write(to: URL(fileURLWithPath: savePath))
+            }
+        }
+        NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
+            if error != nil {
+                NSApp.presentError(error!)
+            } else {
+                if document is KMMainDocument {
+                    let newDocument = document
+                    (newDocument as! KMMainDocument).isNewCreated = true
+                }
+            }
+//            self.homeContentView?.reloadData()
+        }
+    }
+    
+    func createPdfWithParam()  {
+        let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
+        let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
+        let filePath = savePath.deletingLastPathComponent
+        if FileManager.default.fileExists(atPath: filePath) == false {
+            try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
+        }
+        
+        let pdfDocument = CPDFDocument()
+        pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
+        pdfDocument?.write(to: URL(fileURLWithPath: savePath))
+        NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
+            if error != nil {
+                NSApp.presentError(error!)
+            } else {
+                if document is KMMainDocument {
+                    let newDocument = document
+                    (newDocument as! KMMainDocument).isNewCreated = true
+                }
+            }
+//            self.homeContentView?.reloadData()
+        }
+    }
+    
+    func savePdf(_ filePath: String) -> Void {
+        let docVc = KMDocumentController.shared
+        
+        docVc.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { doc, suc, err in
+            try? FileManager.default.removeItem(atPath: filePath)
+        }
+    }
+    
+    func newDocumentTempSavePath(_ fileName: String) -> String {
+        let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
+        let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
+        let append2 = append1!.stringByAppendingPathComponent(String(format: "%@", fileName))
+        return append2
+    }
+    
+    func fetchUniquePath(_ originalPath: String) -> String {
+        var path = originalPath
+        let dManager = FileManager.default
+        if !dManager.fileExists(atPath: path) {
+            if path.extension.count < 1 {
+                path = path.stringByAppendingPathExtension("pdf")
+            }
+            return path
+        } else {
+            let originalFullFileName = path.lastPathComponent
+            let originalFileName = path.lastPathComponent.deletingPathExtension
+            let originalExtension = path.extension
+
+            let startIndex: Int = 0
+            let endIndex: Int = startIndex + originalPath.count - originalFullFileName.count - 1
+            let fileLocatePath = originalPath.substring(to: endIndex)
+            var i = 1
+            while (1 != 0) {
+                var newName = String(format: "%@%ld", originalFileName, i)
+                newName = newName.stringByAppendingPathExtension(originalExtension)
+                let newPath = fileLocatePath.stringByAppendingPathComponent(newName)
+                if !dManager.fileExists(atPath: newPath) {
+                    return newPath
+                } else {
+                    i+=1
+                    continue
+                }
+            }
+        }
+    }
+    
     func menuItemAction_adjustWidth(_ sender: Any) {
         if (self.canResponseDocumentAction() == false) {
             return

+ 1 - 1
PDF Office/PDF Master/Class/ChromiumTabs/src/third_party/mozilla/NSURL+Utils.h

@@ -47,5 +47,5 @@
 
 + (NSURL*)URLFromInetloc:(NSString*)inFile;
 + (NSURL*)URLFromIEURLFile:(NSString*)inFile;
-
++ (NSArray *)readURLsFromPasteboard:(NSPasteboard *)pboard;
 @end

+ 19 - 0
PDF Office/PDF Master/Class/ChromiumTabs/src/third_party/mozilla/NSURL+Utils.m

@@ -144,4 +144,23 @@
 	return ret;
 }
 
++ (NSArray *)readURLsFromPasteboard:(NSPasteboard *)pboard {
+    NSArray *URLs = [pboard readObjectsForClasses:[NSArray arrayWithObject:[NSURL class]] options:[NSDictionary dictionary]];
+    if ([URLs count] == 0) {
+        NSString *type = [pboard availableTypeFromArray:[NSArray arrayWithObjects:NSPasteboardTypeURL, NSFilenamesPboardType, nil]];
+        if ([type isEqualToString:NSPasteboardTypeURL]) {
+            URLs = [NSArray arrayWithObjects:[NSURL URLFromPasteboard:pboard], nil];
+        } else if ([type isEqualToString:NSFilenamesPboardType]) {
+            NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
+            if ([filenames count]  > 0) {
+                NSMutableArray *files = [NSMutableArray array];
+                for (NSString *filename in filenames)
+                    [files addObject:[NSURL fileURLWithPath:[filename stringByExpandingTildeInPath]]];
+                URLs = files;
+            }
+        }
+    }
+    return URLs;
+}
+
 @end

+ 2 - 0
PDF Office/PDF Master/Class/Common/OC/Batch/KMOCTool.h

@@ -12,6 +12,8 @@ NS_ASSUME_NONNULL_BEGIN
 @interface KMOCTool : NSObject
 
 +(void)createPDFFile:(NSString *)filePath imagePaths:(NSArray *)paths results:(NSArray *)resultsArray scale:(CGFloat)scale;
++(NSData*)convertStringsToPDFWithString:(NSArray *)strings;
+
 @end
 
 NS_ASSUME_NONNULL_END

+ 66 - 0
PDF Office/PDF Master/Class/Common/OC/Batch/KMOCTool.m

@@ -98,6 +98,10 @@
     CGContextRelease (pdfContext);
 }
 
++(NSData*)convertStringsToPDFWithString:(NSArray *)strings{
+    return convertStringsToPDF(strings);
+}
+
 static inline NSFont * FontWithSize(NSString *strChar, CGSize size) {
     CGFloat fontsize = 1.0;
     NSFont *font = [NSFont systemFontOfSize:fontsize];
@@ -110,5 +114,67 @@ static inline NSFont * FontWithSize(NSString *strChar, CGSize size) {
     return [NSFont systemFontOfSize:fontsize-1];
 }
 
+static NSData *convertStringsToPDF(NSArray<NSAttributedString *> *strings)
+{
+    NSMutableData *pdfData = [[NSMutableData alloc] init];
+    CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData);
+
+    CFMutableDictionaryRef myDictionary = CFDictionaryCreateMutable(NULL,
+                                                                    0,
+                                                                    &kCFTypeDictionaryKeyCallBacks,
+                                                                    &kCFTypeDictionaryValueCallBacks);
+    CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("PDF Reader Pro"));
+    
+    CGRect mediaBox = CGRectMake(0, 0, 595, 842);
+    CGContextRef pdfContext = CGPDFContextCreate(consumer, &mediaBox, myDictionary);
+    CGContextSetRGBFillColor(pdfContext, 1.0, 0.0, 0.0, 0.0);
+    CGContextSetTextDrawingMode(pdfContext, kCGTextFill);
+    
+    CFRelease(myDictionary);
+    
+    for (NSAttributedString *attributeString in strings) {
+        if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_10) {
+            NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attributeString];
+            NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
+            [textStorage addLayoutManager:layoutManager];
+            while (YES) {
+                NSSize contentSize = NSMakeSize(mediaBox.size.width-40,
+                                                mediaBox.size.height-40);
+                NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:contentSize];
+                [layoutManager addTextContainer:textContainer];
+                NSRange rang = [layoutManager glyphRangeForTextContainer:textContainer];
+                if (rang.length <= 0 ||
+                    rang.length + rang.location > attributeString.length) {
+                    break;
+                }
+                NSAttributedString *attStr = [attributeString attributedSubstringFromRange:rang];
+                
+                [NSGraphicsContext saveGraphicsState];
+//                [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:pdfContext flipped:NO]];
+                [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:pdfContext flipped:NO]];
+                CGContextBeginPage(pdfContext, &mediaBox);
+                [attStr drawInRect:CGRectMake(20, 20,
+                                              mediaBox.size.width-40,
+                                              mediaBox.size.height-40)];
+                CGContextEndPage(pdfContext);
+                [NSGraphicsContext restoreGraphicsState];
+            }
+        } else {
+            [NSGraphicsContext saveGraphicsState];
+            [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithCGContext:pdfContext flipped:NO]];
+            CGContextBeginPage(pdfContext, &mediaBox);
+            [attributeString drawInRect:CGRectMake(20, 20,
+                                                   mediaBox.size.width-40,
+                                                   mediaBox.size.height-40)];
+            CGContextEndPage(pdfContext);
+            [NSGraphicsContext restoreGraphicsState];
+        }
+    }
+    
+    CGPDFContextClose(pdfContext);
+    CGContextRelease (pdfContext);
+    
+    return pdfData;
+}
 
 @end

+ 7 - 7
PDF Office/PDF Master/Class/PDFWindowController/ViewController/KMMainViewController.xib

@@ -1,8 +1,8 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="21507" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
+<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="22155" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
     <dependencies>
         <deployment identifier="macosx"/>
-        <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="21507"/>
+        <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="22155"/>
         <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
     </dependencies>
     <objects>
@@ -44,10 +44,6 @@
             <subviews>
                 <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="Qt3-H1-Txz">
                     <rect key="frame" x="667" y="347" width="1" height="1"/>
-                    <constraints>
-                        <constraint firstAttribute="height" constant="0.10000000000000001" id="3Ah-UW-M3a"/>
-                        <constraint firstAttribute="width" constant="0.10000000000000001" id="Iz6-2Y-Kn5"/>
-                    </constraints>
                     <buttonCell key="cell" type="bevel" bezelStyle="rounded" alignment="center" imageScaling="proportionallyDown" inset="2" id="RgE-Pm-Sre">
                         <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
                         <font key="font" metaFont="system"/>
@@ -55,6 +51,10 @@
 Gw
 </string>
                     </buttonCell>
+                    <constraints>
+                        <constraint firstAttribute="height" constant="0.10000000000000001" id="3Ah-UW-M3a"/>
+                        <constraint firstAttribute="width" constant="0.10000000000000001" id="Iz6-2Y-Kn5"/>
+                    </constraints>
                     <connections>
                         <action selector="exitFullScreen:" target="-2" id="eVN-b0-2s4"/>
                     </connections>
@@ -240,7 +240,7 @@ Gw
                     </constraints>
                     <imageCell key="cell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyDown" image="icon_tip_info_small" id="OeM-gK-2cL"/>
                 </imageView>
-                <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="wp0-L3-5I3">
+                <textField focusRingType="none" horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="wp0-L3-5I3">
                     <rect key="frame" x="21" y="8" width="734" height="17"/>
                     <textFieldCell key="cell" lineBreakMode="clipping" title="Please use the scroll bar, thumbnail tool to locate the target page, click or box the area to select the target range." id="P3j-kh-acn">
                         <font key="font" metaFont="system" size="14"/>

+ 1 - 0
PDF Office/PDF Master/PDF_Reader_Pro DMG-Bridging-Header.h

@@ -90,3 +90,4 @@
 #import "NSGraphics_SKExtensions.h"
 #import "NSString+Utils.h"
 #import "NSEvent+PDFListView.h"
+#import "NSURL+Utils.h"

+ 1 - 0
PDF Office/PDF Master/PDF_Reader_Pro Edition-Bridging-Header.h

@@ -86,3 +86,4 @@
 #import "NSGraphics_SKExtensions.h"
 #import "NSString+Utils.h"
 #import "NSEvent+PDFListView.h"
+#import "NSURL+Utils.h"

+ 1 - 0
PDF Office/PDF Master/PDF_Reader_Pro-Bridging-Header.h

@@ -86,3 +86,4 @@
 #import "NSGraphics_SKExtensions.h"
 #import "NSString+Utils.h"
 #import "NSEvent+PDFListView.h"
+#import "NSURL+Utils.h"