Skip to content

Instantly share code, notes, and snippets.

@ArnisL
Created December 15, 2010 15:27
Show Gist options
  • Save ArnisL/742085 to your computer and use it in GitHub Desktop.
Save ArnisL/742085 to your computer and use it in GitHub Desktop.
word_interop.cs
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
public class WordTemplateFiller{
private readonly Zipper _zipper=new Zipper();
private const string _pathToCustomPropXml="docprops\\custom.xml";
/// <returns>path to filled docx</returns>
public FileInfo FillTemplate(string templatePath,Dictionary<string,string> props){
var docPath=Path.GetTempFileName();
using(var tempDir=new TempDirectory()){
_zipper.Unzip(templatePath,tempDir);
ModifyPropXml(Path.Combine(tempDir,_pathToCustomPropXml),props);
_zipper.ZipDir(tempDir,docPath);
}
return new FileInfo(docPath);
}
private static void ModifyPropXml(string customPropXmlPath,Dictionary<string,string> props){
var xd=XDocument.Parse(File.ReadAllText(customPropXmlPath));
foreach(var prop in props){
xd.Root.Elements()
.Where(node=>node.Attribute("name").Value==prop.Key)
.Single().Descendants().First().SetValue(prop.Value);
}
File.WriteAllText(customPropXmlPath,xd.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment