nsprintoperation - 检查用户选择了什么

时间:2017-07-24 15:55:00

标签: swift macos cocoa pdf printing

使用此代码我可以打印pdf文件:

let dictDocuments = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
let completePath = dictDocuments.appendingPathComponent("test.pdf")
let pdfDocument = PDFDocument(url: completePath!)

let printInfoDict = NSMutableDictionary(dictionary: NSPrintInfo.shared().dictionary())
printInfoDict.setObject(NSPrintSpoolJob, forKey: NSPrintJobDisposition as NSCopying)
let printInfo = NSPrintInfo(dictionary: printInfoDict as! [String : Any])
printInfo.isHorizontallyCentered = true
printInfo.isVerticallyCentered = true
printInfo.scalingFactor = 1.5


let printOp = pdfDocument!.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true)!
printOp.runModal(for: self.view.window!, delegate: self, didRun: nil, contextInfo: nil)

我可以检查用户在打印面板中选择了哪个按钮? (取消或打印)

2 个答案:

答案 0 :(得分:0)

来自documentation

  

didRunSelector参数指定的方法必须具有以下签名:

func printOperationDidRun(_ printOperation NSPrintOperation, success: Bool, contextInfo: UnsafeMutableRawPointer?)
     

如果打印操作在没有取消或错误的情况下运行完成,则成功值为true,否则为false

     

如果将canSpawnSeparateThread发送到参数为NSPrintOperation的{​​{1}}对象,则后续调用true中指定的委托可能会在该生成中发送,非主线。

答案 1 :(得分:0)

迅速5.1:

// prepare printOp
...

{
        //was: printOp.run()

        if let w = NSApp.mainWindow{
            let selector = #selector(printOperationDidRun(printOperation: success: contextInfo:))
            printOp.runModal(for: w, delegate: self,
                             didRun: selector,
                             contextInfo: nil)
        }
    }

    // apple docs:
    // - (void)printOperationDidRun:(NSPrintOperation *)printOperation  success:(BOOL)success  contextInfo:(void *)contextInfo

     @objc func printOperationDidRun( printOperation: NSPrintOperation,
                                      success: Bool,
                                      contextInfo: UnsafeMutableRawPointer?){
        // use callback..

    }