为什么HTML到PDF的转换在iPad上失败,但在模拟器上可以工作

为什么HTML到PDF的转换在iPad上失败,但在模拟器上可以工作,ipad,swift3,pdf-generation,ios-simulator,wkwebview,Ipad,Swift3,Pdf Generation,Ios Simulator,Wkwebview,我的应用程序使用WKWebView显示HTML页面,然后使用我从SO复制的函数将页面转换为PDF。转换在模拟器上工作,但在实际设备上失败。如下图所示,pdf数据的大小在模拟器上是正确的,但在设备上则短得多,表明转换失败。我可以在模拟器上查看转换后的PDF。viewController如下所示。我正在使用OS10.3。我还测试了iphone6+和模拟器。同样的问题 import UIKit import WebKit class ViewController: UIViewController

我的应用程序使用WKWebView显示HTML页面,然后使用我从SO复制的函数将页面转换为PDF。转换在模拟器上工作,但在实际设备上失败。如下图所示,pdf数据的大小在模拟器上是正确的,但在设备上则短得多,表明转换失败。我可以在模拟器上查看转换后的PDF。viewController如下所示。我正在使用OS10.3。我还测试了iphone6+和模拟器。同样的问题

import UIKit
import WebKit

class ViewController: UIViewController {

    var webView: WKWebView?

    var dict = [String:String]()

    func fileToURL(file: String) -> URL? {
        // Get the full path of the file
        guard let document = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first) else {
            return nil
        }
        return URL(fileURLWithPath: document+file)
    }


    var activityButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()



        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "PDF", style: .plain, target: self, action: #selector(exportHTMLContentToPDF))
        let leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(backAction))
        navigationItem.leftBarButtonItem = leftBarButtonItem

        let config = WKWebViewConfiguration()
        let frame = view.frame
        webView = WKWebView(frame:frame , configuration:config)
        webView?.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
        let reportFilename = "report"
        createWebView(htmlFileName: reportFilename)




    }



    override func viewDidAppear(_ animated: Bool) {

    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    func createWebView(htmlFileName: String) {
        let url = Bundle.main.url(forResource: htmlFileName, withExtension: "html")!

        let webView = WKWebView()
        webView.loadFileURL(url, allowingReadAccessTo: url)
        webView.translatesAutoresizingMaskIntoConstraints = false

        self.view.addSubview(webView)

        // Auto Layout
        let views = ["webView": webView]
        let c1 = NSLayoutConstraint.constraints(withVisualFormat: "H:|[webView]|", options: [], metrics: nil, views: views)
        let c2 = NSLayoutConstraint.constraints(withVisualFormat: "V:[webView]|", options: [], metrics: nil, views: views)
        let c3 = NSLayoutConstraint(item: webView, attribute: .top, relatedBy: .equal, toItem: self.topLayoutGuide , attribute: .bottom, multiplier: 1, constant: 0)
        NSLayoutConstraint.activate(c1 + c2 + [c3])

        // Pass the reference to the View's Controller
        self.webView = webView
        URLCache.shared.removeAllCachedResponses()
        URLCache.shared.diskCapacity = 0
        URLCache.shared.memoryCapacity = 0


        let request = URLRequest(url: url)
        self.webView?.load(request)

    }



    func backAction() {

        dismiss(animated: true, completion: nil)

    }




    func exportHTMLContentToPDF(sender: UIBarButtonItem) {
        let filename = "report.pdf"
        createPdfFromView(aView: webView!, saveToDocumentsWithFileName: filename)

        //pdfDataWithWebView(webView: webView!, view:self.view, filename: filename)

    }

    func createPdfFromView(aView: UIView, saveToDocumentsWithFileName fileName: String)
    {

        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil)
        UIGraphicsBeginPDFPage()

        guard let pdfContext = UIGraphicsGetCurrentContext() else {
            print("ERROR: ",(#function))
            return }

        aView.layer.render(in: pdfContext)
        UIGraphicsEndPDFContext()

        if let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
            let documentsFileName = documentDirectories + "/" + fileName
            debugPrint(documentsFileName)
            pdfData.write(toFile: documentsFileName, atomically: true)
            let filePath = documentsFileName
            var fileSize : UInt64

            do {
                //return [FileAttributeKey : Any]
                let attr = try FileManager.default.attributesOfItem(atPath: filePath)
                fileSize = attr[FileAttributeKey.size] as! UInt64

                //if you convert to NSDictionary, you can get file size old way as well.
                let dict = attr as NSDictionary
                fileSize = dict.fileSize()
                print("fileSize = \(fileSize)")
            } catch {
                print("Error: \(error)")
            }

            print("SAVED: \(documentsFileName)")
        }

    }



}
整个项目是 这两种情况的控制台日志如下所示:

在模拟器上运行(iPad Air 2)

fileSize=302726

在设备上运行:iPad4(128克) 2017-06-17 13:56:34.865220-0400 testHTMLtoPDF[20652:5079739]无法向服务发出信号com.apple.WebKit.WebContent:113:找不到指定的服务 2017-06-17 13:56:34.871854-0400 testHTMLtoPDF[20652:5079739]无法向服务com.apple.WebKit.Networking发送信号:113:找不到指定的服务 “/var/mobile/Containers/Data/Application/E280AA2C-CF4D-4B9C-8777-CD4B87C95320/Documents/report.pdf”

fileSize=3812


物理设备也是iPad Air 2吗?你可以包括你正在使用的SDK。我正在使用iPad4。模拟器没有为iPad4提供选项。只有1台Pad Air、2台IPad Air和2台IPad pros。我正在使用最新的IOS SDK和Xcode 8版本。我还没有找到SDK版本的位置。