With OpenXML SDK i have created a docx file which i'm using as a template. It needs to replace the words inside the document. Well if i use a document with paragraphs it works. But for text within a tablecell and within a paragraph like a break it's not working. Below my code =>
protected void btnMail_Click(object sender, EventArgs e)
{
string templateDocumentPath = string.Format("{0}\\document.docx", Server.MapPath("~/App_Data"));
byte[] result = null;
byte[] templateBytes = System.IO.File.ReadAllBytes(templateDocumentPath);
using (MemoryStream templateStream = new MemoryStream())
{
templateStream.Write(templateBytes, 0, (int)templateBytes.Length);
using (WordprocessingDocument doc = WordprocessingDocument.Open(templateStream, true))
{
MainDocumentPart mainPart = doc.MainDocumentPart;
var body = doc.MainDocumentPart.Document.Body;
var paras = body.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>();
var breaks = body.Elements<DocumentFormat.OpenXml.Wordprocessing.Break>();
foreach (var br in breaks)
{
foreach (var run in br.Elements<Run>())
{
foreach (var text in run.Elements<Text>())
{
if (text.Text.Contains("#bNaam#"))
{
text.Text = text.Text.Replace("#bNaam#", Parameters.Naam);
run.AppendChild(new Break());
}
}
}
}
foreach (var para in paras)
{
foreach (var run in para.Elements<Run>())
{
foreach (var text in run.Elements<Text>())
{
if (text.Text.Contains("bNaam"))
{
text.Text = text.Text.Replace("bNaam", Parameters.Naam);
run.AppendChild(new Break());
}
if (text.Text.Contains("bAdres"))
{
text.Text = text.Text.Replace("bAdres", Parameters.Adres);
run.AppendChild(new Break());
}
if (text.Text.Contains("#bPostcode#") && text.Text.Contains("#bGemeente#"))
{
text.Text = text.Text.Replace("#bPostcode#", Parameters.Postcode);
text.Text = text.Text.Replace("#bGemeente#", Parameters.Plaats);
run.AppendChild(new Break());
}
if (text.Text.Contains("#docBuitenland#"))
{
text.Text = text.Text.Replace("#docBuitenland#", Parameters.Naam);
run.AppendChild(new Break());
}
}
}
}
mainPart.Document.Save();
templateStream.Position = 0;
using (MemoryStream memoryStream = new MemoryStream())
{
templateStream.CopyTo(memoryStream);
result = memoryStream.ToArray();
}
}
byte[] fileContent = templateStream.ToArray();
templateStream.Close();
// Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AddHeader("Content-Disposition", "filename=document.docx");
Response.BinaryWrite(fileContent);
Response.End();
}
}