Whenever I try to save to a stream and download it the file I get back is blank (see code snippet). But when I replace myDocument.Save(stream, SaveOptions.DocxDefault);
to saving the file to my c drive, myDocument.Save(pathToSave);
the document is saved with the correct content included. Is there something I am missing when saving to a stream?
[HttpGet]
public ActionResult Download(string fileGuid, string fileName)
{
var path = _hostEnvironment.ContentRootPath;
DocumentModel myDocument = DocumentModel.Load(path + "\\Form_template.docx");
var mySection = myDocument.Sections[0];
mySection .HeadersFooters.Add(
new HeaderFooter(myDocument, HeaderFooterType.HeaderDefault,
new Paragraph(myDocument, "Hell 0 World")));
// Insert content from HTML editor.
var bookmark = myDocument.Bookmarks["HtmlBookmark"];
bookmark.GetContent(true).LoadText("<p>Hello world</p>", LoadOptions.HtmlDefault);
var stream = new MemoryStream();
myDocument.Save(stream, SaveOptions.DocxDefault);
return File(stream.ToArray(), SaveOptions.DocxDefault.ContentType, fileName);
}
Hi Jack,
That part is fine, I believe your problem lies somewhere else.
Is it possible that you’re calling this API from AJAX call?
Can you show me how the file is being downloaded on the client side?
Regards,
Mario
NP. Here is the Ajax call.
$.ajax({
type: "POST",
url: "/ExportToWord",
data: { myData },
success: function (response) {
downloadUrl = '/Download?fileGuid=' + response.fileGuid
+ '&filename=' + response.fileName;
var a = document.createElement("a");
//safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location.href = downloadUrl;
} else {
a.href = downloadUrl;
a.download = response.fileName;
document.body.appendChild(a);
a.click();
}
}
});
Hi,
That should work, the first request is an AJAX call to retrieve the downloadUrl
value, and then the second request is a regular (postback) call to that URL.
I’m afraid I’ll need to investigate your project in order to find out what your problem is.
Can you please create a small Visual Studio project that reproduces this issue so that we can investigate it?
Regards,
Mario
Thanks for your help, I figured it out. I had a bad check that was always returning false so it did not added the html to the doc.