所以我正在构建一个 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.")
}
}