【问题标题】:How to export a text file as a PDF file (macOS Swift)?如何将文本文件导出为 PDF 文件(macOS Swift)?
【发布时间】: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.")
                                                         
        }
    }

This is what the text file looks like:

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

【问题讨论】:

  • 打印出字符串,让用户将其保存为PDF文档。
  • 文本应该是什么样子?
  • @Willeke 我希望 pdf 文本看起来像文本文件中的文本。就像您转到实际的文本文件并将其另存为 pdf 一样。这就是我正在寻找的内容。
  • @Willeke 我在我的问题中添加了一张图片。
  • @ElTomato 我不知道怎么写这个。你介意举个例子吗?

标签: swift macos pdf text document-directory


【解决方案1】:

从字符串创建 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)
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-15
    • 2018-07-23
    • 1970-01-01
    • 2022-12-15
    • 2019-03-19
    • 1970-01-01
    • 2014-02-04
    • 1970-01-01
    相关资源
    最近更新 更多