创建一个Word文档,Swift [英] Create a word document, Swift

查看:322
本文介绍了创建一个Word文档,Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a Word document in my Swift app; just some plain text in a certain font as a .docx file. I haven't found a way to create a word document, but my best guess is that I could import a word document into my Xcode project with just the text "Hello World" in it, then in my code replace every occurrence of "Hello World" with the desired text.

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

How might I go about altering the text of a .docx file in my swift project?

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

Edit (here's why I need this): I want to create a .docx file so that the user can export whatever text the type in into the Google Docs app or Pages app. I understand the usage of UIDocumentInteractionController to export preexisting documents, but I need to figure out how I can write and save text to a Word document.

推荐答案

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

Unfortunately, it is nearly impossible to create a .docx file in Swift, given how complicated they are (you can see for yourself by changing the file extension on any old .docx file to .zip, which will reveal their inner structure). The next best thing is to simply create a .txt file, which can also be opened into Pages (though sadly not Docs). If you're looking for a more polished format, complete with formatting and possibly even images, you could choose to create a .pdf file.

以下一些示例代码可能会有所帮助:

Here are some code samples that might be of assistance:

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

Creating and sharing a .txt file in Swift 3:

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文件并打开该文件的共享对话框.

to instantly create a txt file and open the share dialog for it.


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

Creating and sharing a simple .pdf file in Swift 3:

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文件并打开它的共享对话框.

to instantly create a pdf file and open the share dialog for it.

编辑:找到了一种有趣的(尽管未完善)的变通方法来使文本在Google文档中打开:使用此处创建.txt文件"部分中的函数,然后进行更改文件名为"\(title).docx".这会使Docs误以为它是.docx文档,从而可以成功在Docs中打开文本.不幸的是,这会创建一个无效的文档,而Pages,Word或其他任何应用程序都无法打开该文档,因为它不能实际上创建真实的文档文件.而且,Interaction Controller会让用户看到它,就像他们也可以在Pages中打开它一样,尽管这总是会失败.

Found an interesting (though not polished) workaround to getting text to open up in Google Docs: use the function from the "creating a .txt file" section here, and just change the filename to "\(title).docx". This will fool Docs into thinking it's a .docx document, which will allow the text to open in Docs successfully. Unfortunately, this creates an invalid document that can't be opened by Pages, Word, or really any other app because it doesn't actually create a real document file. And the Interaction Controller will make it look to the user like they can also open it in Pages, though that invariably fails.

这篇关于创建一个Word文档,Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆