tbf/Results/Output/Printers/Enhanced/EnhancedPrintDocument.cs

393 lines
15 KiB
C#

///
/// Copyright (c) 2017-2020 Sensus Metering Systems
///
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.IO;
using Common;
using GenCode128;
using Gma.QrCodeNet.Encoding;
using Results.Resources;
namespace Results.Output.Printers.Enhanced
{
public class EnhancedPrintDocument : PrintDocument
{
static QrEncoder encoder = new QrEncoder();
/// Size of the printed area without margins, after taking into account 'pageOrientation'
readonly int printHeight;
readonly int printWidth;
readonly int topMargin;
readonly int bottomMargin;
readonly int leftMargin;
readonly int TitleX;
readonly int TitleY; /// Depends on the size of the header
readonly int spacingOne;
readonly int spacingOneAndHalf;
readonly int spacingOne4Header;
readonly int spacingOneAndHalf4Header;
readonly int spacingOne4Footer;
int spacingAboveTable;
int spacingBelowTable;
int CommonTop; /// = TitleY + 60
int BodyTop; /// = HdrTop + 160
///
int titleHeight;
int commonHeight;
/// <summary>
/// Property variable for the Font the user wishes to use
/// </summary>
Font titleFont;
Font headerFont;
Font font;
Font footerFont;
TableStyle style;
///
/// Data to print
///
Results.Entities.Batch batch;
EnhancedPrinterCfg cfg;
///
/// Items to print
///
string header;
IList<WMeterRsltItemSpec> commonItems;
IList<WMeterRsltItemSpec> testItems;
string footer;
///
/// Layout and status
///
int nrWMsOnFirstPage;
int nrWMsOnNextPage;
int nextWMNr; /// nr. of watermeter to be printed as the first one on the next page
int nrPages;
int pageNr; /// Page number to be printed at the bottom of the page
/// <summary>
/// Constructor
/// </summary>
/// <param name="textToPrint">Text to be printed</param>
public EnhancedPrintDocument(Results.Entities.Batch batch, EnhancedPrinterCfg cfg, string documentName)
{
this.batch = batch;
this.cfg = cfg;
DocumentName = documentName;
topMargin = cfg.TopMargin;
bottomMargin = cfg.BottomMargin;
leftMargin = cfg.LeftMargin;
header = string.IsNullOrEmpty(cfg.Header) ? string.Empty : cfg.Header.Replace("~", Environment.NewLine);
commonItems = Results.WMeterRsltItemSpec.FromStrArray(cfg.CommonItems);
testItems = Results.WMeterRsltItemSpec.FromStrArray(cfg.TestItems); /// TestID info will be overwritten later on
footer = string.IsNullOrEmpty(cfg.Footer) ? string.Empty : cfg.Footer.Replace("~", Environment.NewLine);
/// Initialize fonts
titleFont = new Font((cfg.TitFntFml != null ? cfg.TitFntFml : "Arial"), (cfg.TitFntSz > 0 ? cfg.TitFntSz : 10), (FontStyle)cfg.TitFntSty);
headerFont = new Font((cfg.HdrFntFml != null ? cfg.HdrFntFml : "Arial"), (cfg.HdrFntSz > 0 ? cfg.HdrFntSz : 10), (FontStyle)cfg.HdrFntSty);
font = new Font((cfg.BodyFntFml != null ? cfg.BodyFntFml : "Arial"), (cfg.BodyFntSz > 0 ? cfg.BodyFntSz : 10), (FontStyle)cfg.BodyFntSty);
footerFont = new Font((cfg.FooterFntFml != null ? cfg.FooterFntFml : "Arial"), (cfg.FooterFntSz > 0 ? cfg.FooterFntSz : 10), (FontStyle)cfg.FooterFntSty);
/// Table style of one water meter table where tests are rows
style = new TableStyle
{
Font = font,
HeaderFont = headerFont,
MarginX = 5,
MarginY = 3,
LineWidth = 1,
TopHeadersCount = 1,
HorizLines = TableLines.FirstSecondAndLast,
VertLines = TableLines.All
};
/// Set print area size and margins (in dots using 100 dpi)
DefaultPageSettings.Landscape = (cfg.PageOrientation == PageOrientation.Landscape);
///
if (DefaultPageSettings.Landscape)
{
printHeight = base.DefaultPageSettings.PaperSize.Width - topMargin - bottomMargin;
printWidth = base.DefaultPageSettings.PaperSize.Height - leftMargin - leftMargin;
}
else
{
printHeight = base.DefaultPageSettings.PaperSize.Height - topMargin - bottomMargin;
printWidth = base.DefaultPageSettings.PaperSize.Width - leftMargin - leftMargin;
}
/// Document outline preliminary calculations
spacingOne = System.Windows.Forms.TextRenderer.MeasureText("Abcgq", font).Height;
spacingOneAndHalf = (3 * spacingOne) / 2;
spacingOne4Header = System.Windows.Forms.TextRenderer.MeasureText("Abcgq", headerFont).Height;
spacingOneAndHalf4Header = (3 * spacingOne4Header) / 2;
spacingOne4Footer = System.Windows.Forms.TextRenderer.MeasureText("Abcgq", footerFont).Height;
TitleX = cfg.LeftMargin;
TitleY = cfg.TopMargin;
pageNr = 1;
nextWMNr = 0;
}
/// <summary>
/// Override the default onbeginPrint method of the PrintDocument Object
/// </summary>
/// <param name=e></param>
/// <remarks></remarks>
protected override void OnBeginPrint(System.Drawing.Printing.PrintEventArgs e)
{
base.OnBeginPrint(e);
}
/// <summary>
/// Override the default OnPrintPage method of the PrintDocument.
/// </summary>
/// <param name=e></param>
/// <remarks>This provides the print logic for our document</remarks>
protected override void OnPrintPage(System.Drawing.Printing.PrintPageEventArgs e)
{
/// Run base code
base.OnPrintPage(e);
if (!string.IsNullOrEmpty(cfg.Template))
{
string templatePath = Path.Combine("C:\\TBF\\Templates\\", cfg.Template);
if (File.Exists(templatePath))
{
if (cfg.PageOrientation == PageOrientation.Portrait)
e.Graphics.DrawImage(new Bitmap(Image.FromFile(templatePath), 827, 1169), new Rectangle(0, 0, 827, 1169));
else
e.Graphics.DrawImage(new Bitmap(Image.FromFile(templatePath), 1169, 827), new Rectangle(0, 0, 1169, 827));
}
}
/// Use the StringFormat class for the text layout of our document
StringFormat format = new StringFormat(StringFormatFlags.LineLimit);
if (pageNr == 1)
{
///----------
/// Prepare document outline
///----------
titleHeight = System.Windows.Forms.TextRenderer.MeasureText(header, titleFont).Height;
CommonTop = TitleY + titleHeight + spacingOne4Header;
commonHeight = commonItems.Count * spacingOne;
BodyTop = CommonTop + commonHeight + spacingOne4Header;
Table table0 = Table.Create_TestsAreRows(batch.WaterMeters[0], testItems, style);
SizeF tableSize = table0.Measure(e);
if (cfg.BarcodeType == BarcodeType.None)
{
spacingAboveTable = spacingOneAndHalf4Header;
}
else
{
spacingAboveTable = Math.Max(spacingOneAndHalf4Header, cfg.BarcodeHeight + spacingOne4Header / 2);
}
spacingBelowTable = (tableSize.Height > 0) ? spacingOneAndHalf4Header : (spacingOne4Header / 2);
int wmSectionHeight = (int)tableSize.Height + spacingAboveTable + spacingBelowTable;
nrWMsOnFirstPage = (printHeight - BodyTop + TitleY - 2 * spacingOne) / wmSectionHeight;
nrWMsOnNextPage = (printHeight - 2 * spacingOne) / wmSectionHeight;
nrWMsOnNextPage = Math.Max(nrWMsOnNextPage, 1); /// Prevent division by zero if there are too many WM tests
nrPages = 1 + (batch.WaterMeters.Count - nrWMsOnFirstPage + nrWMsOnNextPage - 1) / nrWMsOnNextPage;
///----------
/// Title
///----------
RectangleF printArea = new RectangleF(TitleX, TitleY, printWidth, titleHeight);
e.Graphics.DrawString(header, titleFont, Brushes.Black, printArea);
///----------------
/// Common items
///----------------
string[] leftColumn = new string[commonItems.Count];
string[] rightColumn = new string[commonItems.Count];
int cnt = 0;
foreach (var v in commonItems)
{
leftColumn[cnt] = v.Caption;
rightColumn[cnt] = (batch.WaterMeters.Count > 0) ? v.Print(batch.WaterMeters[0]) : string.Empty;
cnt++;
}
/// Determine max. left column width in characters
int maxLen = 0;
foreach (var s in leftColumn) if (s.Length > maxLen) maxLen = s.Length;
/// Write aligned columns
for (int i = 0; i < Math.Min(leftColumn.Length, rightColumn.Length); i++)
{
PrintAt(e, leftMargin, CommonTop + spacingOne * i, leftColumn[i]);
PrintAt(e, 300, CommonTop + spacingOne * i, rightColumn[i]);
}
}
///--------
/// Body
///--------
/// This variable represents the top coordinate of the area where WM results are printed
/// and it is updated (increased by) the value returned by PrintXyzWM() - the section size.
int nextWmTop = (pageNr == 1) ? BodyTop : TitleY;
int nrWMsOnPage = (pageNr == 1) ? nrWMsOnFirstPage : nrWMsOnNextPage;
for (int wmNr = nextWMNr; wmNr < Math.Min(nextWMNr + nrWMsOnPage, batch.WaterMeters.Count); wmNr++) /// wmNr is 0-based
{
int wmPosition = true ? batch.WaterMeters[wmNr].WMPosition : (wmNr + 1);
if (!cfg.GoodOnly || batch.WaterMeters[wmNr].Passed)
{
nextWmTop = (int)PrintWM(e, batch.WaterMeters[wmNr], wmPosition, nextWmTop) + spacingBelowTable;
}
}
nextWMNr += nrWMsOnPage;
e.HasMorePages = (nextWMNr < batch.WaterMeters.Count);
///----------
/// Footer
///----------
int footerWidth = (int)e.Graphics.MeasureString(footer, footerFont).Width;
PrintFooterAt(e, leftMargin + (printWidth - footerWidth) / 2, topMargin + printHeight - 2 * spacingOne, footer);
string pageNrText = string.Format("{0} {1}/{2}", Strings.Page, pageNr++, nrPages);
int pageNrWidth = (int)e.Graphics.MeasureString(pageNrText, font).Width;
PrintAt(e, leftMargin + (printWidth - pageNrWidth) / 2, topMargin + printHeight - spacingOne, pageNrText);
}
/// <summary>
/// Print one water meter results
/// </summary>
/// <param name="wm">Water meter</param>
/// <param name="printedWMNr">Number of the water meter printed</param>
/// <param name="top">Top coordinate of watermeter data</param>
/// <returns>The height of the printed section</returns>
float PrintWM(System.Drawing.Printing.PrintPageEventArgs e,
Results.Entities.WaterMeter wm, int printedWMNr, int top)
{
int tableTop = top + spacingAboveTable;
/// Print the water meter number and the serial number
if (string.IsNullOrEmpty(wm.SerialNr))
{
string wmText = string.Format("{0} {1}", Strings.Water_Meter, printedWMNr);
int wmTextWidth = (int)e.Graphics.MeasureString(wmText, headerFont).Width;
PrintHeaderAt(e, leftMargin, tableTop - spacingOneAndHalf4Header, wmText);
}
else
{
string wmText = string.Format("{0} {1} {2} = {3}", Strings.Water_Meter, printedWMNr, Strings.sn, wm.SerialNr);
int wmTextWidth = (int)e.Graphics.MeasureString(wmText, headerFont).Width;
PrintHeaderAt(e, leftMargin, tableTop - spacingOneAndHalf4Header, wmText);
switch (cfg.BarcodeType)
{
case BarcodeType.Code_128_Horizontally:
{
Image img = Code128Rendering.MakeBarcodeImage(wm.SerialNr, 1, true);
e.Graphics.DrawImage(img, leftMargin + wmTextWidth + spacingOne4Header, top, cfg.BarcodeWidth, cfg.BarcodeHeight);
break;
}
case BarcodeType.Code_128_Vertically:
{
Image img = Code128Rendering.MakeBarcodeImage(wm.SerialNr, 1, true);
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
e.Graphics.DrawImage(img, leftMargin + wmTextWidth + spacingOne4Header, top, cfg.BarcodeWidth, cfg.BarcodeHeight);
break;
}
case BarcodeType.QR_Code:
{
QrCode qrCode = encoder.Encode(wm.SerialNr);
DrawQR(e.Graphics, qrCode, leftMargin + wmTextWidth + spacingOne4Header, top, cfg.BarcodeWidth, cfg.BarcodeHeight);
break;
}
}
}
Table table = Table.Create_TestsAreRows(wm, testItems, style);
return table.IsEmpty() ? tableTop : table.Draw(e, leftMargin, tableTop);
}
void PrintAt(System.Drawing.Printing.PrintPageEventArgs e, Point p, string text)
{
PrintAt(e, p.X, p.Y, text);
}
void PrintAt(System.Drawing.Printing.PrintPageEventArgs e, int x, int y, string text)
{
RectangleF printArea = new RectangleF(x, y, 2000, spacingOne);
e.Graphics.DrawString(text, this.font, Brushes.Black, printArea);
}
void PrintHeaderAt(System.Drawing.Printing.PrintPageEventArgs e, Point p, string text)
{
PrintHeaderAt(e, p.X, p.Y, text);
}
void PrintHeaderAt(System.Drawing.Printing.PrintPageEventArgs e, int x, int y, string text)
{
RectangleF printArea = new RectangleF(x, y, 2000, spacingOne4Header);
e.Graphics.DrawString(text, this.headerFont, Brushes.Black, printArea);
}
void PrintFooterAt(System.Drawing.Printing.PrintPageEventArgs e, Point p, string text)
{
PrintFooterAt(e, p.X, p.Y, text);
}
void PrintFooterAt(System.Drawing.Printing.PrintPageEventArgs e, int x, int y, string text)
{
RectangleF printArea = new RectangleF(x, y, 2000, spacingOne4Footer);
e.Graphics.DrawString(text, this.footerFont, Brushes.Black, printArea);
}
public static void DrawQR(Graphics g, QrCode qrCode, float left, float top, float width, float height)
{
/// Assuming 100 dpi (printer)
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
float qrPixWidth = width / qrCode.Matrix.Width;
float qrPixHeight = height / qrCode.Matrix.Height;
for (int i = 0; i < qrCode.Matrix.Height; i++)
{
for (int j = 0; j < qrCode.Matrix.Width; j++)
{
if (qrCode.Matrix[j, i])
{
g.FillRectangle(Brushes.Black, new RectangleF(left + j * qrPixWidth,
top + i * qrPixHeight,
qrPixWidth,
qrPixHeight));
}
}
}
}
}
}