Export Word in ASP.NET

GemBox.Document does not use Office Automation, nor any other library - only .NET Framework, which, combined with it superior performance, makes it ideal for web applications, like ASP.NET. GemBox.Document supports reading and writing a document from / to a stream, so the document can easily be uploaded or streamed to a browser.

Following sample demonstrates how to mail merge web form into a template document and export the resulting document to a browser in ASP.NET application.

Screenshot

Medium Trust Screenshot

See the full code below.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MediumTrustSampleCs._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 103px;
        }
        .style2
        {
            width: 103px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>Invoice:</h2>
        
        <table>
            <tr>
                <td class="style1">Number:</td>
                <td>
                    <asp:Label ID="LblInvoiceNumber" runat="server" />
                </td>
            </tr>
            <tr>
                <td class="style1">Date:</td>
                <td>
                    <asp:TextBox ID="TbxInvoiceDate" runat="server" ></asp:TextBox>
                </td>
            </tr>
        </table>
        <br />
        <table>
            <tr>
                <td class="style2">Name:</td>
                <td>
                    <asp:TextBox ID="TbxCustomerName" runat="server">ACME Corp</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">Address:</td>
                <td>
                    <asp:TextBox ID="TbxCustomerAddress" runat="server">240 Old Country Road, Springfield, IL</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">Country:</td>
                <td>
                    <asp:DropDownList ID="DdlCustomerCountry" runat="server" Width="142px">
                        <asp:ListItem>AFGHANISTAN</asp:ListItem>
                        <asp:ListItem>ÅLAND ISLANDS</asp:ListItem>
                        <asp:ListItem>ALBANIA</asp:ListItem>
                        <asp:ListItem>ALGERIA</asp:ListItem>
                        <asp:ListItem>AMERICAN SAMOA</asp:ListItem>
                        <asp:ListItem>ANDORRA</asp:ListItem>
                        <asp:ListItem>ANGOLA</asp:ListItem>
                        <asp:ListItem>ANGUILLA</asp:ListItem>
                        <asp:ListItem>ANTARCTICA</asp:ListItem>
                        <asp:ListItem>ANTIGUA AND BARBUDA</asp:ListItem>
                        <asp:ListItem>ARGENTINA</asp:ListItem>
                        <asp:ListItem>ARMENIA</asp:ListItem>
                        <asp:ListItem>ARUBA</asp:ListItem>
                        <asp:ListItem>AUSTRALIA</asp:ListItem>
                        <asp:ListItem>AUSTRIA</asp:ListItem>
                        <asp:ListItem>AZERBAIJAN</asp:ListItem>
                        <asp:ListItem>BAHAMAS</asp:ListItem>
                        <asp:ListItem>BAHRAIN</asp:ListItem>
                        <asp:ListItem>BANGLADESH</asp:ListItem>
                        <asp:ListItem>BARBADOS</asp:ListItem>
                        <asp:ListItem>BELARUS</asp:ListItem>
                        <asp:ListItem>BELGIUM</asp:ListItem>
                        <asp:ListItem>BELIZE</asp:ListItem>
                        <asp:ListItem>BENIN</asp:ListItem>
                        <asp:ListItem>BERMUDA</asp:ListItem>
                        <asp:ListItem>BHUTAN</asp:ListItem>
                        <asp:ListItem>BOLIVIA, PLURINATIONAL STATE OF</asp:ListItem>
                        <asp:ListItem>BONAIRE, SINT EUSTATIUS AND SABA</asp:ListItem>
                        <asp:ListItem>BOSNIA AND HERZEGOVINA</asp:ListItem>
                        <asp:ListItem>BOTSWANA</asp:ListItem>
                        <asp:ListItem>BOUVET ISLAND</asp:ListItem>
                        <asp:ListItem>BRAZIL</asp:ListItem>
                        <asp:ListItem>BRITISH INDIAN OCEAN TERRITORY</asp:ListItem>
                        <asp:ListItem>BRUNEI DARUSSALAM</asp:ListItem>
                        <asp:ListItem>BULGARIA</asp:ListItem>
                        <asp:ListItem>BURKINA FASO</asp:ListItem>
                        <asp:ListItem>BURUNDI</asp:ListItem>
                        <asp:ListItem>CAMBODIA</asp:ListItem>
                        <asp:ListItem>CAMEROON</asp:ListItem>
                        <asp:ListItem>CANADA</asp:ListItem>
                        <asp:ListItem>CAPE VERDE</asp:ListItem>
                        <asp:ListItem>CAYMAN ISLANDS</asp:ListItem>
                        <asp:ListItem>CENTRAL AFRICAN REPUBLIC</asp:ListItem>
                        <asp:ListItem>CHAD</asp:ListItem>
                        <asp:ListItem>CHILE</asp:ListItem>
                        <asp:ListItem>CHINA</asp:ListItem>
                        <asp:ListItem>CHRISTMAS ISLAND</asp:ListItem>
                        <asp:ListItem>COCOS (KEELING) ISLANDS</asp:ListItem>
                        <asp:ListItem>COLOMBIA</asp:ListItem>
                        <asp:ListItem>COMOROS</asp:ListItem>
                        <asp:ListItem>CONGO</asp:ListItem>
                        <asp:ListItem>CONGO, THE DEMOCRATIC REPUBLIC OF THE</asp:ListItem>
                        <asp:ListItem>COOK ISLANDS</asp:ListItem>
                        <asp:ListItem>COSTA RICA</asp:ListItem>
                        <asp:ListItem>CÔTE D'IVOIRE</asp:ListItem>
                        <asp:ListItem>CROATIA</asp:ListItem>
                        <asp:ListItem>CUBA</asp:ListItem>
                        <asp:ListItem>CURAÇAO</asp:ListItem>
                        <asp:ListItem>CYPRUS</asp:ListItem>
                        <asp:ListItem>CZECH REPUBLIC</asp:ListItem>
                        <asp:ListItem>DENMARK</asp:ListItem>
                        <asp:ListItem>DJIBOUTI</asp:ListItem>
                        <asp:ListItem>DOMINICA</asp:ListItem>
                        <asp:ListItem>DOMINICAN REPUBLIC</asp:ListItem>
                        <asp:ListItem>ECUADOR</asp:ListItem>
                        <asp:ListItem>EGYPT</asp:ListItem>
                        <asp:ListItem>EL SALVADOR</asp:ListItem>
                        <asp:ListItem>EQUATORIAL GUINEA</asp:ListItem>
                        <asp:ListItem>ERITREA</asp:ListItem>
                        <asp:ListItem>ESTONIA</asp:ListItem>
                        <asp:ListItem>ETHIOPIA</asp:ListItem>
                        <asp:ListItem>FALKLAND ISLANDS (MALVINAS)</asp:ListItem>
                        <asp:ListItem>FAROE ISLANDS</asp:ListItem>
                        <asp:ListItem>FIJI</asp:ListItem>
                        <asp:ListItem>FINLAND</asp:ListItem>
                        <asp:ListItem>FRANCE</asp:ListItem>
                        <asp:ListItem>FRENCH GUIANA</asp:ListItem>
                        <asp:ListItem>FRENCH POLYNESIA</asp:ListItem>
                        <asp:ListItem>FRENCH SOUTHERN TERRITORIES</asp:ListItem>
                        <asp:ListItem>GABON</asp:ListItem>
                        <asp:ListItem>GAMBIA</asp:ListItem>
                        <asp:ListItem>GEORGIA</asp:ListItem>
                        <asp:ListItem>GERMANY</asp:ListItem>
                        <asp:ListItem>GHANA</asp:ListItem>
                        <asp:ListItem>GIBRALTAR</asp:ListItem>
                        <asp:ListItem>GREECE</asp:ListItem>
                        <asp:ListItem>GREENLAND</asp:ListItem>
                        <asp:ListItem>GRENADA</asp:ListItem>
                        <asp:ListItem>GUADELOUPE</asp:ListItem>
                        <asp:ListItem>GUAM</asp:ListItem>
                        <asp:ListItem>GUATEMALA</asp:ListItem>
                        <asp:ListItem>GUERNSEY</asp:ListItem>
                        <asp:ListItem>GUINEA</asp:ListItem>
                        <asp:ListItem>GUINEA-BISSAU</asp:ListItem>
                        <asp:ListItem>GUYANA</asp:ListItem>
                        <asp:ListItem>HAITI</asp:ListItem>
                        <asp:ListItem>HEARD ISLAND AND MCDONALD ISLANDS</asp:ListItem>
                        <asp:ListItem>HOLY SEE (VATICAN CITY STATE)</asp:ListItem>
                        <asp:ListItem>HONDURAS</asp:ListItem>
                        <asp:ListItem>HONG KONG</asp:ListItem>
                        <asp:ListItem>HUNGARY</asp:ListItem>
                        <asp:ListItem>ICELAND</asp:ListItem>
                        <asp:ListItem>INDIA</asp:ListItem>
                        <asp:ListItem>INDONESIA</asp:ListItem>
                        <asp:ListItem>IRAN, ISLAMIC REPUBLIC OF</asp:ListItem>
                        <asp:ListItem>IRAQ</asp:ListItem>
                        <asp:ListItem>IRELAND</asp:ListItem>
                        <asp:ListItem>ISLE OF MAN</asp:ListItem>
                        <asp:ListItem>ISRAEL</asp:ListItem>
                        <asp:ListItem>ITALY</asp:ListItem>
                        <asp:ListItem>JAMAICA</asp:ListItem>
                        <asp:ListItem>JAPAN</asp:ListItem>
                        <asp:ListItem>JERSEY</asp:ListItem>
                        <asp:ListItem>JORDAN</asp:ListItem>
                        <asp:ListItem>KAZAKHSTAN</asp:ListItem>
                        <asp:ListItem>KENYA</asp:ListItem>
                        <asp:ListItem>KIRIBATI</asp:ListItem>
                        <asp:ListItem>KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF</asp:ListItem>
                        <asp:ListItem>KOREA, REPUBLIC OF</asp:ListItem>
                        <asp:ListItem>KUWAIT</asp:ListItem>
                        <asp:ListItem>KYRGYZSTAN</asp:ListItem>
                        <asp:ListItem>LAO PEOPLE'S DEMOCRATIC REPUBLIC</asp:ListItem>
                        <asp:ListItem>LATVIA</asp:ListItem>
                        <asp:ListItem>LEBANON</asp:ListItem>
                        <asp:ListItem>LESOTHO</asp:ListItem>
                        <asp:ListItem>LIBERIA</asp:ListItem>
                        <asp:ListItem>LIBYA</asp:ListItem>
                        <asp:ListItem>LIECHTENSTEIN</asp:ListItem>
                        <asp:ListItem>LITHUANIA</asp:ListItem>
                        <asp:ListItem>LUXEMBOURG</asp:ListItem>
                        <asp:ListItem>MACAO</asp:ListItem>
                        <asp:ListItem>MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF</asp:ListItem>
                        <asp:ListItem>MADAGASCAR</asp:ListItem>
                        <asp:ListItem>MALAWI</asp:ListItem>
                        <asp:ListItem>MALAYSIA</asp:ListItem>
                        <asp:ListItem>MALDIVES</asp:ListItem>
                        <asp:ListItem>MALI</asp:ListItem>
                        <asp:ListItem>MALTA</asp:ListItem>
                        <asp:ListItem>MARSHALL ISLANDS</asp:ListItem>
                        <asp:ListItem>MARTINIQUE</asp:ListItem>
                        <asp:ListItem>MAURITANIA</asp:ListItem>
                        <asp:ListItem>MAURITIUS</asp:ListItem>
                        <asp:ListItem>MAYOTTE</asp:ListItem>
                        <asp:ListItem>MEXICO</asp:ListItem>
                        <asp:ListItem>MICRONESIA, FEDERATED STATES OF</asp:ListItem>
                        <asp:ListItem>MOLDOVA, REPUBLIC OF</asp:ListItem>
                        <asp:ListItem>MONACO</asp:ListItem>
                        <asp:ListItem>MONGOLIA</asp:ListItem>
                        <asp:ListItem>MONTENEGRO</asp:ListItem>
                        <asp:ListItem>MONTSERRAT</asp:ListItem>
                        <asp:ListItem>MOROCCO</asp:ListItem>
                        <asp:ListItem>MOZAMBIQUE</asp:ListItem>
                        <asp:ListItem>MYANMAR</asp:ListItem>
                        <asp:ListItem>NAMIBIA</asp:ListItem>
                        <asp:ListItem>NAURU</asp:ListItem>
                        <asp:ListItem>NEPAL</asp:ListItem>
                        <asp:ListItem>NETHERLANDS</asp:ListItem>
                        <asp:ListItem>NEW CALEDONIA</asp:ListItem>
                        <asp:ListItem>NEW ZEALAND</asp:ListItem>
                        <asp:ListItem>NICARAGUA</asp:ListItem>
                        <asp:ListItem>NIGER</asp:ListItem>
                        <asp:ListItem>NIGERIA</asp:ListItem>
                        <asp:ListItem>NIUE</asp:ListItem>
                        <asp:ListItem>NORFOLK ISLAND</asp:ListItem>
                        <asp:ListItem>NORTHERN MARIANA ISLANDS</asp:ListItem>
                        <asp:ListItem>NORWAY</asp:ListItem>
                        <asp:ListItem>OMAN</asp:ListItem>
                        <asp:ListItem>PAKISTAN</asp:ListItem>
                        <asp:ListItem>PALAU</asp:ListItem>
                        <asp:ListItem>PALESTINIAN TERRITORY, OCCUPIED</asp:ListItem>
                        <asp:ListItem>PANAMA</asp:ListItem>
                        <asp:ListItem>PAPUA NEW GUINEA</asp:ListItem>
                        <asp:ListItem>PARAGUAY</asp:ListItem>
                        <asp:ListItem>PERU</asp:ListItem>
                        <asp:ListItem>PHILIPPINES</asp:ListItem>
                        <asp:ListItem>PITCAIRN</asp:ListItem>
                        <asp:ListItem>POLAND</asp:ListItem>
                        <asp:ListItem>PORTUGAL</asp:ListItem>
                        <asp:ListItem>PUERTO RICO</asp:ListItem>
                        <asp:ListItem>QATAR</asp:ListItem>
                        <asp:ListItem>RÉUNION</asp:ListItem>
                        <asp:ListItem>ROMANIA</asp:ListItem>
                        <asp:ListItem>RUSSIAN FEDERATION</asp:ListItem>
                        <asp:ListItem>RWANDA</asp:ListItem>
                        <asp:ListItem>SAINT BARTHÉLEMY</asp:ListItem>
                        <asp:ListItem>SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA</asp:ListItem>
                        <asp:ListItem>SAINT KITTS AND NEVIS</asp:ListItem>
                        <asp:ListItem>SAINT LUCIA</asp:ListItem>
                        <asp:ListItem>SAINT MARTIN (FRENCH PART)</asp:ListItem>
                        <asp:ListItem>SAINT PIERRE AND MIQUELON</asp:ListItem>
                        <asp:ListItem>SAINT VINCENT AND THE GRENADINES</asp:ListItem>
                        <asp:ListItem>SAMOA</asp:ListItem>
                        <asp:ListItem>SAN MARINO</asp:ListItem>
                        <asp:ListItem>SAO TOME AND PRINCIPE</asp:ListItem>
                        <asp:ListItem>SAUDI ARABIA</asp:ListItem>
                        <asp:ListItem>SENEGAL</asp:ListItem>
                        <asp:ListItem>SERBIA</asp:ListItem>
                        <asp:ListItem>SEYCHELLES</asp:ListItem>
                        <asp:ListItem>SIERRA LEONE</asp:ListItem>
                        <asp:ListItem>SINGAPORE</asp:ListItem>
                        <asp:ListItem>SINT MAARTEN (DUTCH PART)</asp:ListItem>
                        <asp:ListItem>SLOVAKIA</asp:ListItem>
                        <asp:ListItem>SLOVENIA</asp:ListItem>
                        <asp:ListItem>SOLOMON ISLANDS</asp:ListItem>
                        <asp:ListItem>SOMALIA</asp:ListItem>
                        <asp:ListItem>SOUTH AFRICA</asp:ListItem>
                        <asp:ListItem>SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS</asp:ListItem>
                        <asp:ListItem>SOUTH SUDAN</asp:ListItem>
                        <asp:ListItem>SPAIN</asp:ListItem>
                        <asp:ListItem>SRI LANKA</asp:ListItem>
                        <asp:ListItem>SUDAN</asp:ListItem>
                        <asp:ListItem>SURINAME</asp:ListItem>
                        <asp:ListItem>SVALBARD AND JAN MAYEN</asp:ListItem>
                        <asp:ListItem>SWAZILAND</asp:ListItem>
                        <asp:ListItem>SWEDEN</asp:ListItem>
                        <asp:ListItem>SWITZERLAND</asp:ListItem>
                        <asp:ListItem>SYRIAN ARAB REPUBLIC</asp:ListItem>
                        <asp:ListItem>TAIWAN, PROVINCE OF CHINA</asp:ListItem>
                        <asp:ListItem>TAJIKISTAN</asp:ListItem>
                        <asp:ListItem>TANZANIA, UNITED REPUBLIC OF</asp:ListItem>
                        <asp:ListItem>THAILAND</asp:ListItem>
                        <asp:ListItem>TIMOR-LESTE</asp:ListItem>
                        <asp:ListItem>TOGO</asp:ListItem>
                        <asp:ListItem>TOKELAU</asp:ListItem>
                        <asp:ListItem>TONGA</asp:ListItem>
                        <asp:ListItem>TRINIDAD AND TOBAGO</asp:ListItem>
                        <asp:ListItem>TUNISIA</asp:ListItem>
                        <asp:ListItem>TURKEY</asp:ListItem>
                        <asp:ListItem>TURKMENISTAN</asp:ListItem>
                        <asp:ListItem>TURKS AND CAICOS ISLANDS</asp:ListItem>
                        <asp:ListItem>TUVALU</asp:ListItem>
                        <asp:ListItem>UGANDA</asp:ListItem>
                        <asp:ListItem>UKRAINE</asp:ListItem>
                        <asp:ListItem>UNITED ARAB EMIRATES</asp:ListItem>
                        <asp:ListItem>UNITED KINGDOM</asp:ListItem>
                        <asp:ListItem Selected="True">UNITED STATES</asp:ListItem>
                        <asp:ListItem>UNITED STATES MINOR OUTLYING ISLANDS</asp:ListItem>
                        <asp:ListItem>URUGUAY</asp:ListItem>
                        <asp:ListItem>UZBEKISTAN</asp:ListItem>
                        <asp:ListItem>VANUATU</asp:ListItem>
                        <asp:ListItem>VENEZUELA, BOLIVARIAN REPUBLIC OF</asp:ListItem>
                        <asp:ListItem>VIET NAM</asp:ListItem>
                        <asp:ListItem>VIRGIN ISLANDS, BRITISH</asp:ListItem>
                        <asp:ListItem>VIRGIN ISLANDS, U.S.</asp:ListItem>
                        <asp:ListItem>WALLIS AND FUTUNA</asp:ListItem>
                        <asp:ListItem>WESTERN SAHARA</asp:ListItem>
                        <asp:ListItem>YEMEN</asp:ListItem>
                        <asp:ListItem>ZAMBIA</asp:ListItem>
                        <asp:ListItem>ZIMBABWE</asp:ListItem>                       
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td class="style2">Contact person:</td>
                <td>
                    <asp:TextBox ID="TbxContactPerson" runat="server">Joe Smith</asp:TextBox>
                </td>
            </tr>
        </table>
        <br />
        <table>
        <tr>
            <td colspan="2">
                <asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" 
                    BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" 
                    OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="false" >
                    <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
                    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
                    <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
                    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#D54A06" Font-Bold="True" ForeColor="White"/>
                    <Columns>
                        <asp:BoundField DataField="Date" HeaderText="Date"  DataFormatString="{0:D}" />
                        <asp:BoundField DataField="Hours" HeaderText="Work hours" DataFormatString="{0:D}" ItemStyle-HorizontalAlign="Right"/>
                        <asp:BoundField DataField="Price" HeaderText="Unit price (USD/hour)" DataFormatString="{0:C}" ItemStyle-HorizontalAlign="Right"/>
                        <asp:BoundField DataField="Total" HeaderText="Total" ReadOnly="true" DataFormatString="{0:C}" HeaderStyle-Width="100px" ItemStyle-HorizontalAlign="Right"/>
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
        <tr>
        <td><asp:Button ID="BtnAddItem" runat="server" Text="Add row" onclick="BtnAddItem_Click" /></td>
        <td align="right">
            <asp:Label ID="LblTotal" runat="server"></asp:Label></td>
        </tr>        
        </table>
        <br />
        Notes: <br />
        <asp:TextBox ID="TbxNotes" runat="server" TextMode="MultiLine" Width="517px">Payment via check.</asp:TextBox>        
    </div>
    <br />
    <asp:RadioButtonList ID="RdbOutputFormat" runat="server">
        <asp:ListItem Value="pdf" Selected="True">PDF</asp:ListItem>
        <asp:ListItem Value="docx">DOCX</asp:ListItem>
        <asp:ListItem Value="html">HTML</asp:ListItem>
        <asp:ListItem Value="mht">MHTML</asp:ListItem>
		<asp:ListItem Value="rtf">RTF</asp:ListItem>
    </asp:RadioButtonList>
    <br />
    <asp:Button ID="BtnGenerate" runat="server" onclick="BtnGenerate_Click" Text="Generate Invoice"  />
    </form>
</body>

</html>
1using System;
2using System.Collections.Generic;
3using System.Data;
4using System.IO;
5using System.Linq;
6using System.Web.UI;
7using System.Web.UI.WebControls;
8using GemBox.Document;
9 
10namespace MediumTrustWebDemo
11{
12    public partial class _Default : System.Web.UI.Page
13    {
14        private static int invoiceNumber = 0;
15 
16        protected void Page_Load(object sender, EventArgs e)
17        {
18            // Set license key.
19            ComponentInfo.SetLicense("FREE-LIMITED-KEY");
20 
21            // By specifying a location that is under ASP.NET application's control, 
22            // GemBox.Document can use file system operations to retrieve font data even in Medium Trust environment.
23            FontSettings.FontsBaseDirectory = Server.MapPath("Fonts/");
24 
25            if (!Page.IsPostBack)
26            {
27                // Set default values.
28                this.LblInvoiceNumber.Text = (++invoiceNumber).ToString();
29                this.TbxInvoiceDate.Text = DateTime.Now.ToShortDateString();
30 
31                // Fill grid with some dummy data.
32                DataTable dt = new DataTable();
33                dt.Columns.Add("Date", typeof(DateTime));
34                dt.Columns.Add("Hours", typeof(int));
35                dt.Columns.Add("Price", typeof(double));
36                dt.Columns.Add("Total", typeof(double));
37 
38                dt.Rows.Add(DateTime.Now.AddDays(-2), 7, 35);
39                dt.Rows.Add(DateTime.Now.AddDays(-1), 8, 35);
40 
41                Session["DataTable"] = dt;
42 
43                this.SetDataBinding();
44            }
45        }
46 
47        // On button click generate the document and stream it to the browser.
48        protected void BtnGenerate_Click(object sender, EventArgs e)
49        {
50            DocumentModel document = GenerateDocument();
51 
52            string fileName = "Report." + this.RdbOutputFormat.SelectedValue;
53 
54            document.Save(this.Response, fileName);
55        }
56 
57        private DocumentModel GenerateDocument()
58        {
59            DateTime invoiceDate;
60            if (!DateTime.TryParse(this.TbxInvoiceDate.Text, out invoiceDate))
61                this.TbxInvoiceDate.Text = (invoiceDate = DateTime.Now).ToShortDateString();
62 
63            return Process((DataTable)Session["DataTable"], int.Parse(this.LblInvoiceNumber.Text),
64                        invoiceDate, this.TbxCustomerName.Text, this.TbxCustomerAddress.Text, this.DdlCustomerCountry.SelectedValue, this.TbxContactPerson.Text, this.TbxNotes.Text);
65        }
66 
67        // Modify document with the data from web form using Mail Merge.
68        // This method also shows how to modify document from different data sources.
69        public DocumentModel Process(
70            DataTable dt, int invoiceNumber, DateTime invoiceDate, string customerName, string companyAddress, string country, string contantactPerson, string notes)
71        {
72            string path = Path.Combine(Request.PhysicalApplicationPath, "Invoice.docx");
73 
74            // Load template document.
75            DocumentModel document = DocumentModel.Load(path);
76 
77            // Subscribe to FieldMerging event (we want to format the output).
78            document.MailMerge.FieldMerging += (sender, e) =>
79            {
80                if (e.IsValueFound)
81                    switch (e.FieldName)
82                    {
83                        case "Date":
84                            ((Run)e.Inline).Text = ((DateTime)e.Value).ToString("dddd, MMMM d, yyyy");
85                            break;
86                        case "Price":
87                        case "Total":
88                        case "TotalPrice":
89                            ((Run)e.Inline).Text = ((double)e.Value).ToString("C");
90                            break;
91                    }
92            };
93 
94            // Fill table.
95            document.MailMerge.Execute(dt, "Item");
96 
97            // Fill invoice data.
98            document.MailMerge.Execute(
99                new
100                {
101                    Number = invoiceNumber,
102                    InvoiceDate = invoiceDate.ToShortDateString()
103                });
104 
105 
106            // Fill customer data.
107            document.MailMerge.Execute(
108                new Dictionary<string, object>()
109                {
110                    { "Name", customerName },
111                    { "Address" , companyAddress },
112                    { "Country" , country },
113                    { "ContactPerson" , contantactPerson }
114                });
115 
116            // Fill total.
117            document.MailMerge.Execute(new { TotalPrice = dt.Rows.Cast<DataRow>().Sum(row => (double)row["Total"]) });
118 
119            // Fill notes.
120            document.MailMerge.Execute(
121                new KeyValuePair<string, object>[]
122                {
123                    new KeyValuePair<string, object>("Notes", notes)
124                });
125 
126            return document;
127        }
128 
129        private void SetDataBinding()
130        {
131            DataTable data = (DataTable)Session["DataTable"];
132            double total = 0;
133            foreach (DataRow row in data.Rows)
134            {
135                double totalRow = (int)row["Hours"] * (double)row["Price"];
136                row["Total"] = totalRow;
137                total += totalRow;
138            }
139 
140            DataView dataView = data.DefaultView;
141 
142            this.GridView1.DataSource = dataView;
143            dataView.AllowDelete = true;
144            this.GridView1.DataBind();
145 
146            this.LblTotal.Text = "Total: " + total.ToString("C");
147        }
148 
149        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
150        {
151            DataTable people = (DataTable)Session["DataTable"];
152 
153            people.Rows[e.RowIndex].Delete();
154            this.SetDataBinding();
155        }
156 
157        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
158        {
159            this.GridView1.EditIndex = e.NewEditIndex;
160            this.SetDataBinding();
161        }
162 
163        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
164        {
165            int i;
166            int rowIndex = e.RowIndex;
167            DataTable dt = (DataTable)Session["DataTable"];
168 
169            for (i = 1; i < dt.Columns.Count; i++)
170            {
171                var editTextBox = this.GridView1.Rows[rowIndex].Cells[i].Controls[0] as System.Web.UI.WebControls.TextBox;
172 
173                if (editTextBox != null)
174                {
175                    try
176                    {
177                        dt.Rows[rowIndex][i - 1] = editTextBox.Text;
178                    }
179                    catch (ArgumentException)
180                    {
181                    }
182                }
183            }
184 
185            this.GridView1.EditIndex = -1;
186            this.SetDataBinding();
187        }
188 
189        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
190        {
191            this.GridView1.EditIndex = -1;
192            this.SetDataBinding();
193        }
194 
195        protected void BtnAddItem_Click(object sender, EventArgs e)
196        {
197            DataTable dt = (DataTable)Session["DataTable"];
198            dt.Rows.Add(DateTime.Now, 8, 35);
199            this.SetDataBinding();
200        }
201    }
202}
1Imports System.Collections.Generic
2Imports System.Data
3Imports System.IO
4Imports System.Linq
5Imports System.Web.UI
6Imports System.Web.UI.WebControls
7Imports GemBox.Document
8Imports GemBox.Document.MailMerging
9
10Partial Class _Default
11    Inherits System.Web.UI.Page
12
13    Private Shared invoiceNumber As Integer = 0
14
15    Protected Sub Page_Load(sender As Object, e As EventArgs)
16
17        ' Set license key
18        ComponentInfo.SetLicense("FREE-LIMITED-KEY")
19
20        ' By specifying a location that is under ASP.NET application's control, 
21        ' GemBox.Document can use file system operations to retrieve font data even in Medium Trust environment.
22        FontSettings.FontsBaseDirectory = Server.MapPath("Fonts/")
23
24        If Not Page.IsPostBack Then
25
26            ' Set default values.
27            invoiceNumber = invoiceNumber + 1
28            Me.LblInvoiceNumber.Text = invoiceNumber.ToString()
29            Me.TbxInvoiceDate.Text = DateTime.Now.ToShortDateString()
30
31            ' Fill grid with some dummy data.
32            Dim dt As New DataTable()
33            dt.Columns.Add("Date", GetType(DateTime))
34            dt.Columns.Add("Hours", GetType(Integer))
35            dt.Columns.Add("Price", GetType(Double))
36            dt.Columns.Add("Total", GetType(Double))
37
38            dt.Rows.Add(DateTime.Now.AddDays(-2), 7, 35)
39            dt.Rows.Add(DateTime.Now.AddDays(-1), 8, 35)
40
41            Session("DataTable") = dt
42
43            Me.SetDataBinding()
44
45        End If
46    End Sub
47
48    ' On button click generate the document and stream it to the browser.
49    Protected Sub BtnGenerate_Click(sender As Object, e As EventArgs)
50
51        Dim document As DocumentModel = GenerateDocument()
52
53        Dim fileName = "Report." & RdbOutputFormat.SelectedValue
54
55        document.Save(Response, fileName)
56
57    End Sub
58
59    Private Function GenerateDocument() As DocumentModel
60
61        Dim invoiceDate As DateTime
62        If Not DateTime.TryParse(Me.TbxInvoiceDate.Text, invoiceDate) Then
63            invoiceDate = DateTime.Now
64            Me.TbxInvoiceDate.Text = invoiceDate.ToShortDateString()
65        End If
66
67        Return Process(DirectCast(Session("DataTable"), DataTable), Integer.Parse(Me.LblInvoiceNumber.Text), invoiceDate, Me.TbxCustomerName.Text, Me.TbxCustomerAddress.Text, Me.DdlCustomerCountry.SelectedValue, _
68         Me.TbxContactPerson.Text, Me.TbxNotes.Text)
69
70    End Function
71
72    ' Modify document with the data from web form using Mail Merge.
73    ' This method also shows how to modify document from different data sources.
74    Public Function Process(dt As DataTable, invoiceNumber As Integer, invoiceDate As DateTime, customerName As String, companyAddress As String, country As String, _
75     contantactPerson As String, notes As String) As DocumentModel
76
77        Dim path1 As String = Path.Combine(Request.PhysicalApplicationPath, "Invoice.docx")
78
79        ' Load template document.
80        Dim document As DocumentModel = DocumentModel.Load(path1)
81
82        ' Subscribe to FieldMerging event (we want to format the output).
83        AddHandler document.MailMerge.FieldMerging, AddressOf OnFieldMerging
84
85        ' Fill table.
86        document.MailMerge.Execute(dt, "Item")
87
88        ' Fill invoice data.
89        document.MailMerge.Execute(New With { _
90            .Number = invoiceNumber, _
91            .InvoiceDate = invoiceDate.ToShortDateString() _
92        })
93
94        ' Fill customer data.
95        Dim customerData As Dictionary(Of String, Object) = New Dictionary(Of String, Object)
96        customerData.Add("Name", customerName)
97        customerData.Add("Address", companyAddress)
98        customerData.Add("Country", country)
99        customerData.Add("ContactPerson", contantactPerson)
100        document.MailMerge.Execute(customerData)
101
102        ' Fill total.
103        document.MailMerge.Execute(New With { _
104          .TotalPrice = dt.Rows.Cast(Of DataRow)().Sum(Function(row) CDbl(row("Total"))) _
105        })
106
107        ' Fill notes.
108        document.MailMerge.Execute(New KeyValuePair(Of String, Object)() {New KeyValuePair(Of String, Object)("Notes", notes)})
109
110        Return document
111    End Function
112
113    Private Sub OnFieldMerging(ByVal sender As Object, ByVal e As FieldMergingEventArgs)
114
115        If e.IsValueFound Then
116            Select Case e.FieldName
117                Case "Date"
118                    DirectCast(e.Inline, Run).Text = CType(e.Value, DateTime).ToString("dddd, MMMM d, yyyy")
119                    Exit Select
120                Case "Price", "Total", "TotalPrice"
121                    DirectCast(e.Inline, Run).Text = CDbl(e.Value).ToString("C")
122                    Exit Select
123            End Select
124        End If
125
126    End Sub
127
128    Private Sub SetDataBinding()
129        Dim data As DataTable = DirectCast(Session("DataTable"), DataTable)
130        Dim total As Double = 0
131        For Each row As DataRow In data.Rows
132            Dim totalRow As Double = CInt(row("Hours")) * CDbl(row("Price"))
133            row("Total") = totalRow
134            total += totalRow
135        Next
136
137        Dim dataView As DataView = data.DefaultView
138
139        Me.GridView1.DataSource = dataView
140        dataView.AllowDelete = True
141        Me.GridView1.DataBind()
142
143        Me.LblTotal.Text = "Total: " & total.ToString("C")
144    End Sub
145
146    Protected Sub GridView1_RowDeleting(sender As Object, e As GridViewDeleteEventArgs)
147        Dim people As DataTable = DirectCast(Session("DataTable"), DataTable)
148
149        people.Rows(e.RowIndex).Delete()
150        Me.SetDataBinding()
151    End Sub
152
153    Protected Sub GridView1_RowEditing(sender As Object, e As GridViewEditEventArgs)
154        Me.GridView1.EditIndex = e.NewEditIndex
155        Me.SetDataBinding()
156    End Sub
157
158    Protected Sub GridView1_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
159        Dim i As Integer
160        Dim rowIndex As Integer = e.RowIndex
161        Dim dt As DataTable = DirectCast(Session("DataTable"), DataTable)
162
163        For i = 1 To dt.Columns.Count - 1
164            Dim editTextBox = TryCast(Me.GridView1.Rows(rowIndex).Cells(i).Controls(0), System.Web.UI.WebControls.TextBox)
165
166            If editTextBox IsNot Nothing Then
167                Try
168                    dt.Rows(rowIndex)(i - 1) = editTextBox.Text
169                Catch ex As ArgumentException
170                End Try
171            End If
172        Next
173
174        Me.GridView1.EditIndex = -1
175        Me.SetDataBinding()
176    End Sub
177
178    Protected Sub GridView1_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs)
179        Me.GridView1.EditIndex = -1
180        Me.SetDataBinding()
181    End Sub
182
183    Protected Sub BtnAddItem_Click(sender As Object, e As EventArgs)
184        Dim dt As DataTable = DirectCast(Session("DataTable"), DataTable)
185        dt.Rows.Add(DateTime.Now, 8, 35)
186        Me.SetDataBinding()
187    End Sub
188
189End Class

Check next sample or find out more about GemBox.Document and GemBox Software.