Created
February 20, 2015 07:35
-
-
Save GeirGrusom/38861d595959ee270f57 to your computer and use it in GitHub Desktop.
Printer Text Writer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Drawing; | |
using System.Drawing.Printing; | |
using System.IO; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Printing | |
{ | |
public class PrinterWriter : TextWriter | |
{ | |
private readonly PrintDocument _document; | |
private readonly Font _font; | |
private int _currentIndex; | |
private int _linesPerPage; | |
private readonly StringBuilder _text; | |
private string _contents; | |
public PrinterWriter() | |
: this(new Font("Consolas", 10), "Untitled") | |
{ | |
} | |
public PrinterWriter(Font font, string documentName, PrinterSettings settings) | |
{ | |
_text = new StringBuilder(); | |
_font = font; | |
_document = new PrintDocument(); | |
_document.PrintPage += DocumentOnPrintPage; | |
_document.DocumentName = documentName; | |
_document.PrinterSettings = settings; | |
} | |
public PrinterWriter(Font font, string documentName) | |
{ | |
_text = new StringBuilder(); | |
_font = font; | |
_document = new PrintDocument(); | |
_document.DocumentName = documentName; | |
_document.PrintPage += DocumentOnPrintPage; | |
} | |
private void DocumentOnPrintPage(object sender, PrintPageEventArgs e) | |
{ | |
_linesPerPage = e.PageBounds.Height / _font.Height; | |
int nextPage = GetNextPageIndex(_contents, _linesPerPage); | |
e.Graphics.DrawString(_contents.Substring(_currentIndex, nextPage - _currentIndex), _font, Brushes.Black, e.MarginBounds, new StringFormat(StringFormatFlags.NoWrap)); | |
e.HasMorePages = nextPage != _contents.Length; | |
_currentIndex = nextPage; | |
} | |
private int GetNextPageIndex(string contents, int linesPerPage) | |
{ | |
int count = linesPerPage; | |
for (int i = _currentIndex; i < _contents.Length; i++) | |
{ | |
if (contents[i] == '\r') | |
{ | |
--count; | |
if (count == 0) | |
return i; | |
} | |
} | |
return _contents.Length; | |
} | |
protected override void Dispose(bool disposing) | |
{ | |
base.Dispose(disposing); | |
Close(); | |
} | |
public override void Close() | |
{ | |
_contents = _text.ToString(); | |
_document.Print(); | |
} | |
public override Encoding Encoding | |
{ | |
get { return Encoding.Unicode; } | |
} | |
public override void Write(char value) | |
{ | |
_text.Append(value); | |
} | |
public override async Task WriteAsync(char value) | |
{ | |
await Task.Factory.StartNew(() => _text.Append(value)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment