A Customizable Printing Text Class | |||
| |||
print a text document. The task is quite simple for a .NET programmer,but even more with PrintTextDocument class. This class was written to help in printing text documents,adding customizable header and footer and line numbers to the printed text. The text can be printed wrapping the exceeding text to the next line,truncating it,or spanning it through many pages. The last mode is useful when printing text banners like the ones coming from ASCII Art or from text tables with many columns. PrintTextDocumen is derived from System.Drawing.Printing.PrintDocument and provides some extra properties that set the class behavior during printing. // // Simple use of PrintTextDocument class // // assume filename a string that contains the full path of // an ASCII file. // PrintTextDocument toPrint = new PrintTextDocument(filename); toPrint.PrintMode = PrintTextMode.WrapText; toPrint.PrintLineNumbers = true; toPrint.Print(); Points of interestWhen I wrote the code,the first version was quite simple. The OnPrintPage override was made of a loop that scanned through the text file and called the MeasureString and DrawText methods. After some trials,I noticed that there was a bug in the text wrapping. It was as if MeasureString did not take care of the spaces at the end of the line. This was because of the way I wrote the GetLineBreakCharPosition function. This function checks the result of MeasureString and makes the adjustment according to the number of spaces that came at the end of the measured text. I don’t know if this is a bug of MeasureString. I did not find any useful information regarding this strange behavior. I even tried to use StringFormat with the MeasureString method but it did not get better. I’d like to know if there is another way to do what GetLineBreakCharPosition does.Collapseprivate int GetLineBreakCharPosition(Graphics gfx,string text,RectangleF rectangle) { StringFormat fmt = new StringFormat(StringFormatFlags.MeasureTrailingSpaces); int charactersOnLine = 0; int lines = 0; // Sets the value of charactersOnPage to the number of characters // of stringToPrint that will fit within the bounds of the rectangle. SizeF sizeText = gfx.MeasureString(text,_printFont,rectangle.Size,fmt,out charactersOnLine,out lines); string rem = text.Substring(0,charactersOnLine); // Fix MeasureString issue with trailing spaces if(rem.EndsWith(" ") Tags: C# C# Print GetLineBreakCharPosition Print PrintLineNumbers PrintTextDocument Substring WrapText | |||
| |||
| |||
Login for comment |