如何从 Swift 中的 .writetoFile 恢复 PDF

How to recover PDF's from .writetoFile in Swift

我正在使用 .writetofile 保存图像,但我不知道如何恢复它。 这是我保存图像的方式:

self.pdfData.writeToURL(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.URLByAppendingPathComponent("testgogo.pdf"), atomically: true) // what it is saved as


        self.pdfData.writeToFile("tessst.pdf", atomically: false)
        print(NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!.path!)


        var pdfData: NSData {
            let result = NSMutableData()
            UIGraphicsBeginPDFContextToData(result, frame, nil)
            guard let context = UIGraphicsGetCurrentContext()
  else { return result }

     UIGraphicsBeginPDFPage()
     layer.renderInContext(context)
     UIGraphicsEndPDFContext()
     return result
}

以后如何取回图像?

您需要记住 URL 保存您正在存储的 image/pdf 的位置。

为了取回,可以使用NSDataclass获取url处的文件内容。

dataWithContentsOfURL:(NSURL *)aURL 是一个很好的起点。

看来问题可能出在您尝试将 pdf 文件作为图像加载时不起作用。试试这个方法:

if let pdfURL = NSBundle.mainBundle().URLForResource("myPDF", withExtension: "pdf", subdirectory: nil, localization: nil),data = NSData(contentsOfURL: pdfURL), baseURL = pdfURL.URLByDeletingLastPathComponent  {
    let webView = UIWebView(frame: CGRectMake(20,20,self.view.frame.size.width-40,self.view.frame.size.height-40))
    webView.loadData(data, MIMEType: "application/pdf", textEncodingName:"", baseURL: baseURL)
    self.view.addSubview(webView)
}

Ps 我从这里得到了这段代码:

在另一个

中使用稍微修改过的代码版本

我有以下代码:

class ViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    lazy var documentsPath = {
       return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    }()
    let fileName = "file.pdf"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        createPDF()

        loadPDF()
    }

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

        // 2. Assign print formatter to UIPrintPageRenderer

        let render = UIPrintPageRenderer()
        render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)

        // 3. Assign paperRect and printableRect

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

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

        // 4. Create PDF context and draw

        let pdfData = NSMutableData()
        UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil)

        for i in 1...render.numberOfPages() {

            UIGraphicsBeginPDFPage();
            let bounds = UIGraphicsGetPDFContextBounds()
            render.drawPageAtIndex(i - 1, inRect: bounds)
        }

        UIGraphicsEndPDFContext();

        // 5. Save PDF file

        pdfData.writeToFile("\(documentsPath)/\(fileName)", atomically: true)
    }

    func loadPDF() {

        let filePath = "\(documentsPath)/\(fileName)"
        let url = NSURL(fileURLWithPath: filePath)
        let urlRequest = NSURLRequest(URL: url)
        webView.loadRequest(urlRequest)
    }
}

此代码有效,它创建一个 PDF 文件,然后将同一个 PDF 文件加载到 webView 中。我唯一改变的是创建一个 returns 文档目录的惰性变量,我使用常量作为文件路径。

您应该能够使用相同的方法来保存和检索您的 PDF 文件。

这是一个示例,说明如何在 Swift 2.x 中执行此操作。

它使用NSData(contentsOfFile: myFilePath)加载文件。 该示例使用 PNG 文件。

直接来自我的 Playground:

import UIKit

/*
 * Creates an UIImage from a UIView
 */
func createImage(fromView view: UIView) -> UIImage {
    UIGraphicsBeginImageContext(view.frame.size)
    let context = UIGraphicsGetCurrentContext()
    view.layer.renderInContext(context!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext();
    return image
}

/*
 * Finds the path in Document folder
 */
func createMyFilePath(forFileName fileName: String) -> String? {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask,true)
    if let path = paths.first {
        return path + "/\(fileName)"
    }
    return nil
}

/*
 * Main behaviour
 */

// ImageView with Label on it
let imageView = UIImageView(image: UIImage(named: "borat"))
let label = UILabel(frame: imageView.frame)
label.font = UIFont(name: "helvetica", size: 40)
label.text = "Great Success!"
imageView .addSubview(label)

// Find the path where to save
guard let myFilePath = createMyFilePath(forFileName: "borat-with-label.png") else {
    print("Cannot generate file path ☹️")
    exit(0)
}

// Use this to check in finder where your file is saved
print(myFilePath)

// Transform the imageView in UIImage to save it
let imageToSave = createImage(fromView: imageView)

// Get the image as data
guard let imageToSaveAsData = UIImagePNGRepresentation(imageToSave) else {
    print("Cannot transform image to data ☹️")
    exit(1)
}

// Save to Disk!
do{
    try imageToSaveAsData.writeToFile(myFilePath, options: .DataWritingAtomic)
} catch {
    print("Error, cannot write to the location \(myFilePath)")
}

// Load from Disk!
let loadedImageData = NSData(contentsOfFile: myFilePath)

// Check the data is the same
if loadedImageData == imageToSaveAsData {
    print("✌️")
}

// Have a look at the loaded image!
UIImage(data: loadedImageData!)