using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using Common;
using Config.Entities;
namespace SharedDatabase.Output.Printers
{
public class PrintersCommon : PrintDocument
{
static Font lastFont = null;
static float lastSpacing = 0;
///
/// Measure the size of a paragraph of text, lines are separated by '~'.
///
/// PrintPageEventArgs
/// Text, lines are separated by '~'
/// Font
/// Size of the paragraph of text
public static SizeF Measure(System.Drawing.Printing.PrintPageEventArgs e, string text, Font font)
{
if (font != lastFont)
{
lastFont = font;
lastSpacing = e.Graphics.MeasureString("Abcgq", font).Height;
}
string[] lines = text.Split(new char[] { '~' });
float width = 0;
foreach (var line in lines)
{
float lineWid = e.Graphics.MeasureString(line, font).Width;
if (lineWid > width) width = lineWid;
}
return new SizeF(width, 0.8f * lines.Length * lastSpacing + 0.2f);
}
///
/// Print a paragraph of text, lines are separated by '~'.
///
/// PrintPageEventArgs
/// Text, lines are separated by '~'
/// Font
/// Position x
/// Position y
/// Width (required when alignment=Alignment.Center or alignment=Aligmenr.Right
/// Height, 0 = no vertical centering
/// Horizontal alignment
/// Vertical alignment
public static void PrintAt(System.Drawing.Printing.PrintPageEventArgs e, string text, Font font,
float x, float y, float width, float height,
Alignment horizAlignment, VertAlignment vertAlignment)
{
SizeF size = PrintersCommon.Measure(e, text, font);
string[] lines = text.Split(new char[] { '~' });
if (height <= size.Height) vertAlignment = VertAlignment.Top;
float y0;
switch (vertAlignment)
{
default:
case VertAlignment.Top: y0 = y; break;
case VertAlignment.Middle: y0 = y + (height - size.Height) / 2; break;
case VertAlignment.Bottom: y0 = y + (height - size.Height); break;
}
foreach (var line in lines)
{
float x0;
switch (horizAlignment)
{
default:
case Alignment.Left: x0 = x; break;
case Alignment.Center: x0 = x + (width - e.Graphics.MeasureString(line, font).Width) / 2; break;
case Alignment.Right: x0 = x + width - e.Graphics.MeasureString(line, font).Width; break;
}
e.Graphics.DrawString(line, font, Brushes.Black, new PointF(x0, y0));
y0 += 0.8f * lastSpacing;
}
}
}
}