【发布时间】:2021-09-20 18:39:27
【问题描述】:
所以我正在构建一个 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文档。
-
文本应该是什么样子?
-
@Willeke 我希望 pdf 文本看起来像文本文件中的文本。就像您转到实际的文本文件并将其另存为 pdf 一样。这就是我正在寻找的内容。
-
@Willeke 我在我的问题中添加了一张图片。
-
@ElTomato 我不知道怎么写这个。你介意举个例子吗?
标签: swift macos pdf text document-directory