C#.NET Printing Text

Posted on 2010-09-23
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.
Question by:ChrisMDrew
  • 4
  • 2

Author Comment

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

Expert Comment

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... (

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.



   // The Click event is raised when the user clicks the Print button.

   private void printButton_Click(object sender, EventArgs e) 




          streamToPrint = new StreamReader

             ("C:\\My Documents\\MyFile.txt");



             printFont = new Font("Arial", 10);

             PrintDocument pd = new PrintDocument();

             pd.PrintPage += new PrintPageEventHandler









      catch(Exception ex) 





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


      // Print each line of the file.

      while(count < linesPerPage && 

         ((line=streamToPrint.ReadLine()) != null)) 


         yPos = topMargin + (count * 


         ev.Graphics.DrawString(line, printFont, Brushes.Black, 

            leftMargin, yPos, new StringFormat());



      // If more lines exist, print another page.

      if(line != null)

         ev.HasMorePages = true;


         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 = 


      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 is the main entry point for the application.

   public static void Main(string[] args) 


      Application.Run(new PrintingExample());



Open in new window


Author Comment

ID: 33744044

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?
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

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: (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.

Author Comment

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!.
LVL 33

Accepted Solution

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.

Author Closing Comment

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 !

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

863 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

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now