using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
namespace WindowsApplication6
{
class CustomDocument:PrintDocument
{
private Font _printFont;
private string _fileToPrint;
private Single _headerHeight;
private TextReader _printStream;
public string FieldToPrint
{
get
{
return _fileToPrint;
}
set
{
if (File.Exists(value))
{
_fileToPrint = value;
}
else
throw (new Exception("File not found."));
}
}
public Font PrintFont
{
get
{
return _printFont;
}
set
{
_printFont=value;
}
}
public Single HeaderHeight
{
get
{
return _headerHeight;
}
set
{
_headerHeight = value;
}
}
protected virtual Single printPageHeader(RectangleF bounds,
PrintPageEventArgs e)
{
Graphics g = e.Graphics;
Font drawFont = new Font("Arial", 16, FontStyle.Bold);
string headerText = this.DocumentName;
RectangleF headerTextLayout = new RectangleF(bounds.X, bounds.Y, bounds.Width , bounds.Height);
Single localHeaderHeight;
StringFormat headerStringFormat = new StringFormat();
headerStringFormat.Alignment = StringAlignment.Center;
localHeaderHeight = g.MeasureString(headerText, drawFont, headerTextLayout.Size,headerStringFormat).Height;
g.DrawString(headerText, drawFont, Brushes.Black, headerTextLayout, headerStringFormat);
return localHeaderHeight;
}
protected override void OnBeginPrint(PrintEventArgs e)
{
base.OnBeginPrint(e);
_printStream = new StreamReader(FieldToPrint);
}
protected override void OnEndPrint(PrintEventArgs e)
{
base.OnEndPrint(e);
_printStream.Close();
}
protected override void OnPrintPage(PrintPageEventArgs e)
{
base.OnPrintPage(e);
Graphics gdipage=e.Graphics ;
Single leftMargin = e.MarginBounds.Left;
Single topMargin = e.MarginBounds.Top;
Single width = e.MarginBounds.Width;
Single height = e.MarginBounds.Height;
Single lineHeight = _printFont.GetHeight(gdipage);
Single linePerpage = e.MarginBounds.Height;
int lineCount = 0;
string lineText = null;
Single headerSize;
Single currentPosition = topMargin;
RectangleF headerBounds = new RectangleF(leftMargin, topMargin, width ,height);
headerBounds.Height = this.HeaderHeight;
headerSize = printPageHeader(headerBounds, e);
currentPosition += (headerSize + 20);
while (lineCount < linePerpage && ((lineText = _printStream.ReadLine()) != null))
{
gdipage.DrawString(lineText, _printFont, Brushes.Black, leftMargin, (currentPosition + (lineCount++ * lineHeight)));
}
if (lineText != null)
e.HasMorePages = true;
else
e.HasMorePages=false;
}
}
}