Swift 3 打印功能

1. 加载到webview再打印

2. 直接打印nsdata

func printViaWebView(fileName: String)
{
 let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = "\(documentsPath)/\(filename)"
        let url = NSURL(fileURLWithPath: filePath)
        let urlRequest = NSURLRequest(url: url as URL)
        
        webView.loadRequest(urlRequest as URLRequest)
        
        
        let pic = UIPrintInteractionController.shared
        let printInfo : UIPrintInfo = UIPrintInfo(dictionary: nil)
        
        printInfo.outputType = UIPrintInfoOutputType.general
        printInfo.jobName = url.absoluteString!
        
        pic.printInfo = printInfo
        pic.printFormatter = webView.viewPrintFormatter()
        pic.showsPageRange = false
        
        pic.present(animated: true, completionHandler: nil)
}

func printViaNSData(fileName: String){
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let filePath = "\(documentsPath)/\(filename)"
        let url = NSURL(fileURLWithPath: filePath)
        let urlRequest = NSURLRequest(url: url as URL)
        
        webView.loadRequest(urlRequest as URLRequest)
        
        
        let pic = UIPrintInteractionController.shared
        let printInfo : UIPrintInfo = UIPrintInfo(dictionary: nil)
        
        printInfo.outputType = UIPrintInfoOutputType.general
        //printInfo.jobName = url.absoluteString!
        //printInfo.orientation = .portrait
        
        pic.printingItem = NSData(contentsOfFile: filePath)
        pic.showsPaperSelectionForLoadedPapers = true;
        pic.showsPageRange = true;
        pic.showsNumberOfCopies = true;
        pic.printInfo = printInfo
        //pic.printFormatter = webView.viewPrintFormatter()
        
        pic.present(animated: true, completionHandler: nil)
}


已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页