Created
December 15, 2010 15:27
-
-
Save ArnisL/742085 to your computer and use it in GitHub Desktop.
word_interop.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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