Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

C#.NET Printing Text

Posted on 2010-09-23
7
Medium Priority
?
1,355 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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
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 2000 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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

715 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