herve
Forum Replies Created
-
AuthorPosts
-
Hello Eric,
My project was just accepted so I’m starting to work on it but I’m completly lost and stuck on the code… A book will be really usefull.
I have a template document (modele.docx) with some content and let say, 3 special texts inside, like this :
{document1}
{document2}
{document3}They represent the name of the file I have to insert content from (document1.docx, documen2.docx and document3.docx)
With the help of the video you suggested me (http://www.ericwhite.com/blog/advanced-use-of-documentbuilder), Im trying to :
1) Open the model
2) Search for everything that starts with { and ends with }
3) Replace it with an Id on the form “document1”, “document2” and “document3”
4) From a list of sources (document1.docx etc) create and generate a new documentHere is the code :
WmlDocument doc1 = new WmlDocument(@"C:\Winston\models\modele.docx"); using (MemoryStream mem = new MemoryStream()) { mem.Write(doc1.DocumentByteArray, 0, doc1.DocumentByteArray.Length); using (WordprocessingDocument doc = WordprocessingDocument.Open(mem, true)) { XDocument xDoc = doc.MainDocumentPart.GetXDocument(); foreach (XElement element in xDoc.Root.Element(W.body).Elements(W.p)) { if (element == null) continue; if(element.Name == W.p) { string content = element.Value; if (content == null || content.Trim().Equals("")) continue; content = content.Trim(); if(content.StartsWith("{") && content.EndsWith("}")) { string idName = content.Replace("{", string.Empty).Replace("}", string.Empty); MessageBox.Show(idName); element.ReplaceWith(new XElement(PtOpenXml.Insert, new XAttribute("Id", idName))); } } } doc.MainDocumentPart.PutXDocument(); } doc1.DocumentByteArray = mem.ToArray(); } string outFileName = @"C:\Winston\output\output.docx"; List<Source> sources = new List<Source>() { new Source(doc1, true), new Source(new WmlDocument(@"C:\Winston\data\document1.docx"), "document1"), new Source(new WmlDocument(@"C:\Winston\data\document2.docx"), "document2"), new Source(new WmlDocument(@"C:\Winston\data\document3.docx"), "document3"), }; DocumentBuilder.BuildDocument(sources, outFileName);
When I comment this line :
element.ReplaceWith(new XElement(PtOpenXml.Insert, new XAttribute("Id", idName)));
The code finds the 3 searched patterns but when I uncomment it, it only see the patterns one time…??
Do you have an idea of what I am doing wrong?Thank you by advance.
Bye,
HervéHello Eric,
Thank you very much for your help, I will have a look to the videos.
Concerning the book, I will be very interested.Thanks again.
Bye
-
AuthorPosts