Generating MS Word (RTL+LTR) (arabic, Farsi, Pashto etc) in MVC

Generating MS Word for (Right to left and Left to Right languages) i-e (pashto, farsi, urdu, arabic etc + enghlish) in MVC
Such a Document can be generated by DocX an open source Library. 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.
At the end of this article we will be able to generate the following document.
 

Steps for creating Document
  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
 
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 FileResult  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.Bold = true;
            headLineFormat.Size = 18.0;

            string headlineText = "أين أجده ؟";
            Paragraph heading1= document.InsertParagraph(headlineText, false, headLineFormat);
            heading1.Direction = Direction.RightToLeft;

            var paraFormat = new Formatting();
            paraFormat.FontFamily = new System.Drawing.FontFamily("Segoe WP");
            paraFormat.Size = 12.0f;
            paraFormat.CapsStyle = CapsStyle.none;

            string p1TExt = @".  إيبسوم نفسه عدة مرات بما تتطلبه الحاجة، يقوم مولّدنا هذا باستخدام كلمات من قاموس يحوي على أكثر من 200 كلمة لا تينية، مضاف إليها مجموعة من الجمل النموذجية، لتكوين نص لوريم إيبسوم ذو شكل منطقي قريب إلى النص الحقيقي. وبالتالي يكون النص الناتح خالي من التكرار، أو أي كلمات أو عبارات غير لائقة أو ما شابه. وهذا ما يجعله أول مولّد نص لوريم إيبسوم حقيقي على الإنترنت.";
            Paragraph p3 = document.InsertParagraph(p1TExt, false, paraFormat);
            p3.Alignment = Alignment.both;
            p3.Direction = Direction.RightToLeft;
          
            document.InsertParagraph(" ");
            string EnglishHeadingText = "English";
            Paragraph Eng = document.InsertParagraph(EnglishHeadingText, false, headLineFormat);
            Eng.Direction = Direction.LeftToRight;

            string engP = @"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. ";
            Paragraph engpara = document.InsertParagraph(engP, false);
            engpara.Alignment = Alignment.both;
            engpara.Direction = Direction.LeftToRight;
            document.InsertParagraph(" ");

            string pashtoHeadingText = "پښتو";
            Paragraph pashtoHeading = document.InsertParagraph(pashtoHeadingText, false, headLineFormat);
            pashtoHeading.Direction = Direction.RightToLeft;

            Formatting pashtoFormatting = new Formatting();
            pashtoFormatting.FontFamily = new System.Drawing.FontFamily("Times New Roman");
            pashtoFormatting.Size = 12.0f;
            pashtoFormatting.CapsStyle = CapsStyle.none;

            string paText = @"سوری، سوړه، غار، سوغالی پرهار؛ کورګی؛ ټپی بايسکل چلونکی؛ ماشين ضربان زړه خوځوونکی ماشي څرځای، ايساره ځمکه,ګردنۍ، قطاروزمه رضايت، خوښه، قناعت ورکونه بنډل، ګيډۍ، ښوونځی";
            Paragraph PaPara = document.InsertParagraph(paText, false,pashtoFormatting);
            PaPara.Alignment = Alignment.both;
            PaPara.Direction = Direction.RightToLeft;
            document.InsertParagraph(" ");
            //Page break when required
           // document.InsertSectionPageBreak();

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

            tbl.Rows[0].Cells[0].Paragraphs.First().Append("نوم");
            tbl.Rows[0].Cells[1].Paragraphs.First().Append("دپلارنوم");
            tbl.Rows[0].Cells[2].Paragraphs.First().Append("آدرس");
            tbl.Rows[0].Cells[3].Paragraphs.First().Append("ټیلیفون شماره");

            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);        
            return File(ms.ToArray(), "application/msword", "report.docx");
        }
    }
}

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/jqueryLTR")
    @Scripts.Render("~/bundles/bootstrapLTR")
    @Styles.Render("~/content/cssLTR")
</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>

Post a Comment