How to export a text file as a PDF file (macOS Swift)?

723 Views Asked by At

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.")
                                                         
        }
    }

This is what the text file looks like:

This is what I would like the PDF to look like:

1

There are 1 best solutions below

0
On

An easy way to create PDF data from a string is by using a NSTextView.

Example:

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