I have a requirement to find the list of fonts is being used in the word document(.docx) uploaded in the SharePoint 2013 Library? how can I do that?
1 Answer
The list of fonts in a word file is stored in an XML file called fonttable.xml
. To get this file, you need to convert the word file into a package (zip file) and parse the contents of fonttable.xml
.
Note: You need to add 2 references: DocumentFormat.OpenXml.dll
and WindowsBase.dll
to your project for handling word processing.
Following code handles getting the file from document library using CSOM and reading the file to get the fonts and stores them in a generic list.
ClientContext ctx = new ClientContext("http://siteUrl");
Microsoft.SharePoint.Client.ListItem listItem = ctx.Web.Lists.GetByTitle("Documents").GetItemById(itemID);
ctx.Load(listItem);
ctx.ExecuteQuery();
Microsoft.SharePoint.Client.File file = listItem.File;
ClientResult<Stream> data = file.OpenBinaryStream();
ctx.ExecuteQuery();
WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(data.Value, false);
var fontTable = wordprocessingDocument.MainDocumentPart.OpenXmlPackage.Package.GetPart(new Uri(@"/word/fontTable.xml", UriKind.Relative));
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNodeList xmlnode;
int i = 0;
Stream fs = fontTable.GetStream();
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("w:fonts");
var childNodes = xmlnode[0].ChildNodes;
List<string> allFonts = new List<string>();
for (i = 0; i <= childNodes.Count - 1; i++)
{
allFonts.Add(childNodes[i].Attributes[0].Value);
}
ctx.Dispose();