【问题标题】:Create a word document, Swift [closed]创建一个word文档,Swift [关闭]
【发布时间】:2016-08-03 18:50:56
【问题描述】:

我正在尝试在我的 Swift 应用程序中创建一个 Word 文档;只是某种字体的一些纯文本作为.docx 文件。我还没有找到创建 word 文档的方法,但我最好的猜测是我可以将 word 文档导入到我的 Xcode 项目中,其中只有文本“Hello World”,然后在我的代码中替换每次出现的“Hello世界”与所需的文本。

在我的 swift 项目中如何更改 .docx 文件的文本?

编辑(这就是我需要这个的原因):我想创建一个.docx 文件,以便用户可以将输入的任何文本导出到 Google 文档应用程序或 Pages 应用程序中。我了解UIDocumentInteractionController 用于导出预先存在的文档的用法,但我需要弄清楚如何编写文本并将其保存到 Word 文档中。

【问题讨论】:

  • 这个问题太宽泛,不适合 Stack Overflow。它尚未关闭的唯一原因是附加的赏金。
  • 很遗憾,一旦有人向其添加了赏金,您就无法将糟糕的帖子标记为关闭。

标签: ios swift


【解决方案1】:

不幸的是,考虑到它们的复杂性,在 Swift 中创建 .docx 文件几乎是不可能的(您可以通过将任何旧的 .docx 文件的文件扩展名更改为 .zip 来亲自查看,这将揭示它们的内部结构)。下一个最好的事情是简单地创建一个.txt 文件,该文件也可以在 Pages 中打开(但遗憾的是不是 Docs)。如果您正在寻找更精致的格式,包括格式甚至图像,您可以选择创建一个.pdf 文件。


以下是一些可能有帮助的代码示例:

在 Swift 3 中创建和共享 .txt 文件:

func export(_ string: String, title: String) throws {
    // create a file path in a temporary directory
    let fileName = "\(title).txt"
    let filePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(fileName)

    // save the string to the file
    try string.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)

    // open share dialog

        // Initialize Document Interaction Controller
    self.interactionController = UIDocumentInteractionController(url: URL(fileURLWithPath: filePath))
        // Configure Document Interaction Controller
        self.interactionController!.delegate = self
        // Present Open In Menu
    self.interactionController!.presentOptionsMenu(from: yourexportbarbuttonoutlet, animated: true) // create an outlet from an Export bar button outlet, then use it as the `from` argument
}

这可以调用

export("Hello World", title: "HelloWorld")

立即创建一个 txt 文件并为其打开共享对话框。


在 Swift 3 中创建和共享一个简单的 .pdf 文件:

func openPDF(_ string: String, title: String) throws {
    // 1. Create a print formatter

    let html = "<h2>\(title)</h2><br><h4>\(string)</h4>" // create some text as the body of the PDF with html.

    let fmt = UIMarkupTextPrintFormatter(markupText: html)

    // 2. Assign print formatter to UIPrintPageRenderer

    let render = UIPrintPageRenderer()
    render.addPrintFormatter(fmt, startingAtPageAt: 0)

    // 3. Assign paperRect and printableRect

    let page = CGRect(x: 10, y: 10, width: 595.2, height: 841.8) // A4, 72 dpi, x and y are horizontal and vertical margins
    let printable = page.insetBy(dx: 0, dy: 0)

    render.setValue(NSValue(cgRect: page), forKey: "paperRect")
    render.setValue(NSValue(cgRect: printable), forKey: "printableRect")

    // 4. Create PDF context and draw

    let pdfData = NSMutableData()
    UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)

    for i in 1...render.numberOfPages {

        UIGraphicsBeginPDFPage();
        let bounds = UIGraphicsGetPDFContextBounds()
        render.drawPage(at: i - 1, in: bounds)
    }

    UIGraphicsEndPDFContext();

    // 5. Save PDF file

    var path = "\(NSTemporaryDirectory())\(title).pdf"
    pdfData.write(toFile: path, atomically: true)
    print("open \(path)") // check if we got the path right.
        // open share dialog
        print("opening share dialog")
        // Initialize Document Interaction Controller
        self.interactionController = UIDocumentInteractionController(url: URL(fileURLWithPath: path))
        // Configure Document Interaction Controller
        self.interactionController!.delegate = self
        // Present Open In Menu
        self.interactionController!.presentOptionsMenu(from: yourexportbarbuttonoutlet, animated: true) // create an outlet from an Export bar button outlet, then use it as the `from` argument
}

这可以用

调用
openPDF("Hello World", title: "HelloWorld")

立即创建一个 pdf 文件并为其打开共享对话框。


编辑: 找到了一个有趣的(虽然不是经过完善的)解决方法来在 Google 文档中打开文本:使用此处“创建 .txt 文件”部分中的函数,然后进行更改"\(title).docx" 的文件名。这会使 Docs 误以为这是一个 .docx 文档,这将允许文本在 Docs 中成功打开。不幸的是,这会创建一个无法由 Pages、Word 或任何其他应用程序打开的无效文档,因为它实际上并没有创建一个真正的文档文件。并且交互控制器会让用户看起来好像他们也可以在 Pages 中打开它,尽管这总是失败。

【讨论】:

  • 虽然你并没有真正解决这里的全部问题,但你提供了一个很好的解释和一些不错的选择,所以这里有一些互联网点。
  • @JohnRamos 是的,这有点不幸,但这确实是我能找到的唯一答案。
  • 很棒的帖子!非常感谢您的 pdf 教程!
  • @LinusG。别客气!乐于助人:D
【解决方案2】:

您不能直接在 Word 文档中“编辑文本”。 .docx 文件实际上是一个 ZIP 文件,其内部具有一定的文件/文件夹结构(尝试将其重命名为 .zip 并解压即可),符合“Office Open XML”格式(@987654321 @)。

如果没有库可以在 Swift 中修改 Office OpenXML 格式,您可能只需要自己编写代码。但是,如果您有简单的要求(只是一些纯文本,正如您所说),这应该不会太复杂。

Microsoft 在 GitHub 中有一个 OpenXML 库,地址为 https://github.com/OfficeDev/Open-XML-SDK,它可能对您有所帮助。

【讨论】:

  • 我没有找到任何库。如果你能给我指出 Github 项目的相关文件,那就太好了(它是如此庞大)。
  • 是的,它非常大......他们为所有元素提供了很多类,并解析它们并添加限制。将它们拼凑在一起需要一点时间。另一种选择是保存一个基本的 DOCX 文件和一种逆向工程/找出你需要修改的内容。
【解决方案3】:

鉴于您提到一位用户想要将文档传输到 Google 文档,您可以考虑改用 RTF 格式。您还可以将 docx 文件导出为 RTF 格式,然后进行处理,完成后,将修改后的 RTF 文件直接导入 Google 文档。

我建议这样做,因为 RTF 也是一种可行的开放格式:请参阅 https://www.safaribooksonline.com/library/view/rtf-pocket-guide/9781449302047/ch01.html。根据该参考,您可以生成这个简单的 (ascii) 输出:

{\rtf1\ansi\deff0 {\fonttbl {\f0 Verdana;}}
\f0\fs16
Hello World!
}

并将其保存为扩展名为 .rtf 的文件。

【讨论】:

  • 好的,我可以成功创建和共享 rtf 文件,但是 UIDocumentInteractionController 没有在页面中打开或在文档中打开作为选项,这与至少有页面作为选项的 txt 文件不同。我该怎么做才能让 Pages 打开 rtf?而且我知道我正在正确地创建文件,因为当我通过空投将它导出到我的 Mac 时,它看起来很棒。
  • 页面无法打开 RTF。 Docs 也不能。所以即使我可以成功地用它制作一个 RTF,我也无法打开它。
  • 好的,我不知道 Pages 和 Docs 都不能打开 RTF 文件。
  • 是的,我也没有……不用担心,感谢您的帮助。
猜你喜欢
  • 2014-03-04
  • 2021-03-05
  • 2014-01-03
  • 2010-09-05
  • 2010-11-05
  • 2010-09-12
  • 1970-01-01
相关资源
最近更新 更多