Been strugling with a lot of problems. Using OpenXML on a ASP.NET Core server, I want to create a new docx document based on a template one. Once this document is fully saved, I want it to be sent to my client so he can download it directly. Here's my code :
public IActionResult Post([FromBody] Consultant consultant)
{
using (Stream templateStream = new MemoryStream(Properties.Resources.templateDossierTech))
using (WordprocessingDocument template =
WordprocessingDocument.Open(templateStream, false))
{
string fileName = environment.WebRootPath + @"\Resources\"+ consultant.FirstName + "_" + consultant.LastName + ".docx";
WordprocessingDocument dossierTechniqueDocument =
WordprocessingDocument.Create(fileName,
WordprocessingDocumentType.Document);
foreach (var part in template.Parts)
{
dossierTechniqueDocument.AddPart(part.OpenXmlPart, part.RelationshipId);
}
var body = dossierTechniqueDocument.MainDocumentPart.Document.Body;
var paras = body.Elements();
foreach (var para in paras)
{
foreach (var run in para.Elements())
{
foreach (var text in run.Elements())
{
if (text.InnerText.Contains("{{prenom}}"))
{
var t = new Text(text.InnerText.Replace("{{prenom}}", consultant.FirstName));
run.RemoveAllChildren<Text>();
run.AppendChild(t);
}
}
}
}
dossierTechniqueDocument.MainDocumentPart.Document.Save();
dossierTechniqueDocument.Close();
var cd = new System.Net.Mime.ContentDisposition
{
FileName = consultant.FirstName + "_" + consultant.LastName + ".docx",
Inline = true
};
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.Headers.Add("X-Content-Type-Options", "nosniff");
return File(System.IO.File.ReadAllBytes(fileName),"application/vnd.openxmlformats-officedocument.wordprocessingml.document","Dossier Technique");
}
}
As a first look, it looks like is saving well but when I try to open it on word, it says that it is corrupted for some reason. That's the same problem when I try to send it. Once it's sent my client doesn't download it (Ajax query). Do anyone of you have any idea how to fix it ?