So I'm building a macOS app and I would like it to save or export a copy of this text file the app creates as a PDF file as well. I'm a beginner and I'm not sure how to proceed.
Note: I tried to change .txt to .pdf but the PDF cannot be opened due to incorrect file formatting.
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.")
}
}
An easy way to create PDF data from a string is by using a
NSTextView
.Example: