I am trying to use the awesome DocX library on codeplex to create a Word document.
when the user clicks the button, the document is created, and I want him to be able to immediately send it to the user through the answer .. I am doing something similar to this now:
Proposal Based Edited Code
using (DocX Report = DocX.Create(string.Format("Report-{0}.doc", DateTime.Now.Ticks))) { Paragraph p = Report.InsertParagraph(); p.Append("Title").FontSize(30).Bold() .Append("Sub title").FontSize(28) .AppendLine() .Append(DateTime.Now.Date) ; MemoryStream ms = new MemoryStream(); Report.SaveAs(ms); Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".docx\""); Response.ContentType = "application/msword"; Response.Write(ms); Response.End(); }
I tried several variations of this ... but I can't achieve what I want. Looking at this answer I can save the document to the server and open it using the io stream .. but I want to avoid this extra step (and then I need to also delete the file)
I see no reason to create a file in a few milliseconds. There should be a way to save the content and send it to the response stream. Correctly?
How could I do this? thanks..
EDIT: my current code either throws up, cannot open the file (Access denied) error If I use a file stream, OR loads an empty document file without any content (sometimes the type of response is written to the document)
This code gets me an MS text document with
System.IO.MemoryStream
as its contents.
Ok, here is the final working solution:
For some reason, the DocX library does not want to directly store in Response.OutputStream
, so I had to save it in the memory stream and write the memory stream in response, for example Neil and Daniel . Here is what worked for me:
MemoryStream ms = new MemoryStream() Report.SaveAs(ms); Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".doc\"); Response.ContentType = "application/msword"; ms.WriteTo(Response.OutputStream); Response.End();
Locusthorde
source share