Generate MS Word(.docx) in Asp.net MVC

Generate MS Word(.docx) in Asp.net MVC by using DocX library.
 
What is DocX?
DocX is a .NET library that allows developers to manipulate Word 2007/2010/2013 files, in an easy and intuitive manner. DocX is fast, lightweight and best of all it does not require Microsoft Word or Office to be installed.

Generated Document. 
 

Steps for generating DocX
  1. Create new MVC project in visual studio
  2. Download DocX.dll from HERE and add reference of this (.dll) to your project
  3. Add controller (GenerateDocumentController) to your project
  4. Add action method(GenerateDocument) to the controller
  5. Add view to (GenerateDocument) action method


Controller (GenerateDocumentController) Should look like this
 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Novacode;
using System.IO;

namespace MyApp.Controllers
{
    public class GenerateDocumentController : Controller
    {
        
        public ActionResult GenerateDocument()
        {
            return View();
        }
        [HttpPost]
        public void GenerateDocument(string gen)
        {
            DocX document = null;

            document = DocX.Create(Server.MapPath("~/mydoc.docx"), DocumentTypes.Document);

            Image img = document.AddImage(Server.MapPath("~/Images/mvc.png"));
           
           Picture pic= img.CreatePicture(100, 100);
           

           Paragraph picturepara = document.InsertParagraph();
           picturepara.Alignment = Alignment.center;
          // picturepara.Append("                                ");
           picturepara.AppendPicture(pic).Alignment= Alignment.center;

            var headLineFormat = new Formatting();
            headLineFormat.FontFamily = new System.Drawing.FontFamily("Arial Black");
            headLineFormat.Size = 18D;
            headLineFormat.Position = 12;

            string headlineText = "What is Lorem Ipsum?";
            document.InsertParagraph(headlineText, false, headLineFormat);

            var paraFormat = new Formatting();
            paraFormat.FontFamily = new System.Drawing.FontFamily("Calibri");
            paraFormat.Size = 11.0f;
            paraFormat.CapsStyle = CapsStyle.none;
         
          

            string p1TExt = @"Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean. A small river named Duden flows by their place and supplies it with the necessary regelialia. It is a paradisematic country.";
            document.InsertParagraph(p1TExt, false, paraFormat).Alignment= Alignment.both;
            document.InsertParagraph(" ");

            string p2Text = @"Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life One day however a small line of blind text by the name of Lorem Ipsum decided to leave for the far World of Grammar. The Big Oxmox advised her not to do so, because there were thousands of bad Commas, wild Question Marks and devious Semikoli, but the Little Blind Text didn’t listen. She packed her seven versalia, put her initial into the belt and made herself on the way. When she reached the first hills of the Italic Mountains, she had a last view back on the skyline of her hometown Bookmarksgrove, the headline of Alphabet Village and the subline of her own road, the Line Lane. Pityful a rethoric question ran over her cheek, then";
            document.InsertParagraph(p2Text, false, paraFormat).Alignment= Alignment.both;
            document.InsertParagraph(" ");

            Table tbl = document.AddTable(5, 4);
            tbl.Alignment = Alignment.center;
            tbl.Design = TableDesign.LightGridAccent2;

            tbl.Rows[0].Cells[0].Paragraphs.First().Append("Name");
            tbl.Rows[0].Cells[1].Paragraphs.First().Append("Father Name");
            tbl.Rows[0].Cells[2].Paragraphs.First().Append("Address");
            tbl.Rows[0].Cells[3].Paragraphs.First().Append("Phone");

            for (int i = 1; i <= 4; i++)
            {
                for (int j = 0; j <= 3; j++)
                {
                    tbl.Rows[i].Cells[j].Paragraphs.First().Append("(" + i + "," + j + ")");
                }
            }
            document.InsertTable(tbl);

            // For  Farsi, Arabic and Urdu.
           // document.SetDirection(Direction.RightToLeft); 

            document.Save();
          

            MemoryStream ms = new MemoryStream();
            document.SaveAs(ms);
            // document.Save(ms, SaveFormat.Docx);
            byte[] byteArray = ms.ToArray();
            ms.Flush();
            ms.Close();
            ms.Dispose();
            Response.Clear();
            Response.AddHeader("Content-Disposition", "attachment; filename=report.docx");
            Response.AddHeader("Content-Length", byteArray.Length.ToString());
            Response.ContentType = "application/msword";
            Response.BinaryWrite(byteArray);
            Response.End();
        }
    }
}
Add Empty view to GenerateDocument action method. The view should look like this.
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>GenerateDocument</title>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Styles.Render("~/content/css")
</head>
<body>
    <div class="container">
        <div class="jumbotron">
            @using (Html.BeginForm())
            {
                <div class="form-horizontal">
                    <button type="submit" class="btn btn-success btn-lg">
<i class="fa fa-list-alt"></i> Generate document</button>
                </div>
            }
        </div>
    </div>
</body>
</html>

5 Comments

  1. do i need to purchase this or its free ?

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. How can i password protect word doc using this dll? I.e i need the doc to promt the user to input password when tryin to open the file.

    ReplyDelete
  4. Try to zetword.com- this an advance word document processing API for .NET application

    ReplyDelete

Post a Comment