【问题标题】:How to recover PDF's from .writetoFile in Swift如何在 Swift 中从 .writetoFile 恢复 PDF
【发布时间】:2016-06-27 00:11:40
【问题描述】:

我正在使用 .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
}

我以后如何取回图像?

【问题讨论】:

标签: objective-c xcode swift writetofile


【解决方案1】:

这是一个在 Swift 2.x 中如何做到这一点的示例。

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

直接来自我的游乐场:

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!)

【讨论】:

    【解决方案2】:

    您需要记住 URL 保存您要存储的图像/pdf 的位置。

    为了取回它,您可以使用NSData 类来获取该 url 处文件的内容。

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

    【讨论】:

    • 我正在获取这样的图像:
    • 让路径:字符串? = NSBundle.mainBundle().pathForResource("testgogo", ofType: "pdf", inDirectory: "DirectoryName/Images") 让 imageFromPath = UIImage(contentsOfFile: path!)! self.image.image = imageFromPath
    • 我有点困惑。在你的问题中,你正在写一个pdf,买你真的需要一张图片吗?
    • 我正在保存一个 pdf,因为 png 没有正确保存
    • 如果您将其保存为pdf,您将无法使用UIImage(named:)
    【解决方案3】:

    看起来问题可能是您尝试将 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 我从这里得到这个代码:How to Load Local PDF in UIWebView in Swift

    【讨论】:

    【解决方案4】:

    在另一个answer中使用代码的略微修改版本

    我有以下代码:

    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 中。我唯一改变的是创建一个返回文档目录的惰性变量,并且我使用一个常量作为文件路径。

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

    【讨论】:

    • 我需要保存一张图片和上面的值标签。我应该使用这样的代码: 添加图像。我应该如何定位每个字段?
    • 您正在处理一些复杂的逻辑,我已经在另一个问题中向您展示了如何使用 swift 合并图像和文本,这个问题是关于保存和检索我也向您展示的 PDF 文件。使用 HTML 将以类似的方式工作,它将元素相互叠加,不会组合它们。我建议您使用 UIKit 元素重新创建表单的 swift 版本,然后使用已经显示的方法截取您拥有的视图或在需要时绘制最终结果
    • 我应该如何创建它?
    猜你喜欢
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    相关资源
    最近更新 更多