0

所以我正在构建一个 macOS 应用程序,我希望它也可以将应用程序创建的这个文本文件的副本保存或导出为 PDF 文件。我是初学者,我不确定如何进行。

注意:我尝试将 .txt 更改为 .pdf,但由于文件格式不正确,无法打开 PDF。

 let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0]
        let docURL = URL(string: documentsDirectory)!
        let dataPath = docURL.appendingPathComponent("User_Notes") // this is the folder name
        let stringToWrite = 
""" 
User: Smith John Apple
Today's Date:  07/11/2021
This is a a note that the user writes in the app.
"""

        if !FileManager.default.fileExists(atPath: dataPath.path) || FileManager.default.fileExists(atPath: dataPath.path) {
            do {
                try
                    FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
                                    
                try stringToWrite.write(toFile: "\(dataPath/\(dateField.stringValue)/\(userName.stringValue))).txt", atomically: true, encoding: String.Encoding.utf8)
                
            } catch {
                print(error.localizedDescription)
            }
        }
        
        if error != nil {
                                                         
            print("Error saving user data.")
                                                         
        }
    }

这是文本文件的样子:

这就是我希望 PDF 的样子:

4

1 回答 1

2

从字符串创建 PDF 数据的一种简单方法是使用NSTextView.

例子:

    let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let docURL = urls[0]
    let dataURL = docURL.appendingPathComponent("User_Notes")
    
    let stringToWrite = 
"""
User: Smith John Apple
Today's Date:  07/11/2021

This is a a note that the user writes in the app.
"""
    let txtData = Data(stringToWrite.utf8)
    
    // create a NSTextView
    let textView = NSTextView(frame: NSRect(x: 0, y: 0, width: 612, height: 791))
    textView.textContainerInset = NSSize(width: 50, height: 50)
    
    // add font attribute to the string and insert in the NSTextView
    if let font = NSFont(name: "Menlo", size: 11) {
        let attributedString = NSAttributedString(string: stringToWrite, attributes: [.font: font])
        textView.insertText(attributedString, replacementRange: NSRange(location: 0, length: 0))
    }
    else {
        textView.insertText(stringToWrite, replacementRange: NSRange(location: 0, length: 0))
    }
    
    // generate pdf data
    let pdfData = textView.dataWithPDF(inside: textView.bounds)

    // write data to files
    do {
        try FileManager.default.createDirectory(at: dataURL, withIntermediateDirectories: true, attributes: nil)
        let documentName = "\(dateField.stringValue)_\(userName.stringValue)"
        try txtData.write(to: dataURL.appendingPathComponent("\(documentName).txt"), options: .atomic)
        try pdfData.write(to: dataURL.appendingPathComponent("\(documentName).pdf"), options: .atomic)
    } catch {
        print(error.localizedDescription)
    }
于 2021-07-13T22:16:56.393 回答