在swift 3中将字节数组转换为PDF

时间:2017-06-26 07:24:20

标签: ios arrays swift swift3

我要做的是,从api响应中获取字节数组响应,并将其保存到文件(PDF)。

(服务器返回一个bytearray)

使用Alamofire进行网络请求

Alamofire.request("\(BaseUrl)api/mobile/downloadResume", headers : ProfileViewHeader)
        .response { response in
    print(response)
        // let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        // let filePath = "\(documentsPath)/readingfile.pdf"
        // let data:NSData = NSKeyedArchiver.archivedData(withRootObject: response.data) as NSData
        // let file = data.write(toFile: filePath, atomically: false)
}

得到字节数组响应没有任何问题,

我的主要问题是如何将字节数组保存在文件中。我在Android中做了同样的事情没有任何问题,但在swift中无法实现相同的目标,

任何形式的帮助将不胜感激。请帮帮我。

由于

2 个答案:

答案 0 :(得分:1)

使用Alamofire,结果是内部数据。您可以这样做以保存在文档目录下的文件中。

   override func viewDidAppear(_ animated: Bool) {


    Alamofire.request("LINK", headers : nil)
    .response { response in
        print(response.data ?? "")


        self.createPDF(pdfData: response.data!)
    }
}


func createPDF( pdfData : Data) {
    let render = UIPrintPageRenderer()

    let html = "<b>Hello <i>World!</i></b> <p>Generate PDF file from HTML in Swift</p>"
    let fmt = UIMarkupTextPrintFormatter(markupText: html)

    render.addPrintFormatter(fmt, startingAtPageAt: 0)

    // 3. Assign paperRect and printableRect

    let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
    let printable = page.insetBy(dx: 0, dy: 0)

    render.setValue(NSValue(cgRect: page), forKey: "paperRect")
    render.setValue(NSValue(cgRect: printable), forKey: "printableRect")

    // 4. Create PDF context and draw
    //let pointzero = CGPoint(x: 0,y :0)
    let rect = CGRect.zero


    let data = NSMutableData(base64Encoded: pdfData.base64EncodedData(), options: NSData.Base64DecodingOptions.ignoreUnknownCharacters);

    UIGraphicsBeginPDFContextToData(data!, rect, nil)


    for i in 1...render.numberOfPages {

        UIGraphicsBeginPDFPage();
        let bounds = UIGraphicsGetPDFContextBounds()
        render.drawPage(at: i - 1, in: bounds)
    }

    UIGraphicsEndPDFContext();

    let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

    // 5. Save PDF file
    do {
        let fileURL = try documentsPath.asURL().appendingPathComponent("file.pdf")
       try pdfData.write(to: fileURL, options: .atomic)

    } catch {

    }


    print("saved success")
}

createPDF函数将获取您的字节数组并基于此生成新的pdf文件。 另一种通用的方法就是保存它,就像它来自服务器一样

         let documentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

        // Save to a file
        let fileURL = documentDirectory.appendingPathComponent("file.pdf")


        do {
            try  response.data?.base64EncodedData().write(to: fileURL, options: .atomic)
        } catch {
            print(error)
        }

答案 1 :(得分:1)

对于未来的读者来说,这对我使用swiftyJson有用:

let documentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

let fileURL = documentDirectory.appendingPathComponent("TEST2.pdf")

let bytes = json["Recibo"].arrayObject as! [UInt8]

let data = Data(bytes);
data.write(to: fileURL, options: .atomic)