If I have a.doc file with text, can I print the text?

Is there any Class/Method in asp.net with which I can print the text of a doc file?

Another question:

I ahev a populated gridview or a datalist and I want to copy it to a file which I have just created. I tried the StreamWriter like:

StreamWriter sw=new StreamWriter(FileName);

sw.Write(DataList1);

 

Well I didn't expect it to work, but do you have any ideas how can I copy the whole datalist to the file via codebehind? 

 

Thanks

0
Tengo
4/6/2008 6:21:18 PM
asp.net.getting-started 91979 articles. 3 followers. Follow

10 Replies
579 Views

Similar Articles

[PageSpeed] 17

You cannot print the text of a .doc file just like that with the built in asp features.

You can either use the Office Components or Aspose.Words to achive this.


Remy Blaettler
Chief of the System
Supertext AG
0
rblaettler
4/6/2008 7:43:18 PM

Ok, I don't have any idea what you mean in Office Components or in Aspose.Words... So can you explain what is it or just how can I print a page when I press on a button in my website? You know I mean what should I write in the click event in order to print the page of that file anyhow..

Or you know what - can you explain how to print a regular page of the site? not of a file.. just how to send a print command somehow via codebehind or in other automatic way?

(If possible..)

 

Thanks

 

0
Tengo
4/6/2008 7:57:58 PM

 Hi Tengo,

check this code....



using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Web;
using System.IO;


namespace CsXml.FormPrint
{
 public class WebPrinting
 {


  protected StringReader stringToPrint;
  protected Font printFont;


  public WebPrinting()
  {
  }


  public void PageCreate(string printerName, string pageTitle)
  {
   StringBuilder sb = new StringBuilder();
   string qs = "";
   try
   {
    // start creating page with title and date/time
    sb.Append(pageTitle + "\n\n");
    sb.Append("DateTime: " + DateTime.Now.ToString()+ "\n\n");
    string fieldValue;
    // iterate submitted form fields, also gets field name
    foreach ( string fieldName in HttpContext.Current.Request.Form )
    {
     // exclude viewstate and submit button
     if (fieldName == "__VIEWSTATE" || fieldName == "Submit"){}
     else
     {
      // get the field value
      fieldValue = HttpContext.Current.Request.Form[fieldName] ;
      // builds the querystring for results.aspx
      qs = qs + "&" + fieldName + "=" + fieldValue;
      // adds the field name and value to the page
      // breaks the field value into 50 character segments so it will fit on the paper
      // this example only accounts for fields of l50 characters or less
      // issue: breaks in the middle of words instead of at spaces
      if (fieldValue.Length > 100)
      {
       sb.Append(fieldName + ": " + fieldValue.Substring(0,50) + "\n");
       sb.Append("            " + fieldValue.Substring(50,50) + "\n");
       sb.Append("            " + fieldValue.Substring(100,fieldValue.Length - 100) + "\n");
      }
      else if(fieldValue.Length > 50)
      {
       sb.Append(fieldName + ": " + fieldValue.Substring(0,50) + "\n");
       sb.Append("            " + fieldValue.Substring(50,fieldValue.Length - 50) + "\n");
      }
      else
      {
       sb.Append(fieldName + ": " + fieldValue + "\n");
      }
      
     }
    }
    // place stringbuilder in string reader
    stringToPrint = new StringReader(sb.ToString());
    // set font and size here
    printFont = new Font("Arial", 12);
    PrintDocument doc = new PrintDocument();
    // set the printer name
    doc.PrinterSettings.PrinterName = printerName;
    // add print page event handler
    doc.PrintPage += new PrintPageEventHandler(this.PagePrint);
    // print the page
    doc.Print();
    // adds status to querystring
    qs = "Results.aspx?" + qs.Substring(1,qs.Length-1) + "&Status=Success";
   }
   catch
   {
    qs = "Results.aspx?Status=Failed";
   }
   finally
   {
    stringToPrint.Close() ;
   }
   // redirects to result.aspx
   HttpContext.Current.Response.Redirect(qs);
  }




Hope this help...

Thanks,
----
j@y


Mark as Answered if this Helped You.


Thanks,
----
j@y

Please remember to click “Mark as Answer” on the post(s) which helps you !
0
Dexter007
4/7/2008 5:25:53 AM

Thanks, but it prints a blank page. I have tried just to print a regular string like: sdfshdfjkshdfjsdkfhjk...

but it printed a blank page.

Tell you the truth I think it's a little bit odd that the doc object doesn't get somhow the string which should be printed.. But I didn't find any property for that.. Any ideas?

0
Tengo
4/7/2008 11:53:37 AM

Dexter, the code you posted only works for WinForms. I don't think that will work for an ASP page, or the file will be printed on the server.

Don't think that is the idea, no?

If you want to just print a website, you can use the window.print() function. I wrote a little post about it with an example:

http://remy.supertext.ch/2008/04/print-a-web-page-with-javascript/

Hope this helps.


Remy Blaettler
Chief of the System
Supertext AG
0
rblaettler
4/7/2008 7:16:19 PM

hi!

do you want to export your gridview to a file located on the Server or do you want to throw the html code of the server controlS to the client (IE, MOzilla, etc...)?

 

ciao ;-)


jan maru

Click "Mark as Answer" on the post if my words were helpful.

0
janmaru
4/7/2008 7:50:34 PM

Hi, thanks for the reply.

 

Well, I have to stress out the fact that I donwt really understand your question - but I'll tell what is the target eventually - ":

 

I want the gridview which shows a table-like thing - you know from the DB - I want it to appear in my doc file just as it appears on my website page. IE copy it somehow to there.  Any ideas?

 

Oh and I have an extremely important question:

 

How can I add a row to a gridview? More details:

 I have a gridview which shows a user's shopping cart. The gridview has a column in which there checkboxes (I added a column with a templated field and then in the template load I draged a checkbox). I want all the selected rows in that gridview to be added to a new gridview which I create in the cs. But I have noticed that there isn't any AddRow/InsertRow method there... So how can I add the ready rows just as they are to a new gridview?

Question number 3:

In my gridview, as I have mentioned above, I have the checkbox column, and in addition, except the bound data from the database, other columns such as Total price and Jewel Image, for example, which get their values from the aspx.cs IE in the runtime. I have a button - delete all selected. I have a SqlDataSource - there I have the DeleteCommand set. In the click event of the button I delete the row with the: GVCart.DeleteRow(IndexRow) . OK it deletes from the database as I wish but when it deletes from the gridview - it loses the data of the Total and JewelImage fields as they didn't exist... But when I do a refresh the data returns back and everything is just fine. My question is - Can't it be done without the refresh? And not - why??? It seems a little odd.. I followed it in the debug and I saw it entered to the disasembly....... Strange..

 

So in a conclusion - my most important question is with the AddRow to the gridview - it's extremely important , please if you have any ideas - write a sample of code.

 

Thanks

0
Tengo
4/8/2008 6:49:55 PM

hi!

hope this code will help you... sorry but too many questionS, this is the basic

 

Partial Class test1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim clmID As New System.Data.DataColumn

        With clmID
            .ColumnName = "ID"
            .DefaultValue = 1
        End With
        Dim clmName As New System.Data.DataColumn

        With clmName
            .ColumnName = "Name"
            .DefaultValue = "maru"
        End With
        Dim clmSurname As New System.Data.DataColumn

        With clmSurname
            .ColumnName = "Surname"
            .DefaultValue = "jan"
        End With

        Dim dt As New System.Data.DataTable

        dt.Columns.Add(clmID)
        dt.Columns.Add(clmName)
        dt.Columns.Add(clmSurname)

        For i As Integer = 0 To 10
            Dim rw As System.Data.DataRow = dt.NewRow
            rw.Item("ID") = i
            rw.Item("Name") = "jan" + i.ToString
            rw.Item("Surname") = "maru" + i.ToString
            dt.Rows.Add(rw)
        Next

        Me.GridView1.DataSource = dt
        Me.GridView1.DataBind()



    End Sub

    Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LinkButton1.Click
        Response.Clear()
        Response.AddHeader("content-disposition", "attachment;filename=FileName.doc")

        Response.Charset = "ISO-8859-1"

        Response.Cache.SetCacheability(HttpCacheability.NoCache)

        Response.ContentType = "application/vnd.word"

        Response.Write(Session("grid"))

        Response.End()

    End Sub
    Protected Overloads Overrides Sub OnPreRender(ByVal e As EventArgs)
        Session("grid") = GetHtmlFromControl(Me.GridView1)
    End Sub
    Private Shared Function GetHtmlFromControl(ByVal control As Control) As String
        Dim html As String = String.Empty
        Using sw As New System.IO.StringWriter()
            Using tw As New HtmlTextWriter(sw)
                control.RenderControl(tw)
                html = sw.ToString()
            End Using
        End Using
        Return html
    End Function
    Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
    End Sub
End Class

 and the page...

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="test1.aspx.vb" Inherits="test1" %>

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <asp:LinkButton ID="LinkButton1" runat="server">Export to Word</asp:LinkButton>
    </form>
</body>
</html>

 

ciao ;-)


jan maru

Click "Mark as Answer" on the post if my words were helpful.

0
janmaru
4/8/2008 7:39:30 PM

Thank you very much, but can you write in c#? (If you know c#..) Because Visual basic is rather Chinesse for me than English...

Oh and in the row adding - If I have a ready row - can't I add it to the Gridview RowCollection as it is without the cells copying? (Because I have a lot of columns  - I think there's got to be a way to insert it .. maybe I'm wrong - But Imean somehow with a forloop or something like that..I have tried to think about it but couldn't find a way without going to its cells..) If there isn't, so it seems that I have to create rows each one with 10 columns?

However thank you, and if you are able write somehow the code you have written in c# please, and if you can write which method deals with which question I 've got a little mixed up with it

 

Thanks

0
Tengo
4/8/2008 7:58:00 PM

hi!

actually chinese is easier then english and italian, too!!! You can add rowS to your data and bind lateR your Grid or you can add rowS to your grid dynamically... I can't tell from your descriptionS what really you want to do, maybe posting a bit of your code could help...

 

using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;


    partial class test1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, System.EventArgs e)
        {
            System.Data.DataColumn clmID = new System.Data.DataColumn();

            {
                clmID.ColumnName = "ID";
                clmID.DefaultValue = 1;
            }
            System.Data.DataColumn clmName = new System.Data.DataColumn();

            {
                clmName.ColumnName = "Name";
                clmName.DefaultValue = "maru";
            }
            System.Data.DataColumn clmSurname = new System.Data.DataColumn();

            {
                clmSurname.ColumnName = "Surname";
                clmSurname.DefaultValue = "jan";
            }

            System.Data.DataTable dt = new System.Data.DataTable();

            dt.Columns.Add(clmID);
            dt.Columns.Add(clmName);
            dt.Columns.Add(clmSurname);

            for (int i = 0; i <= 10; i++)
            {
                System.Data.DataRow rw = dt.NewRow();
                rw.SetField("ID", i);
                rw.SetField("Name", "jan" + i.ToString());
                rw.SetField("Surname", "maru" + i.ToString()); 

                dt.Rows.Add(rw);
            }

            this.GridView1.DataSource = dt;
            this.GridView1.DataBind();



        }

        protected void LinkButton1_Click(object sender, System.EventArgs e)
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");

            Response.Charset = "ISO-8859-1";

            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            Response.ContentType = "application/vnd.word";

            Response.Write(Session["grid"]);

            Response.End();

        }
        protected override void OnPreRender(EventArgs e)
        {
            Session["grid"] = GetHtmlFromControl(this.GridView1);
        }
        private static string GetHtmlFromControl(Control control)
        {
            string html = string.Empty;
            using (System.IO.StringWriter sw = new System.IO.StringWriter())
            {
                using (HtmlTextWriter tw = new HtmlTextWriter(sw))
                {
                    control.RenderControl(tw);
                    html = sw.ToString();
                }
            }
            return html;
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
        }
    } 
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test1.aspx.cs" Inherits="test1" %>

<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" >Export to Word</asp:LinkButton>
    </form>
</body>
</html>

  ciao ;-)
   

 


jan maru

Click "Mark as Answer" on the post if my words were helpful.

0
janmaru
4/8/2008 8:42:18 PM
Reply:

Similar Artilces:

length or trim ? how can i get textbox.text as text that publichouse to textbox.text as text that public ?
hello friends length or trim ? how can i get textbox.text as text that publichouse to textbox.text as text that public ? second example is ..... textbox1.text is greenhouse.. i want to get green from textbox.text cheer Mark as me if my question or my answer can be helpful for you :) Hi,you can always perform a Trim to a retrieved string to delete the leading and trailing space characters. For your second example where you want to gt a part of the retrieved string you can use the SubString method of the String class.Grz, Kris. Read my blog. Handy Firefox plugins for web developers.Workar...

When I upload a text file from client to server using stream, how can I guarantee that the uploaded text file can be displayed correctly?
When I upload a text file from client to server using stream, how can I guarantee that the uploaded text file can be displayed correctly? A user want to upload a text file from client PC to server (normally it is Windows 2003), but I'm not sure which OS it is in client, maybe it is a english version Windows or chinese Windows (default encoding is GB2312).so the encoding of text file in client maybe is ASCII or GB2312.I think that "StreamReader myRead= new StreamReader(FileUpload1.PostedFile.InputStream,Encoding.Default) will be run in server,so "Encoding.Default" will be the default encodin...

Can someone tell me why I can't get this sentence to get displaye d from a text paragraph file:(
# loop & search for file: while(<>){ print if ($ARGV=~/^has been working very hard.$\i); } Error Msg Search pattern not terminated at line 13. Many Thanks! ...

who can tell me the format of SDF text file and CSV text file?
as title thanks On Sat, 14 Aug 1999 18:22:36 +0800, "simon" <simonshen@netease.com> wrote: >who can tell me the format of SDF text file and CSV text file? They are both text file formats used to hold data. SDF (System Data Format) - fields are fixed length. CSV (Comma Separated Values) - fields are separated by a comma Boris Gasin [TeamSybase] mailto:bgasin@dynamictechgroup.com ___ ____ _ _____ _ ____ _ ___ Dynamic Technology Group, Inc. http://www.dynamictechgroup.com/ ...

RE: Can someone tell me why I can't get this sentence to get disp laye d from a text paragraph file:(
> print if ($ARGV=~/^has been working very hard.$\i); That second slash is going the wrong way (\ instead of /) ____________________ Chris Spurgeon Senior Design Technologist cspurgeon@electronicink.com ELECTRONIC INK One South Broad Street 19th Floor Philadelphia, PA 19107 www.electronicink.com t 215.922.3800 x(233) f 215.922.3880 -----Original Message----- From: AMORE,JUAN (HP-Roseville,ex1) [mailto:juan_amore@hp.com] Sent: Monday, October 15, 2001 5:28 PM To: Beginners@Perl. Org (E-mail) Subject: Can someone tell me why I can't get this sentence to get...

Getting Text Between Two Words In Text File
Hi everyone, Im just wondering what the best way to do this would be.I need to get a certain line of text from a number of text file records.This text lies between "-" and a </strong> tag. How would I go about this Thanks for your help! julie Use the File class to open and read your file and then use Regular Expression to find the specific word. References: File Class Regular Expression "I refuse to sign my posts with some clever quote said by some famous tech head in order to make myself seem more intelligent"-- Bill Gates...

How do I get the Text of a Text ....
That may sound confusing, but I need to get the text of a Dynamically created text object. For each row the Text objects text might be somthing different, and when I loop through all the rows, I need to see if any of them are a certain Word. When I used Getitemstring, it doesn't like it. dw_1.Describe( 'text_control.text' ) will give you the .text attribute of a text control in a datawindow. How are you getting different values for the .text attributes on different rows? Using an expression or something? -- Paul Horan[TeamSybase] VCI Springfield, MA www.v...

Can read text on line 5 in text file?
How to read a string form text file on a line you want?EX: read text on line 5 in txt file had 10 lineCan help me? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconReadingTextFromFile.aspSimply modify the loop from the example with a conditional "if" statement to look at a counter variable when it reaches line five, and you're all set.-- Dan Fields...

Programmatically getting text from resource file: can't get GetGlobalResourceObject to work :(
I have a site that uses resource files to translate my site into various languages.  It works fine for basic labels and such on the site.  However, I am now translating my dynamically generated error messages and I am having trouble.  After several hours of trying last night I discovered the GetGlobalResourceObject method, but I am having trouble with getting the correct syntax. Here's a snippet from my script:  if (pwd != "")                    {  &nb...

Google doc (text doc) not doing "File > print/view as webpage"
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9pre) Gecko/2008051406 Minefield/3.0pre On a text document created at http://docs.google.com/ there are two "google doc" menu items under "File" menu * File > print as webpage... * File > view as webpage... I dont see this working on Firefox trunk. * is it a Firefox bug ? * or a google doc bug? I also dont see any error message at JS console. ...

Append a text file to an existing text file
Hello, Is there a way to append a text file to an existing text file. For example, File A: Jan Feb Mar April ... File B: 10 30 40 20 ... After appending job, the File A would be like below. Jan Feb Mar April ... 10 30 40 20 ... TIA On Sep 18, 11:49=A0am, backgoo...@gmail.com (Back9) wrote: > Hello, > > Is there a way to append a text file to an existing text file. > For example, > File A: > Jan Feb Mar April ... > > File B: > 10 30 40 20 ... > > After appending job, the File A would be like below. > Jan Feb Mar April ... &g...

Load a Text File, Search a Text File
I'd like to load a text file that has a list of target words and replacement words. After loading the list, I'll replace all words with the target word. I've got the code worked out to do the replacing, now I just need some help with how to actually load and search the text file (xml). Here what it looks like: <dictionary> <entry> <word>Word1</word> <equivalent>Word1R1</equivalent> <equivalent>Word1R2</equivalent> <equivalent>Word1R3</equivalent> </entry> </dictionary> Th...

How to append a text file to an existing text file
Hello, Is there a way to append a text file to an existing text file. For example, File A: Jan Feb Mar April ... File B: 10 30 40 20 ... After appending job, the File A would be like below. Jan Feb Mar April ... 10 30 40 20 ... TIA Hi, It's a basic job in Perl, just open, read, and print. open B with read mode; read the content of B into memory (ie, save to a variable); close B; open A with append mode; write B's content to A; close A; 2008/9/19 Back9 <backgoodoo@gmail.com>: > Hello, > > Is there a way to append a text file to...

Text as text
Name: JohnA Boice Email: jaboiceathughesdotnet Product: Firefox Summary: Text as text Comments: You need to do as Safari does and make ALL text, including buttons, links, bookmarks, and general page text actual text so screen readers can interpret and voice the text. Until this occurs, your products are a real pain to use. And I have limited sight. What about those with less or no sight? Browser Details: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3 ...

Web resources about - If I have a.doc file with text, can I print the text? - asp.net.getting-started

Print - Wikipedia, the free encyclopedia
Old master print , a product of printmaking, such as an engraving , etching or woodcut , in the European tradition, instead of others (e.g., ...

Print Wikipedia
From Aaaaa! to ZZZap! an exhibition by Michael Mandiberg at Denny Gallery, 261 Broome St. featuring work from the Print Wikipedia series June ...

Old master print - Wikipedia, the free encyclopedia
An old master print is a work of art produced by a printing process within the Western tradition (European or New World). A date of about 1830 ...

Piccolo Automatically Sends Users Prints Of Their Photos On Facebook, Instagram
... Instagram applications and services, as startup Piccolo announced its beta launch, aimed at allowing users to automatically receive printed ...

READ, WEEP, PRINT... - Facebook
The Blacksphere hat geschrieben: READ, WEEP, PRINT AND KEEP! This... Tritt Facebook bei, um dich mit The Blacksphere und anderen Nutzern, die ...

Print Facebook Photos at Target Through Kodak Picture Kiosks — But at What Resolution?
Users looking to make physical copies of their Facebook photos can now print them at Kodak Picture Kiosks at Target retail stores. The kiosks ...

Mediaite.com - News & Opinion - Media: TV, Print, Online, Jobs, Ranking
Mediaite is a news and opinion blog and aggregator for the media industry. Coverage includes newspapers, magazines, online, and television. The ...

Re-print of Adolf Hitler's 'Mein Kampf' unleashes row in Germany
For the first time since Hitler's death, Germany is publishing the Nazi leader's political treatise 'Mein Kampf', unleashing a highly charged ...

Hearst Plans to Launch New Print Products in 2016
In a year-end letter to staffers, Hearst Magazines president David Carey said the company plans to launch new print products and partner with ...

Company 3D prints ceramics that can withstand 1700ºC temps
... manufacturing, especially of complex shapes, challenging. Now, a team at a company called HRL Laboratories has described a method of 3D printing ...

Resources last updated: 1/10/2016 8:38:52 PM