Create a Word Document, Swift

Create a word document, Swift

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:

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
}

This can be called with

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

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


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
}

This can be called with

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

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


Edit: 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.

Creating *.docx (and maybe *.doc ?) documents in the fly?

Thanks to @moritz (in the comments) I found this question that suggest libopc which is what I was looking for.
How to create .doc file or word processor in iOS application?

How to create and save a .rtf, .doc, .docx in Objective-C for iOS

RTF is going to be the easiest, because it's a plain text format. It's kind of like HTML, but without closing tags. Here is a class for writing an RTF, but it requires a lot of dependencies from elsewhere in the framework.

DOCX would be rather difficult. It's actually a zip file, containing a few XML files. You can examine the format yourself by changing the .docx extension to .zip and unzipping it. But even though XML is a fairly easy to write format, the way the text attributes are organized is still rather complicated. Also, I recall that it has to be zipped in a very specific way to be read properly.

As for DOC, it will be very difficult because it's such a complex format. You could look into some open source projects, like Abiword or Word2x. Be careful using their code because the licenses may not agree with the App Store rules.

Converting Docx Files To Text In Swift

Your initial issue is with how you get the string from the URL. String(File_Name) is not the correct way to convert a file URL into a file path. The proper way is to use the path function.

let location = NSURL.fileURLWithPath(NSTemporaryDirectory())
let fileURL = location.URLByAppendingPathComponent("My File.docx")
let fileContent = try? NSString(contentsOfFile: fileURL.path, encoding: NSUTF8StringEncoding)

Note the many changes. Use proper naming conventions. Name variables more clearly.

Now here's the thing. This still won't work because a docx file is a zipped up collection of XML and other files. You can't load a docx file into an NSString. You would need to use NSData to load the zip contents. Then you would need to unzip it. Then you would need to go through all of the files and find the desired text. It's far from trivial and it is far beyond the scope of a single stack overflow post.

How to generate a word file programmatically from collected data in iPhone sdk

Short answer yes, long answer:

You can't do this to create "proper" Word documents, however you should be able to acomplish this on any platform by building the word doc from HTML and saving it with a .doc extension (instead of HTML). You can put anything in there, custom layouts - I'd probably stick to paragraphs and tables and floated elements (like imgs and such).

There may be extra code you will need in the HTML doc (for instance to make it open in page view rather than in HTML view) but you can figure all that out by saving a word doc in HTML format. :) There's also a lot of information on the internet about it if you know where to look.

I did something like this not long ago. I'll see if I can find an example and post it here.

Update

This is the only "custom" stuff I have in my html word doc:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:w="urn:schemas-microsoft-com:office:word"
xmlns="http://www.w3.org/TR/REC-html40">

And this - to make it open in Page view:

<!--[if gte mso 9]><xml> 
<w:WordDocument>
<w:View>Print</w:View>
<w:Zoom>100</w:Zoom>
</w:WordDocument>
</xml><![endif]-->

The rest of it is just standard HTML and CSS (remember to put CSS INSIDE the HTML document in <style> tags - word isn't going to remotely fetch your css files).

Convert text to .docx document file and open share dialog, Swift 2

I figured this one out for you.

Take this answer user Casey made, and just change this line:

let fileName = "\(title).txt"

to this

let fileName = "\(title).docx"

and Swift will figure out that you want to export your text as a document, and convert it automatically.

How to open the Document files e.g(.pdf,.doc,.docx) in ios mobile when a button action using swift3.0?

Swift 3*, 4*,

To open document and select any document, you are using UIDocumentPickerViewController then all documents presented in your iCloud, Files and in Google Drive will be shown if Google Drive is connected in user device. Then selected document need to download in your app and from there you can show it in WKWebView,

   @IBAction func uploadNewResumeAction(_ sender: Any) {

/* let documentPicker = UIDocumentPickerViewController(documentTypes: ["com.apple.iwork.pages.pages", "com.apple.iwork.numbers.numbers", "com.apple.iwork.keynote.key","public.image", "com.apple.application", "public.item","public.data", "public.content", "public.audiovisual-content", "public.movie", "public.audiovisual-content", "public.video", "public.audio", "public.text", "public.data", "public.zip-archive", "com.pkware.zip-archive", "public.composite-content", "public.text"], in: .import) */

let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.text", "com.apple.iwork.pages.pages", "public.data"], in: .import)

documentPicker.delegate = self
present(documentPicker, animated: true, completion: nil)
}

extension YourViewController: UIDocumentPickerDelegate{

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {

let cico = url as URL
print(cico)
print(url)

print(url.lastPathComponent)

print(url.pathExtension)

}
}

Note: If you intend to select all files the you have to use following code:

  let documentPicker = UIDocumentPickerViewController(documentTypes: ["com.apple.iwork.pages.pages", "com.apple.iwork.numbers.numbers", "com.apple.iwork.keynote.key","public.image", "com.apple.application", "public.item","public.data", "public.content", "public.audiovisual-content", "public.movie", "public.audiovisual-content", "public.video", "public.audio", "public.text", "public.data", "public.zip-archive", "com.pkware.zip-archive", "public.composite-content", "public.text"], in: .import) 

In your action method.



Related Topics



Leave a reply



Submit