Automatically Word-wrap text on a print page?

I have code that prints a line, but if the line says β€œBlah blah blah” ... and there are no line breaks, the text takes up one line. I would like to be able to format the string so that it wraps paper sizes.

private void PrintIt(){ PrintDocument document = new PrintDocument(); document.PrintPage += (sender, e) => Document_PrintText(e, inputString); document.Print(); } static private void Document_PrintText(PrintPageEventArgs e, string inputString) { e.Graphics.DrawString(inputString, new Font("Courier New", 12), Brushes.Black, 0, 0); } 

I suppose I can determine the length of the character and wrap the text manually, but if there is a built-in way to do this, I would rather do it. Thanks!

+7
c # printing word-wrap
source share
3 answers

Yes, there is a DrawString that has the ability to automatically wrap text. You can use the MeasureString method to check whether the specified string can be completely drawn on the page or not and how much space is required.

There is also a TextRenderer Class specifically for this purpose.

Here is an example:

  Graphics gf = e.Graphics; SizeF sf = gf.MeasureString("shdadj asdhkj shad adas dash asdl asasdassa", new Font(new FontFamily("Arial"), 10F), 60); gf.DrawString("shdadj asdhkj shad adas dash asdl asasdassa", new Font(new FontFamily("Arial"), 10F), Brushes.Black, new RectangleF(new PointF(4.0F,4.0F),sf), StringFormat.GenericTypographic); 

Here I have specified a maximum of 60 pixels as a width, and then measures the line, which will give me the size that will be needed to draw this line. Now, if you already have the size, you can compare with the returned size to see if it will be drawn correctly or truncated

+11
source share

I found this: How: Print a multi-page text file in Windows Forms

 private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) { int charactersOnPage = 0; int linesPerPage = 0; // Sets the value of charactersOnPage to the number of characters // of stringToPrint that will fit within the bounds of the page. e.Graphics.MeasureString(stringToPrint, this.Font, e.MarginBounds.Size, StringFormat.GenericTypographic, out charactersOnPage, out linesPerPage); // Draws the string within the bounds of the page e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black, e.MarginBounds, StringFormat.GenericTypographic); // Remove the portion of the string that has been printed. stringToPrint = stringToPrint.Substring(charactersOnPage); // Check to see if more pages are to be printed. e.HasMorePages = (stringToPrint.Length > 0); } 
+11
source share

HTML printing dude is a complete nightmare. I would say that, in my opinion, you should try something else to print the text, etc. Pass parameters to report services and print a PDF file that the user can print.

Or perhaps you will need to count the number of characters and explicitly specify a line break!

-one
source share

All Articles