为什么HTML到PDF转换在iPad上失败但在Simulator上工作

时间:2017-06-17 18:27:26

标签: ipad swift3 pdf-generation ios-simulator wkwebview

我的应用程序使用WKWebView显示HTML页面,然后使用我从SO复制的功能将页面转换为PDF。转换在模拟器上运行但在实际设备上失败。如下所示,pdf数据的大小在模拟器上是正确的,但在设备上显着缩短,表明转换失败。我可以在模拟器上查看转换后的PDF。 viewController如下所示。我使用的是OS 10.3。我还在iPhone 6+和模拟器上进行了测试。同样的问题。

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)")
        }

    }



}

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

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

  

fileSize = 302726

在设备上运行:iPad4(128 G) 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

0 个答案:

没有答案