Solved

C#.NET Printing Text

Posted on 2010-09-23
7
1,320 Views
Last Modified: 2013-12-16
I'm sure that this is simple but I can't find a good example so far.

I want to create a simple report which will be sent to the printer.  I am currently using the UltraPrintPreviewDialog and UltraPrintDocument classes but I think that they work in a similar way to the standard .NET PrintDocument.  

I click a button to create the report and have added header and footer text to the report and then use the ultraPrintPreviewDialog.ShowDialog to see the eport - all good so far.

I want however to add text to the body of the report - this will be a number of lines of straight text followed by two lists with a few columns in them.

I can't seem to find out WHERE I add the text to the report - do I trap the PageBodyPrinting and add the text there?  If so how do I actually add the text to print and how do I deal with the situation where I have too much text to fit onto one page of the report?

I thought that there would be a simple AddLine function of the PrintDocument but this does not seem to be how this works.

Thanks for any suggestions/examples of creating a multi-page report.
0
Comment
Question by:ChrisMDrew
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 

Author Comment

by:ChrisMDrew
ID: 33742763
In addition, I need to be able to print in columns as I am including the contents of list views in the printed document...
0
 
LVL 3

Expert Comment

by:MRomani
ID: 33743707
heres an example off the msdn page regarding printing...might be easier to use PrintDocument Class....

hope that helps, also, maybe you can check out the System.Drawing.Printing Namespace here for other usefull info... (http://msdn.microsoft.com/en-us/library/system.drawing.printing(v=VS.71).aspx)
[C#] 
public class PrintingExample : System.Windows.Forms.Form 
{
    private System.ComponentModel.Container components;
    private System.Windows.Forms.Button printButton;
    private Font printFont;
    private StreamReader streamToPrint;

   public PrintingExample() : base() 
   {
      // The Windows Forms Designer requires the following call.
      InitializeComponent();
   }

   // The Click event is raised when the user clicks the Print button.
   private void printButton_Click(object sender, EventArgs e) 
   {
      try 
      {
          streamToPrint = new StreamReader
             ("C:\\My Documents\\MyFile.txt");
          try 
          {
             printFont = new Font("Arial", 10);
             PrintDocument pd = new PrintDocument();
             pd.PrintPage += new PrintPageEventHandler
                (this.pd_PrintPage);
             pd.Print();
          }  
          finally 
          {
             streamToPrint.Close();
          }
      }  
      catch(Exception ex) 
      {
          MessageBox.Show(ex.Message);
      }
   }

   // The PrintPage event is raised for each page to be printed.
   private void pd_PrintPage(object sender, PrintPageEventArgs ev) 
   {
      float linesPerPage = 0;
      float yPos = 0;
      int count = 0;
      float leftMargin = ev.MarginBounds.Left;
      float topMargin = ev.MarginBounds.Top;
      string line = null;

      // Calculate the number of lines per page.
      linesPerPage = ev.MarginBounds.Height / 
         printFont.GetHeight(ev.Graphics);

      // Print each line of the file.
      while(count < linesPerPage && 
         ((line=streamToPrint.ReadLine()) != null)) 
      {
         yPos = topMargin + (count * 
            printFont.GetHeight(ev.Graphics));
         ev.Graphics.DrawString(line, printFont, Brushes.Black, 
            leftMargin, yPos, new StringFormat());
         count++;
      }

      // If more lines exist, print another page.
      if(line != null)
         ev.HasMorePages = true;
      else
         ev.HasMorePages = false;
   }


   // The Windows Forms Designer requires the following procedure.
   private void InitializeComponent() 
   {
      this.components = new System.ComponentModel.Container();
      this.printButton = new System.Windows.Forms.Button();

      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(504, 381);
      this.Text = "Print Example";

      printButton.ImageAlign = 
         System.Drawing.ContentAlignment.MiddleLeft;
      printButton.Location = new System.Drawing.Point(32, 110);
      printButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
      printButton.TabIndex = 0;
      printButton.Text = "Print the file.";
      printButton.Size = new System.Drawing.Size(136, 40);
      printButton.Click += new System.EventHandler(printButton_Click);

      this.Controls.Add(printButton);
   }

   // This is the main entry point for the application.
   public static void Main(string[] args) 
   {
      Application.Run(new PrintingExample());
   }
}

Open in new window

0
 

Author Comment

by:ChrisMDrew
ID: 33744044
Thanks,

I have seen elsewhere the concept of deriving from PrintDocument so that you can set the text to be printed and then iterating through this in the PrintPage (or OnPrintPage) function.  I quite like the Infragistics derivation of the PrintDocument as it gives me some extra control over the headers and footers which does not seem to be in the base class.

I have created my own PrintDocument class with this added in and have at least been able to output to the printer/print preview.  My main problem now (for my very simple report) is how to calculate the printable area.  My class uses


//Set print area size and margins
printHeight = base.DefaultPageSettings.PaperSize.Height - base.DefaultPageSettings.Margins.Top - base.DefaultPageSettings.Margins.Bottom;
printWidth = base.DefaultPageSettings.PaperSize.Width - base.DefaultPageSettings.Margins.Left - base.DefaultPageSettings.Margins.Right;
leftMargin = base.DefaultPageSettings.Margins.Left;  //X
rightMargin = base.DefaultPageSettings.Margins.Top;  //Y

However tghis does not work correctly with the Infragistics UltraPrintDocument - presumabl;y because of the header.  Any ideas how to obtain the print area for UltraPrintDocument?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 33745851
I'm not familiar with the Infragistics libraries you're using, though I have recently used the .Net PrintDocument class to print a simple report with limited formatting.  It's tedious pain in the neck - if you can get away with plain text (i.e. no graphics, no font decorations a la bold/italic/underline/etc) it's easy to send raw text to the printer using the class outlined in this KB article: http://support.microsoft.com/kb/322090 (though there is no graphics support, you can still achieve some minimal formatting by using tabs).
Alternatively, I might be able to shed some light on using the PrintDocument class with a header/footer if you want to go down that road.
0
 

Author Comment

by:ChrisMDrew
ID: 33745892
Thanks,  although currently my eport is pretty simple I do not want to limit future development by working with raw text.  I would like to stick with UltraPrintDocument if possible but the whole area seems very (overly) complex from what I have seen so far!.
0
 
LVL 33

Accepted Solution

by:
Todd Gerbert earned 500 total points
ID: 33745935
Like I said, tedious pain in the neck - hence the raw text suggestion. ;)
Another option would be to take advantage of a report tool, like CrystalReports if you're using Pro edition of VS, which may be better suited to the task at hand.
 
0
 

Author Closing Comment

by:ChrisMDrew
ID: 33758091
Thanks - it seems as though there is no easy way to do this other than by frigging the print area to avoid the hearer and footer - which I have done and it works so for now that will do !
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question