Create Microsoft Word document, Add content from textbox and Add Image by using FileUpload control in ASP.Net

 

Overview:

 

This article deals with how to create and add content and image simultaneously into a newly created document will be explained. After a lot of R&D I found to add the images to a specific position along with the content using file upload control to implement. Microsoft .Net given wonderful classes to implement the functionality to Create Microsoft Word document, Add content from textbox and Add Image by using File Upload control.

 

What Classes and Interfaces I used in this Article ?

 

I have used the following classes and interfaces I used in this article.

 

Microsoft.Office.Interop.Word.ApplicationClass

Microsoft.Office.Interop.Word._Application

Microsoft.Office.Interop.Word._Document

Microsoft.Office.Interop.Word.Paragraph

 

Note : Please Check MSDN for indetail of the classes and the interfaces.

 

Code:  PageName:MSWord.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MSWord.aspx.cs" Inherits="MSWord" %>

<!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>Inserting image into a specific area along with text</title>

</head>

<body>

    <form id="Form1" method="post" runat="server">

    <div>

        Content:<br />

        <asp:TextBox ID="txtBox" runat="server" Rows="5" TextMode="MultiLine" Width="300"

            Columns="5"></asp:TextBox>

        <br />

        <br />

        <asp:FileUpload ID="files" runat="server" />

        <asp:Button runat="server" ID="btnUpload" Text="UploadImage" OnClick="btnUpload_Click" />

        <br />

        <br />

        <asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="Submit" />

        <asp:HiddenField ID="filesToIgnore" runat="server" />

        <div runat="server" id="divTxt">

        </div>

        <span id="list"></span>

    </div>

    </form>

</body>

</html>

 

MSWord.aspx.cs:

 

using System;

using Microsoft.Office.Interop.Word;

using System.IO;


public partial class MSWord : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    }


    protected void Button1_Click(object sender, EventArgs e)

    {

        object nullobj = System.Reflection.Missing.Value;

        object oMissing = System.Reflection.Missing.Value;

        object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

        //Start Word and create a new document.

        Microsoft.Office.Interop.Word._Application oWord;

        Microsoft.Office.Interop.Word._Document oDoc;

        oWord = new Microsoft.Office.Interop.Word.Application();

        oWord.Visible = true;

        oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);

        //Insert a paragraph at the beginning of the document.

        Microsoft.Office.Interop.Word.Paragraph oPara1;

        oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);

        oPara1.Range.Text = "Creating, Writing And Adding Image Into A Word Document";

        oPara1.Range.Font.Bold = 1;

        oPara1.Range.Font.Color = WdColor.wdColorBrown;

        oPara1.Format.SpaceAfter = 12;

        oPara1.Format.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

        oPara1.Range.InsertParagraphAfter();

 

        //Insert a paragraph at the end of the document.

        Microsoft.Office.Interop.Word.Paragraph oPara2;

        object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

        oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);

        oPara2.Range.Font.Color = WdColor.wdColorPlum;

        string TextToWrite = txtBox.Text;

        if (TextToWrite.Length < 0)

        {

            TextToWrite = "<font color='red'> You didnt entered any text from textbox";

        }

        else

        {

            TextToWrite = txtBox.Text;

        }

        oPara2.Range.Text = TextToWrite;

        oPara2.Format.SpaceAfter = 50;

        oPara2.Range.InsertParagraphAfter();

 

        //Insert another paragraph.

        Microsoft.Office.Interop.Word.Paragraph oPara3;

        oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

        oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);

        oPara3.Range.Text = "--------------------------------------------------------------------";

        oPara3.Range.Font.Bold = 0;

        oPara3.Format.SpaceAfter = 24;

        oPara3.Range.InsertParagraphAfter();

        //int x = oWord.Paragraphs.Count;

 

        object fileName1 = @"d:\a.doc";

        oDoc.SaveAs(ref fileName1, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);

        oDoc.Close(ref nullobj, ref nullobj, ref nullobj);

        oWord.Quit(ref nullobj, ref nullobj, ref nullobj);

        string imagepath = Session["ImagePath"].ToString();

        InsertImage(imagepath);

 

    }

    public void readFileContent(string path)

    {

        ApplicationClass wordApp = new ApplicationClass();

        object file = path;

        object nullobj = System.Reflection.Missing.Value;

        Microsoft.Office.Interop.Word.Document docs = wordApp.Documents.Open(

        ref file, ref nullobj, ref nullobj,

        ref nullobj, ref nullobj, ref nullobj,

        ref nullobj, ref nullobj, ref nullobj,

        ref nullobj, ref nullobj, ref nullobj,

        ref nullobj, ref nullobj, ref nullobj, ref nullobj);

 

        docs.ActiveWindow.Selection.WholeStory();

        docs.ActiveWindow.Selection.Copy();

        string sFileText = docs.Content.Text;

        docs.Close(ref nullobj, ref nullobj, ref nullobj);

        wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);

        divTxt.InnerHtml = sFileText;

        //Response.Write(sFileText);

    }

 

    public void InsertImage(string image)

    {

        string path = @"d:\images.jpg"; //test static file paths

        object missing = System.Reflection.Missing.Value;

 

        Microsoft.Office.Interop.Word.ApplicationClass oWordApplic = new ApplicationClass();

        oWordApplic.Visible = true;

        object oTemplate = @"d:\a.doc";

        object LinkToFile = false;

        object SaveWithDocument = true;

 

        Microsoft.Office.Interop.Word.Document WordDoc = oWordApplic.Documents.Add(ref oTemplate, ref missing, ref missing, ref missing);

        object oEndOfDoc = "\\endofdoc";

        int x = WordDoc.Paragraphs.Count;

        Object orMissed = WordDoc.Paragraphs[4].Range; //the position you want to insert

 

        oWordApplic.Selection.InlineShapes.AddPicture(image, ref  LinkToFile, ref SaveWithDocument, ref orMissed);

    }

 

    protected void btnUpload_Click(object sender, EventArgs e)

    {

        if (files.PostedFile.FileName.Length > 0)

        {

            string filename = Path.GetFileName(files.PostedFile.FileName);

            files.SaveAs(Server.MapPath("Images/" + filename));

            Session["ImagePath"] = Server.MapPath("Images/" + filename);

        }

    }

}

 

After running the project you will see the following screen.

                          

 The OUTPUT:

 

      

                                                                                                         Word-ImageandText.rar (1.47 mb)