Introduction
When it comes to printing from C#, you have many options. But I found this solution with Open Office very nice, elegant and easy.
OpenOffice is a free Office suite. You can download it from the internet and use it for free. In this article, I will show you how to use it to load, modify and print text documents from a program in C#.
Background
First of all, you should know that OpenOffice document is a zipped file. You can try to rename the sample.odt file (this file is contained in bin/Debug directory of my sample) to sample.zip. Now you will be able to unpack the file and inspect its contents. The most interesting file between the zip contents is the file content.xml. This file is a simple XML text file. You can extract it, modify and write back to sample.zip. If you rename sample.zip back to sample.odt, you should be able to open the modified document back in OpenOffice.
We will be doing exactly the same steps in the source code.
Using the Code
All the work for manipulating OpenOffice document text file is in the class called Odt
which stands for Open Document Text.
The constructor takes filename of the document to be opened. It extracts the zip contents using SharpZipLib and reads content.xml into XmlDocument
class. The XmlDocument
is then scanned for all input fields and these fields are placed in a collection that allows modifying fields text.
Odt doc = Odt("c:\\test.odt");
doc.Inputs["address"] = "My address";
You can modify the fields as you need. The resulting document can then be saved, opened in OpenOffice writer or printed on your default printer.
doc.Save("c:\\test_modified.odt");
doc.OpenInOo();
doc.Print();
If something goes wrong, you should check that you have OpenOffice installed. The searching for OpenOffice is hardcoded in Odt.cs and you may want to change it to suit your needs via static
variable:
Odt.OoExe = "path to your soffice.exe";>
The attached sample program shows how easy is to use the Odt
class. It displays all input fields of the document and has buttons for saving, opening and printing the modified document.
Thanks
I hope you enjoyed reading this article. See you next time.
Updates
I have added support for spreadsheet documents. You can get it here.