Click here to Skip to main content
Click here to Skip to main content

ASP.NET generating Dynamic word Documents

, 23 May 2006
Rate this:
Please Sign up or sign in to vote.
Word template programming using ASP.NET

Introduction

This is my first article to the Tech World.

 

This document will help programmers to dynamically create documents using word template without generating any word object on the server.

 

Background

 

In some web applications it is required to create a document generated dynamically, like an Offer letter given to the candidate, some other official letters used during the interviewing purpose, or mark sheet templates etc.

 

In such type of documents most of the things are similar except for few changes.

Let’s take some examples.

 

1.Mark Sheet: Name, Marks Scored, Seat Number etc will change from student to student but other details like the Exam name, stream , university name etc. will remain same.

 

2. Offer letter:  The name, address, post date of offer and date of joining, designation and pay structure etc. will change from candidate to candidate. But other details will remain same.

 

 

Solution

 

To generate O/P for such type of requirement follow a step wise procedure given below.

 

Step1: Create A Word Template

 

           Why Word template?

            

I.                    It is very easy to generate formatted O/P in word.

II.                 Sub scripts and super scripts e.g. ™ can be easily written.

III.               Maintenance of such documents can be easily done, if changes arise.

           

 

 

 

 

How to Create Template?

 

e.g.

1.  Offer Letter:

 

##Address##,                                                              ##DOF##

 

Dear ##Name##,

 

We are glad to appoint you for the designation ## desig ##.

 

  1. Mark sheet:

 

Name: ##NAME##

 

Seat Number: ##Number##

 

Subject1     ##SUB1##          

Subject2     ##SUB2##

Subject3     ##SUB3##

Subject4     ##SUB4##

Subject5     ##SUB5##

 

Total           ##Total##

Percentage: ##PER##

 

 

In the e.g.1 we see ##Address##, ##DOF##, ##NAME## and ##desig##. All these will be replaced by dynamic data selected by the user. Whereas the static data will remain the same.

 

Similarly in example 2. for Mark sheet

##SUB1## , ##SUB2##  , ##SUB3##      etc. will be dynamic.

 

This dynamic data can be made available from the database.

 

Once you have formatted your template file in word as per the guidelines outlined above save the file. Provide appropriate name to the file.

 

Note: The saving format should be Rich Text Format(RTF). Click on File – select save as and then select the path and save the file as .rtf extension file.

 

 

 

Step2: Proceed with the code & instructions given below

 

Make use of file scripting object to copy the template file into some temporary file.

 

Note: The path of the temporary file should be fixed and it should also have a .rtf extension as the template file.

 

‘ Declare a scripting object.

Dim td = Server.CreateObject("Scripting.FileSystemObject")

 

‘Copy File

td.CopyFile(Server.MapPath(".") & "Template.rtf", Server.MapPath(".") & "Temporary.rtf")

 

‘ set the file path in a string variable.

            strFilePath = Server.MapPath(".") & "Temporary.rtf"

 

 

 

‘Now open the termporary file in Read mode.

Dim fs2 As New FileStream(strFilePath, FileMode.Open, FileAccess.Read)

 

'Declare d as a stream Reader

            Dim d As New StreamReader(fs2)

 

Dim swrtarget As String

 

'Initialise the stream reader d to the begining of the file.

            d.BaseStream.Seek(0, SeekOrigin.Begin)

            swrtarget = d.ReadToEnd 'Read the file from Start to End in one go.

            d.Close() ' Close the Stream Reader

 

 

Declare string variables say,

Str1ans strvalue1.

Now get the values from database.

Use can use a select query and a data reader to get the values.

 

Now set the file path to the Temporary file

'Set the path to open Temporary

            strFilePath = Server.MapPath(".") & "Temporary.rtf"

 

‘Open the temporary file in Read-Write Mode.

Dim fs1 As New FileStream(strFilePath, FileMode.Open, FileAccess.ReadWrite)

 

Dim s As New StreamWriter(fs1) 'Declare a Stream Writer.

 

'Replace the values with the values in the string read from Temporary.

While myReader.Read

 

Strvalue1= myReader.GetValue(0).ToString()

                Str1= Replace(swrtarget.ToString, ##Address##", Trim(strvalue1)

                Strvalue1= myReader.GetValue(1).ToString()

                str1= Replace(str.ToString, ##Name##", Trim(strvalue1)

 

Similarly it will come for ##DOF## and ##desig###.

 

End While

 

Close the Reader.

Close the Connection.

 

' After replacing all the values write these values in the file2.rtf via the file write (s).

            s.WriteLine(str)

            'After writing the data in the stream writer the values must be flushed.

            s.Flush()

            'Close the stream writer.

            s.Close()

            fs1.Close()

            fs2.Close()

 

 

Now copy the details into the final file.

This file can be a .dc file.

 

Dim td1 = Server.CreateObject("Scripting.FileSystemObject")

        td1.CopyFile(Server.MapPath(".") & "Temporary.rtf", Server.MapPath(".") & "final.doc")

        'Open a new window in the browser and display final.doc file to the  user.

        strtargetFilepath = " finalletter.doc"

        Response.Write("<script> window.open('" & strtargetFilepath & "') </script>")

 

 Main Code Sippnet

******************************************************************************************************************************************************

Public Sub GetOutput()

        Dim strFilePath As String   'Declare string variable to store file path.

        Try

 

            Dim strvalue As String

            Dim myReader As OleDb.OleDbDataReader

            Dim SqlStr1 As String

            Dim Srefno As String

            Srefno = Nothing

            ' Declare a file system object say td.

            Dim td = Server.CreateObject("Scripting.FileSystemObject")

            ' Copy the template file temp2.rtf into file2.rtf.

            td.CopyFile(Server.MapPath(".") & "/temp2.rtf", Server.MapPath(".") & "/file2.rtf")

           

 

            ' Set file path to file2.rtf.

            strFilePath = Server.MapPath(".") & "file2.rtf"

            ' Get the refno into Srefno variable.

            Srefno = Session("RefNo")

            Dim strString As String

            Dim cmd As OleDbCommand

            'Open file2.rtf in read mode.

            Dim fs2 As New FileStream(strFilePath, FileMode.Open, FileAccess.Read)

            'Declare d as a stream Reader

            Dim d As New StreamReader(fs2)

            'A string variable used to store all the values received from the file fiel2.rtf.

            Dim swrtarget As String

            ' This variable str will store all the values from the 2nm till final.

            ' Finally the string writer will write the values stored in the str variable.

            Dim str As String

 

            'Initialise the stream reader d to the begining of the file.

            d.BaseStream.Seek(0, SeekOrigin.Begin)

            swrtarget = d.ReadToEnd 'Read the file from Start to End in one go.

            d.Close() ' Close the Stream Reader

 

 

            Dim SqlStr As String

            Dim srno As String

 

 

            SqlStr = " Your Query HERE"

            clsCon.OpenCon(ConfigurationSettings.AppSettings("strConnection").ToString)

            cmd = New OleDb.OleDbCommand(SqlStr, clsCon.Con)

            myReader = cmd.ExecuteReader

 

 

            'Set the path to open file2.rtf

            strFilePath = Server.MapPath(".") & "file2.rtf"

            'Open file file2.rtf in Read Write Mode

            Dim fs1 As New FileStream(strFilePath, FileMode.Open, FileAccess.ReadWrite)

 

            Dim s As New StreamWriter(fs1) 'Declare a Stream Writer.

            'Now Read values from database i.e. table--> tblofferletter in the string variable strvalue.

            'Replace the values with the values in the string read from file2.rtf

            While myReader.Read

                strvalue = myReader.GetValue(0).ToString()

                str = Replace(swrtarget.ToString, "##refno##", Trim(strvalue))

                strvalue = myReader.GetValue(1).ToString()

                str = Replace(str.ToString, "##Title##", Trim(strvalue))

                strvalue = myReader.GetValue(2).ToString()

                str = Replace(str.ToString, "##FirstName##", Trim(strvalue))

                strvalue = myReader.GetValue(3).ToString()

                str = Replace(str.ToString, "##LName##", Trim(strvalue))

                strvalue = myReader.GetValue(4).ToString()

               

            End While

            myReader.Close()

            cmd.Dispose()

 

            ' After replacing all the values write these values in the file2.rtf via the file write (s).

            s.WriteLine(str)

            'After writing the data in the stream writer the values must be flushed.

            s.Flush()

            'Close the stream writer.

            s.Close()

            fs1.Close()

            fs2.Close()

 

            'Initialise the srefno to nothing so that when new report is requested it will have the latest value.

            Srefno = Nothing

 

 

        Catch ex As Exception

            Response.Write("" + ex.Message)

                  Response.Write("")

 

        Finally

            ' Response.Write("OFFER LETTER GENERATED SUCCESSFULLY.")

                  clsCon.closeCon()

                 

        End Try

 

    End Sub

 

************************************************************************************

 

Advantages

 

  1. Easy maintainability – Changes in the template can be made easily and updated.
  2. Just Few Lines of code.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Nil_Gup
Web Developer
India India
Respectfully Yours,
Nilesh J. Gupte
(B.E. Computer Engg.)

Comments and Discussions

 
QuestionGenerate Label Stubs on single page PinmemberShashank Pangam28-May-14 6:53 
QuestionHow to print? Pinmemberdollargetdollar201120-Oct-11 22:24 
QuestionHow to add rows and write content in perticular cell of inserted rows? Pinmemberamit_834-Mar-11 20:18 
QuestionGenerate word table filled with data Pinmemberkrotas7-Sep-09 8:21 
AnswerRe: Generate word table filled with data PinmemberJohnny Glenn11-Apr-12 22:18 
Generalrtf formatting problem Pinmemberdimi-d10-Jun-09 0:56 
Generalchange text font in output file Pinmemberwinnc23-Mar-09 4:25 
GeneralRe: change text font in output file PinmemberNil_Gup23-Mar-09 6:45 
GeneralRe: change text font in output file Pinmemberwinnc24-Mar-09 5:23 
In my output file I have to use "C39HrP24DhTt" ( a barcode font) for ##ref##. When I change the font in the input file the "string.replace" doesn't recongnize this font. That's why I'm thinking to replace the data first then on the way to write to the output file changing the font.
GeneralRe: change text font in output file PinmemberNil_Gup24-Mar-09 7:28 
GeneralMultiple Pages PinmemberChesty177530-Jan-09 3:53 
GeneralRe: Multiple Pages Working Code in C# PinmemberChesty177530-Jan-09 10:39 
Questionproblem converting the while loop to aspx / c# Pinmemberhvemmig26-Jan-09 22:27 
Generalerror with ur code Pinmembervijaylumar8-Jun-08 21:01 
GeneralDid not replace my text PinmemberRyanJay15-Aug-07 20:57 
GeneralRe: Did not replace my text PinmemberNil_Gup16-Aug-07 5:04 
QuestionFiles size and formatting PinmemberGorata23-Apr-07 23:40 
AnswerRe: Files size and formatting PinmemberNil_Gup24-Apr-07 7:21 
GeneralDid a rewrite to C#/ASP.NET PinmemberC#_Pimpin24-Mar-07 11:26 
QuestionSimilar Requiremnt Pinmembernkmanglam16-Feb-07 3:50 
Questionit is very good article, but "##refno##", "##Title##" not working Pinmembersimonkang27-Nov-06 4:33 
AnswerRe: it is very good article, but "##refno##", "##Title##" not working PinmemberNil_Gup27-Nov-06 4:42 
GeneralArticle OK but Formatting is not good Pinmembercykophysh3913-Nov-06 1:13 
GeneralProblem with Encoding Pinmemberabiradib1-Jun-06 2:34 
GeneralRe: Problem with Encoding Pinmemberrealnaimi26-Aug-06 21:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 23 May 2006
Article Copyright 2006 by Nil_Gup
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid