A Customizable Printing Text Class

CK CK 3788 
Created at
Updated at  
432 0 0

At least once,in the life of a programmer,it succeeds that the moment arrives to 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 interest

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

Collapse

private 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# Print GetLineBreakCharPosition Print PrintLineNumbers PrintTextDocument Substring WrapText Facebook X
Comments 0
Similar posts
  1. Simplified .NET Printing In C#
    692
  2. Print HTML In C# With Or Without The Web Browser Control And The Print Dialog
    972
  3. How To Print Text In C#
    455
  4. Adding Custom Paper Sizes To Named Printers
    646
  5. Printing A Page
    378
  6. Get A Print Dialog Box By Clicking A Button
    818
  7. How To Show The Print Dialog And Print Text Files
    1,295
  8. Two useful string functions - substr & substring
    406
  9. How to print external document ?
    414
  10. Changing the Title of a Print Dialog in Delphi
    1,093
  11. How To Check If Your Printer Is Connected Using C#
    1,026
  1. How to restrict a program to a single instance
    729
  2. Compress and decompress strings in C#
    971
  3. Graphics in C# - Irregular Forms
    908
  4. Extracting the Country from IP Address
    468
  5. How to run shell command by MFC ?
    435
  6. Binary Search Sample Code
    404
  7. Double Linked List based in C++
    796
  8. String Replace Function For C#
    1,547
  9. How to print character in C# by ASCII code
    476
  10. MFC based World Wide Web HTTP Server Source Code
    459
  11. Creating and Using a CAsyncSocket Object to use CAsyncSocket
    472
  12. UDP Send and Receive Using CAsyncSocket
    1,204
  13. Using the shell to receive notification of removable media being inserted or removed
    680
  14. Adding Custom Paper Sizes To Named Printers
    646
  15. Print HTML In C# With Or Without The Web Browser Control And The Print Dialog
    972
  16. Simplified .NET Printing In C#
    692
  17. How To Print Text In C#
    455
  18. C# Lists
    1,151
  19. Simple Example of IF/THEN using C#
    1,265
  20. Fast and Good Keyboard/Mouse Test without the message handler
    982
  21. Simple CGI Programming in C
    544
  22. C++ CGI Example working on Apache
    483
  23. Simple C# CGI working on Apache
    480
  24. How to send binary data through C# CGI app?
    994
  25. Interacting With TinyPic From C#
    1,303
  26. Creating A Watched Folder With Assigned Events
    1,658
  27. Calling Your Main Thread From A Worker Thread In C#
    546
  28. HashTable Tutorial In C#
    1,787
  29. Stack Tutorial In C#
    668
  30. Queue Tutorial In C#
    1,737
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    39
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,611
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    244
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    243
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    582
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    258
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    216
  30. Understanding Data Lineage
    260