prueba prueba
prueba prueba

Reputation: 702

C# MVC 4: Create Word Document and download without saving in disk

This probably has a very simple answer but i just can't find it.

I have a project using C# MVC 4 using Microsoft.Office.Interop.Word 12

In an action I try to dynamically create a Word file (using a database for the information) and then i want to download it. The file does not exist (it is created from scratch) and I don't want to save it in disk (it does not need to be saved because its content is dynamic).

This is the code for now:

public ActionResult Generar(Documento documento)
{
    Application word = new Application();
    word.Visible = false;

    object miss = System.Reflection.Missing.Value;
    Document doc = word.Documents.Add(ref miss, ref miss, ref miss, ref miss);

    Paragraph par = doc.Content.Paragraphs.Add(ref miss);
    object style = "Heading 1";
    par.Range.set_Style(ref style);
    par.Range.Text = "This is a dummy test";

    byte[] bytes = null;  // This is the part i need to get the bytes of the doc object
    doc.Close();

    word.Quit();

    return File(bytes, "application/octet-stream", "NewFile.docx");
}

Upvotes: 4

Views: 16478

Answers (1)

prueba prueba
prueba prueba

Reputation: 702

Using the library that Robert Harvey recommended DocX.dll (thank you, gentleman), this would be the solution:

using Novacode;
using System.Drawing;

.
.
.

public ActionResult Generar(Documento documento)
{
    MemoryStream stream = new MemoryStream();
    DocX doc = DocX.Create(stream);

    Paragraph par = doc.InsertParagraph();
    par.Append("This is a dummy test").Font(new FontFamily("Times New Roman")).FontSize(32).Color(Color.Blue).Bold();

    doc.Save();

    return File(stream.ToArray(), "application/octet-stream", "FileName.docx");
}

I couldn't find the solution using Microsoft.Office.Interop.Word (something so simple, i'm disappointed).

Thank you again to Robert and hope this example helps you solve the problem.

Upvotes: 8

Related Questions