Christian Caspovich
Christian Caspovich

Reputation: 169

Downloading Spire.doc document from controller to view

I am using Spire.doc for creating a Word file, and I followed their example like this

public class WordController : Controller
{
    public void Download()
    {
        Document doc = new Document();

        Paragraph test = doc.AddSection().AddParagraph();

        test.AppendText("This is a test");

        doc.SaveToFile("Doc.doc");

        try
        {
            System.Diagnostics.Process.Start("Doc.doc");
        }catch(Exception)
        {

        }
    }
}

This opens the Word file in Microsoft Word, but how can I make it so that it's downloaded instead?

I've used return File() to return a PDF document to the View before, but it doesn't work with this.

Upvotes: 2

Views: 3641

Answers (2)

dani74
dani74

Reputation: 1

Load file .docx to richtextbox.rtf ( using Spire.Doc ):

       byte[] toArray = null;

       //Paragraph test = doc.AddSection().AddParagraph();
       //test.AppendText("This is a test") --> this also works ;

        Document doc = new Document();
        doc.LoadFromFile("C://Users//Mini//Desktop//doc.docx");

       // or - Document doc = new Document("C://Users//Mini//Desktop//doc.docx");

        using (MemoryStream ms1 = new MemoryStream())
        {
            doc.SaveToStream(ms1, FileFormat.Rtf);
            toArray = ms1.ToArray();
            richTextBox1.Rtf = System.Text.Encoding.UTF8.GetString(toArray);
              
        }

Upvotes: 0

Manik Arora
Manik Arora

Reputation: 4792

Could you please try the below code and let me know if it worked or not, cos I didn't executed this code but believe this should work, I modified my existing working code according to your requirement-

        public class WordController : Controller
        {
            public void Download()
            {
                byte[] toArray = null;
                Document doc = new Document();
                Paragraph test = doc.AddSection().AddParagraph();
                test.AppendText("This is a test");
                using (MemoryStream ms1 = new MemoryStream())
                {
                    doc.SaveToStream(ms1, FileFormat.Doc);
                    //save to byte array
                    toArray = ms1.ToArray();
                }
                //Write it back to the client
                Response.ContentType = "application/msword";
                Response.AddHeader("content-disposition", "attachment;  filename=Doc.doc");
                Response.BinaryWrite(toArray);
                Response.Flush();
                Response.End();
            }
        }

Upvotes: 4

Related Questions