Anil Soman
Anil Soman

Reputation: 2467

Create and download word file from template in MVC

I have kept a word document (.docx) in one of the project folders which I want to use as a template.
This template contains custom header and footer lines for user. I want to facilitate user to download his own data in word format. For this, I want to write a function which will accept user data and referring the template it will create a new word file replacing the place-holders in the template and then return the new file for download (without saving it to server). That means the template needs to be intact as template.

Following is what I am trying. I was able to replace the placeholder. However, I am not aware of how to give the created content as downloadable file to user. I do not want to save the new content again in the server as another word file.

  public void GenerateWord(string userData)
    {
        string templateDoc = HttpContext.Current.Server.MapPath("~/App_Data/Template.docx");

        // Open the new Package
        Package pkg = Package.Open(templateDoc, FileMode.Open, FileAccess.ReadWrite);

        // Specify the URI of the part to be read
        Uri uri = new Uri("/word/document.xml", UriKind.Relative);
        PackagePart part = pkg.GetPart(uri);

        XmlDocument xmlMainXMLDoc = new XmlDocument();
        xmlMainXMLDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read));

        xmlMainXMLDoc.InnerXml = ReplacePlaceHoldersInTemplate(userData, xmlMainXMLDoc.InnerXml);

        // Open the stream to write document
        StreamWriter partWrt = new StreamWriter(part.GetStream(FileMode.Open, FileAccess.Write));
        xmlMainXMLDoc.Save(partWrt);

        partWrt.Flush();
        partWrt.Close();
        pkg.Close();
    }


    private string ReplacePlaceHoldersInTemplate(string toReplace, string templateBody)
    {
        templateBody = templateBody.Replace("#myPlaceHolder#", toReplace);
        return templateBody;
    }

I believe that the below line is saving the contents in the template file itself, which I don't want.

xmlMainXMLDoc.Save(partWrt);

How should I modify this code which can return the new content as downloadable word file to user?

Upvotes: 0

Views: 3342

Answers (1)

Anil Soman
Anil Soman

Reputation: 2467

I found the solution Here!

This code allows me to read the template file and modify it as I want and then to send response as downloadable attachment.

Upvotes: 0

Related Questions