Solved

C#.NET Printing Text

Posted on 2010-09-23
7
1,293 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
  • 4
  • 2
7 Comments
 

Author Comment

by:ChrisMDrew
Comment Utility
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
Comment Utility
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
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 33

Expert Comment

by:Todd Gerbert
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

743 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

22 Experts available now in Live!

Get 1:1 Help Now