I need to grab all text from odf files (open document format) in C#. I found AODL library, and installed it. I visited AODL's page https://wiki.openoffice.org to find examples on how to do the task I need, but they were all unsuccessful. For a reason that I can't imagine, all examples build new document, and there's no example in how to load a document and grab all the text (something like OpenXML). Do you guys know any reference that can guide me?
My "try"
var doc = new AODL.Document.TextDocuments.TextDocument();
doc.Load(@"C:\path/to/Sample.odt");
But I can't figure out how to iterate with the doc document.
Finally, I figured out. This is the method I created to extract all the text. Maybe is not complete, because I don't know all the parts that form the .odt file. This method grabs headers and footers, textboxes and paragraphs and concatenate it with return carriage separator. You need the AODL package, that can be installed through package manager console: PM> Install-Package AODL
. And add
using AODL.Document.TextDocuments;
using AODL.Document.Content;
at the top of your program.
/// <summary>
/// Gets all plain text from an .odt file
/// </summary>
/// <param name="path">
/// the physical path of the file
/// </param>
/// <returns>a string with all text content</returns>
public String GetTextFromOdt(String path)
{
var sb = new StringBuilder();
using (var doc = new TextDocument())
{
doc.Load(path);
//The header and footer are in the DocumentStyles part. Grab the XML of this part
XElement stylesPart = XElement.Parse(doc.DocumentStyles.Styles.OuterXml);
//Take all headers and footers text, concatenated with return carriage
string stylesText = string.Join("\r\n", stylesPart.Descendants().Where(x => x.Name.LocalName == "header" || x.Name.LocalName == "footer").Select(y => y.Value));
//Main content
var mainPart = doc.Content.Cast<IContent>();
var mainText = String.Join("\r\n", mainPart.Select(x => x.Node.InnerText));
//Append both text variables
sb.Append(stylesText + "\r\n");
sb.Append(mainText);
}
return sb.ToString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With