Files
SourceCode/PROMS/Volian.Print.Library/CompleteRORpt.cs
T

1069 lines
34 KiB
C#

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text;
using VEPROMS.CSLA.Library;
using Volian.Base.Library;
using VlnStatus;
namespace Volian.Print.Library
{
class CompleteROReport
{
private static readonly log4net.ILog _MyLog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
readonly Headers Hdrs; // Header stack object.
RODataFile RO_df = null;
int curheaderlen;
readonly string RODataFileName;
readonly iTextSharp.text.Document _pdfReportDoc;
PdfPTable datatable = null;
public iTextSharp.text.Font F14 { get; set; }
public iTextSharp.text.Font F10 { get; set; }
public iTextSharp.text.Font F12 { get; set; }
public iTextSharp.text.Font F10Bold { get; set; }
public iTextSharp.text.Font F12Bold { get; set; }
public bool ConvertCaretToDelta { get; set; } = true;
public bool IncludeEmptyROFields { get; set; } = false;
public int ROFstID { get; set; }
private readonly string ReportTitle = "Complete Referenced Objects Report";
private readonly PdfWriter _MyPDFWriter;
public CompleteROReport(PdfWriter mypdfwriter, iTextSharp.text.Document document, string dataFileName, bool convertCaretToDelta, bool includeEmptyROFields)
{
Hdrs = new Headers();
_pdfReportDoc = document;
RODataFileName = dataFileName;
ConvertCaretToDelta = convertCaretToDelta;
_MyPDFWriter = mypdfwriter;
IncludeEmptyROFields = includeEmptyROFields;
}
public void StartNewDataTable()
{
datatable = new PdfPTable(1)
{
TotalWidth = _pdfReportDoc.PageSize.Width - _pdfReportDoc.LeftMargin - _pdfReportDoc.RightMargin,
LockedWidth = true
};
PdfPCell cell = new PdfPCell(new Phrase(ReportTitle, F14))
{
HorizontalAlignment = Element.ALIGN_CENTER,
BackgroundColor = Color.WHITE,
BorderColor = Color.WHITE
};
datatable.AddCell(cell);
datatable.HeaderRows = 3;
datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
}
public void Run()
{
StartNewDataTable();
RO_df = new RODataFile(RODataFileName);
PrintReport();
RO_df.close();
}
internal Dictionary<int, DocOutline> MyDocOutline { get; set; } = new Dictionary<int, DocOutline>();
public class DocOutline
{
public PdfOutline MyOutline { get; set; }
public string MyHeader { get; set; }
public DocOutline(PdfOutline outline, string header)
{
MyHeader = header;
MyOutline = outline;
}
}
private string ReplaceLineDrawCharsWithUnicode(string text)
{
text = text.Replace("\xc4", "\x2500"); // Horizontal
text = text.Replace("\xb3", "\x2502"); // Vertical
text = text.Replace("\xc0", "\x2514"); // Bottom Left Corner
text = text.Replace("\xd9", "\x2518"); // Bottom Right Corner
text = text.Replace("\xc1", "\x2534"); // Bottom Tee
text = text.Replace("\xda", "\x250c"); // Upper Left Corner
text = text.Replace("\xc3", "\x251c"); // Left Tee
text = text.Replace("\xbf", "\x2510"); // Upper Right Corner
text = text.Replace("\xc2", "\x252c"); // Top Tee
text = text.Replace("\xb4", "\x2524"); // Right Tee
text = text.Replace("\xc5", "\x253c"); // Plus
return text;
}
public Phrase ConvertDOSSuperAndSubScripts(string instr, Font fnt)
{
int idx = 0;
Chunk chk;
Phrase p = new Phrase();
bool underlineChunk = false;
instr = instr.Replace("`", "\u00B0"); //degree
instr = instr.Replace("[RHO]", "\u03C1"); // C2016-018 rho symbol - is being read in as a line draw character, so users need to put "[RHO]" in their text for the rho symbol to print
if (ConvertCaretToDelta)
{
instr = instr.Replace("^", "\u0394"); // delta
}
//instr = instr.Replace("\x94", "\u0394"); // delta - the delta symbol is being read in as character x94
instr = ReplaceLineDrawCharsWithUnicode(instr);
// Handle super/sub scripts
MatchCollection mc = Regex.Matches(instr, "[#~](.*?)[#~]");
foreach (Match m in mc)
{
if (idx < m.Index)
{
int strlen = m.Index - idx;
int uidx = 0;
string strChk = instr.Substring(idx, strlen);
MatchCollection mc1 = Regex.Matches(strChk, "[_](.*?)"); // look ofr Underline on/off
foreach (Match m1 in mc1)
{
if (uidx < m1.Index)
{
string tstr = (instr.Substring(idx+uidx, m1.Index - uidx));
if (tstr.EndsWith(" "))
tstr = $"{tstr.Substring(0, tstr.Length - 1)}\xA0";
chk = new Chunk(tstr, fnt);
if (underlineChunk)
chk.SetUnderline(Color.BLACK, 0, 0.05F, 0, -.131F, PdfContentByte.LINE_CAP_ROUND);
chk.SetTextRise(0);
p.Add(chk);
uidx += (tstr.Length + 1);
idx += (tstr.Length + 1);
strlen -= (tstr.Length + 1);
underlineChunk = !underlineChunk;
}
else if (uidx == m1.Index)
{
uidx++;
underlineChunk = !underlineChunk;
}
}
chk = new Chunk(instr.Substring(idx, strlen), fnt);
if (underlineChunk)
chk.SetUnderline(Color.BLACK, 0, 0.05F, 0, -.131F, PdfContentByte.LINE_CAP_ROUND);
chk.SetTextRise(0);
p.Add(chk);
}
switch (m.Value[0])
{
case '#':
chk = new Chunk(m.Value.Substring(1, m.Length-2), fnt);
if (underlineChunk)
chk.SetUnderline(Color.BLACK, 0, 0.05F, 0, -.131F, PdfContentByte.LINE_CAP_ROUND);
chk.SetTextRise(.25F * chk.Font.Size);
p.Add(chk);
idx = m.Index + m.Length;
break;
case '~':
chk = new Chunk(m.Value.Substring(1, m.Length-2), fnt);
if (underlineChunk)
chk.SetUnderline(Color.BLACK, 0, 0.05F, 0, -.131F, PdfContentByte.LINE_CAP_ROUND);
chk.SetTextRise(-.25F * chk.Font.Size);
p.Add(chk);
idx = m.Index + m.Length;
break;
}
}
if (idx <= instr.Length - 1)
{
int uidx = 0;
string strChk = (instr.Substring(idx));
if (!_LastWasName) //B2016-251 Don't change underscore to underline to Name value
{
MatchCollection mc1 = Regex.Matches(strChk, "[_](.*?)"); // look for underline on/off
foreach (Match m1 in mc1)
{
if (uidx < m1.Index)
{
string tstr = (strChk.Substring(uidx, m1.Index - uidx));
if (tstr.EndsWith(" "))
tstr = $"{tstr.Substring(0, tstr.Length - 1)}\xA0";
chk = new Chunk(tstr, fnt);
if (underlineChunk)
chk.SetUnderline(Color.BLACK, 0, 0.05F, 0, -.131F, PdfContentByte.LINE_CAP_ROUND);
chk.SetTextRise(0);
p.Add(chk);
uidx += (tstr.Length + 1);
underlineChunk = !underlineChunk;
}
else if (uidx == m1.Index)
{
uidx++;
underlineChunk = !underlineChunk;
}
}
}
if (uidx <= strChk.Length - 1)
{
string tstr = strChk.Substring(uidx);
if (tstr.EndsWith(" "))
tstr = $"{tstr.Substring(0, tstr.Length - 1)}\xA0";
chk = new Chunk(tstr, fnt);
if (underlineChunk)
chk.SetUnderline(Color.BLACK, 0, 0.05F, 0, -.131F, PdfContentByte.LINE_CAP_ROUND);
chk.SetTextRise(0);
p.Add(chk);
}
}
return p;
}
public void AddText(string txt, Font fnt) => AddText(txt, fnt, Color.BLACK);
public void AddText(string txt, Font fnt, Color txtcolor)
{
// break the text up on double returns (paragraphs) and put each in their own cell
// this will allow for page breaks between paragraphs0
string[] delim = { "\r\n\r\n","\r\n \r\n" };
string[] strlst = txt.Split(delim,StringSplitOptions.None);
foreach (string str in strlst)
{
Font f = new Font(fnt)
{
Color = txtcolor
};
PdfPCell cell = new PdfPCell(ConvertDOSSuperAndSubScripts(str, f))
{
BorderColor = Color.WHITE
};
if (strlst.Length > 1)
cell.PaddingBottom = 6;
datatable.AddCell(cell);
}
}
public void AddImage(string filename)
{
ROImageInfo roImage = ROImageInfo.GetByROFstID_FileName(ROFstID, filename) ?? ROFstInfo.Get(ROFstID).GetROImageByFilename(filename, null);
PdfPCell spaceCell = new PdfPCell
{
BorderColor = Color.WHITE
};
datatable.AddCell(spaceCell);
if (roImage != null)
{
ROImageConfig rc = new ROImageConfig(roImage);
int size = Convert.ToInt32(rc.Image_Size);
byte[] cnt = roImage.Content;
byte[] dcnt = ROImageInfo.Decompress(cnt, size);
iTextSharp.text.Image it_image;
try
{
it_image = iTextSharp.text.Image.GetInstance(dcnt);
//iTextSharp.text.Image it_image = iTextSharp.text.Image.GetInstance(ROImageInfo.Decompress(roImage.Content, size));
}
catch (Exception)
{
try
{
MemoryStream ms = new MemoryStream(dcnt);
System.Drawing.Bitmap bm = new System.Drawing.Bitmap(ms);
using (MemoryStream ms2 = new MemoryStream())
{
bm.Save(ms2, System.Drawing.Imaging.ImageFormat.Png);
ms2.Seek(0, SeekOrigin.Begin);
byte[] newdcnt = new byte[ms2.Length];
ms2.Read(newdcnt, 0, (int)ms2.Length);
it_image = iTextSharp.text.Image.GetInstance(newdcnt);
}
}
catch (Exception ex2)
{
AddText(string.Format("Bad Image File: {0}", filename), F12, Color.RED);
GenerateErrorMessage(ex2, "Bad Image File. ", string.Format("Image File: {0}", filename));
roImage.Dispose();
return;
}
}
it_image.ScaleToFit(_MyPDFWriter.DirectContent.PdfDocument.PageSize.Width - 144, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height - 216);
PdfPCell cell = new PdfPCell(it_image)
{
BorderColor = Color.WHITE
};
datatable.AddCell(cell);
roImage.Dispose();
}
else
{
AddText(string.Format("Image File {0} is missing.", filename), F12, Color.RED);
GenerateErrorMessage(null, "Image File Missing. ", string.Format("Image File: {0}", filename));
Application.DoEvents();
}
}
public void AddXYPlot(string plotlang)
{
string pngFile = VlnSettings.TemporaryFolder + @"\XYPlot1.png";
string rawPlotLang = plotlang;
plotlang = plotlang.Replace("`", "\xB0"); //degree
plotlang = plotlang.Replace("\xF8", "\xB0"); //degree
if (ConvertCaretToDelta)
plotlang = plotlang.Replace("^", "\x394"); // delta
plotlang = plotlang.Replace("\x7F", "\x394"); //delta
PdfPCell spaceCell = new PdfPCell
{
BorderColor = Color.WHITE
};
datatable.AddCell(spaceCell);
try
{
System.Drawing.RectangleF plotRect = MSWordToPDF.CreatePlot(pngFile, plotlang, 600F, MSWordToPDF.FormForPlotGraphics);
iTextSharp.text.Image it_image = iTextSharp.text.Image.GetInstance(pngFile);
it_image.ScaleToFit(_MyPDFWriter.DirectContent.PdfDocument.PageSize.Width - 144, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height - 216);
PdfPCell cell = new PdfPCell(it_image)
{
BorderColor = Color.WHITE
};
datatable.AddCell(cell);
}
catch (Exception e)
{
AddText("-- Error Processing X/Y Plot Language --",F12,Color.RED);
datatable.AddCell(spaceCell);
AddText(rawPlotLang, F10);
GenerateErrorMessage(null, "Error Processing X/Y Plot Lanuage. ", e.Message);
}
}
private string processingRO = "";
public string MyROID { get; set; } = null;
public void PrintReport()
{
bool StopPrinting = false;
VlnStatusBar showStatBar = new VlnStatusBar("Complete RO Report");
try
{
if (RO_df.GetFileLength() > 0)
{
showStatBar.BarMax = (int)RO_df.GetFileLength();
showStatBar.StatMsg = "Creating Report";
short iRecType;
// Loop until either printing is aborted or end of file.
while (!StopPrinting && (iRecType = RO_df.ReadInteger16()) != -1)
{
//Console.WriteLine("Record Type: {0}.{0:X}", iRecType);
switch (iRecType)
{
case 1: // Set Header
SetHeader();
break;
case 2: // Push Header
PushHeader();
break;
case 3: // Pop Header
PopHeader();
break;
case 4: // RRO Begin
RROBegin();
break;
case 5: // RRO End
RROEnd();
processingRO = "";
break;
case 6: // Msg
Msg();
break;
case 7:
processingRO = KeyField();
break;
case 8:
MyROID = ROIDField();
break;
case 100: // Text Field - sometimes also XY Plot
Text();
Application.DoEvents();
break;
case 101: // Plot Field
XYPlot();
Application.DoEvents();
break;
case 102: // Image Field
ImageFile();
Application.DoEvents();
break;
case 103: // Multi Begin - Display data for setpoints
Multiple();
break;
case 104: // Multi End
break;
case 0: // nothing was entered in that field
if (IncludeEmptyROFields)
NoInformatEntered();
break;
case 255:
_pdfReportDoc.Add(datatable);
_pdfReportDoc.NewPage();
StartNewDataTable();
showStatBar.BarValue = (int)RO_df.GetFilePointerPosition();
//Console.WriteLine("Record Type: {0} No Operation", iRecType);
//Console.WriteLine("----------------------------------------------");
break;
default: // Problem
StopPrinting = true;
MessageBox.Show(string.Format("Unrecognized record type [{0}]", iRecType), "Error Creating Complete RO Report", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
;
}
}
else
{
StartNewDataTable();
datatable.HeaderRows = 1;
AddText("Selected Referenced Object has no data.", F12);
}
//Console.WriteLine("Record Type: {0}\n** Done **", iRecType);
_pdfReportDoc.Add(datatable);
showStatBar.Dispose();
}
catch (Exception e)
{
Console.WriteLine("Exception : {0}", e.Message);
RO_df.close();
_pdfReportDoc.Add(datatable);
showStatBar.Dispose();
GenerateErrorMessage(e, "Error Processing Complete RO Report. ", null);
}
AddErrorBookmarks();
return;
}
private void GenerateErrorMessage( Exception e, string erMsg, string erMsg2)
{
// if there is lenght then we are in the mist of processing an RO
string headers = erMsg;
for (int iLoop = 0; iLoop < Hdrs.HdrCnt; iLoop++)
headers += $"{Hdrs.strHdrs[iLoop]}\n ";
if (processingRO.Length > 0)
headers += processingRO;
if (erMsg2 != null && erMsg2.Length > 0)
headers += "\n" + erMsg2;
if (e != null)
_MyLog.Error(headers, e);
else
_MyLog.Error(headers);
#pragma warning disable IDE0059 // Unnecessary assignment of a value - for debugging
PdfOutline outl = new PdfOutline(MyErrorOutline, MyPdfDestPage, processingRO.Length > 0 ? processingRO : "Problem Reading Header");
#pragma warning restore IDE0059 // Unnecessary assignment of a value
//DestSample(outl);
}
//For Debugging/Testing
//private void DestSample(PdfOutline outl)
//{
// new PdfOutline(outl, new PdfDestination(PdfDestination.FIT), "FIT");
// new PdfOutline(outl, new PdfDestination(PdfDestination.FITV, 700), "FITV,700");
// new PdfOutline(outl, new PdfDestination(PdfDestination.FITH, 700), "FITH,700");
// new PdfOutline(outl, new PdfDestination(PdfDestination.XYZ, 72, 720, 5), "XYZ,72,720,5");
// new PdfOutline(outl, new PdfDestination(PdfDestination.FITR, 72, 650, 144, 722), "FITR,72, 650, 144, 722");
// new PdfOutline(outl, new PdfDestination(PdfDestination.XYZ, 72, 720, 10), "XYZ,72,720,10");
// new PdfOutline(outl, new PdfDestination(PdfDestination.FITR, 0, 500, _pdfReportDoc.PageSize.Width, 720), "FITR,0, 500,_pdfReportDoc.PageSize.Width , 720");
// new PdfOutline(outl, new PdfDestination(PdfDestination.XYZ, 0, 792, 1), "XYZ,72,720,10");
//}
public void AddErrorBookmarks()
{
if (_MyErrorOutline == null) return;
string emsg = "A Bookmark grouping named \"Errors\" was added to the PDF.\n\n Click on the RO in this grouping to jump to the report page which will contain an error message.\n\nThe error were also recorded in the PROMS error log.";
MessageBox.Show(emsg, "Errors Found Creating Report", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public void Multiple()
{
short typ, i, j;
string str, sep;
string buff = "";
int[] width;
LastHeader();
sep = "";
// nw - number of fields
short nw = RO_df.ReadInteger16();
// allocate space for widths
width = new int[nw];
// loop through and load field widths and names
for (i = 0; i < nw; i++)
{
// load width
width[i] = RO_df.ReadInteger16();
// load name
str = RO_df.ReadText();
// how wide is the header
int wtxt = str.Length;
buff += sep;
buff += str;
// if the width is wider than the header output spaces to pad
// to specified width
if (width[i] > wtxt)
{
int extra = width[i] - wtxt;
while (extra > 0)
{
buff += " ";
extra--;
}
// otherwise set the width to the width of the header
}
else
{
width[i] = wtxt;
}
// place a vertical bar between fields
sep = "|";
}
sep = "\n";
buff += "\n";
// place horizonal bars between the header and the values
for (i = 0; i < nw; i++)
{
for (j = 0; j < width[i]; j++)
{
buff += "-";
}
if (i < nw - 1)
buff += "|";
}
i = 0;
// While not the end of multi
while ((typ = RO_df.ReadInteger16()) != 104)
{
if (typ == 0)
{// Next row
sep = "\n"; // set the separator (between rows) to a newline
i = 0;
}
else
{// more for this row
// get the data
str = RO_df.ReadText();
// if first time output a newline otherwise output a vertical
// bar between values
buff += sep;
// output value
if (str != null)
buff += str;
// set the separator to a vertical bar
sep = "|";
if (width[i] > 0)
{
int jj;
jj = width[i] - str.Length;
// pad the value to the specified width
while (jj > 0)
{
buff += " ";
jj--;
}
}
i++;
}
}
// output the table
PutHeaderAndText(buff);
//Console.WriteLine("Multiple: {0} ", buff);
//Console.WriteLine("----------------------------------------------");
}
public void SetHeader()
{
string pTmp;
//Console.WriteLine("Set Header");
// Get the number of header records
short iNewCnt = RO_df.ReadInteger16();
//Console.WriteLine("Num Header Records: {0}", iNewCnt);
// Clear the existing headers
Hdrs.strHdrs.Clear();
// Loop through the headers
int iLoop = 0;
for (; iLoop < iNewCnt; iLoop++)
{
int hdrRptCnt = (int)RO_df.ReadInteger16();
if (Hdrs.repeatCount.Count - 1 < iLoop)
Hdrs.repeatCount.Add((int)hdrRptCnt);
else
Hdrs.repeatCount[iLoop] =hdrRptCnt;
pTmp = RO_df.ReadText();
//Console.WriteLine("SH[{0}]", pTmp);
if (Hdrs.strHdrs.Count - 1 < iLoop)
Hdrs.strHdrs.Add(pTmp);
else
Hdrs.strHdrs[iLoop] = pTmp;
//Console.WriteLine("Value: {0}", Hdrs.repeatCount[iLoop]);
//Console.WriteLine("Value Text: {0}", Hdrs.strHdrs[iLoop]);
//Console.WriteLine("----------------------------------------------");
}
// Set the new header count
Hdrs.HdrCnt = iNewCnt;
}
bool _LastWasName = false;//B2016-251 Don't change underscore to underline to Name value
public void PushHeader()
{
string pTmp = RO_df.ReadText();
//Console.WriteLine("PH[{0}]", pTmp);
curheaderlen = pTmp.Length;
_LastWasName = (pTmp == "Name");//B2016-251 Don't change underscore to underline to Name value
Hdrs.strHdrs.Add(pTmp);
Hdrs.repeatCount.Add(2);
Hdrs.HdrCnt++;
Hdrs.printedLastHeader = false;
//m_pPrinterOut->PushedHeader(Hdrs.strHdrs[Hdrs.HdrCnt-1]);
//Console.WriteLine("Push Header");
//Console.WriteLine("Header Text: {0}", pTmp);
//Console.WriteLine("----------------------------------------------");
}
public void PopHeader()
{
if (Hdrs.repeatCount[Hdrs.HdrCnt-1] == 2)
{
// if the last header was pushed on header list
// print eject the page if the page ran out, and
// print the header with "none".
LastHeader();
//m_pPrinterOut->PutLine(0, "none");
//m_pPrinterOut->NewLine(1);
}
// Remove the header
Hdrs.HdrCnt--;
Hdrs.strHdrs.RemoveAt(Hdrs.HdrCnt);
Hdrs.repeatCount.RemoveAt(Hdrs.HdrCnt);
//Console.WriteLine("Pop Header");
//Console.WriteLine("----------------------------------------------");
}
public void RROBegin()
{
//Console.WriteLine("RRO Begin");
//Console.WriteLine("----------------------------------------------");
// Start of a new RO, print out the headers
for (int iLoop = 0; iLoop < Hdrs.HdrCnt; iLoop++)
{
if (!MyDocOutline.ContainsKey(iLoop) || MyDocOutline[iLoop].MyHeader != Hdrs.strHdrs[iLoop])
{
PdfOutline parentOutline;
if (iLoop == 0)
parentOutline = MyRootOutline;//_MyPDFWriter.DirectContent.RootOutline;
else
parentOutline = MyDocOutline[iLoop - 1].MyOutline;
AddOutlineLevel(parentOutline, iLoop, Hdrs.strHdrs[iLoop], MyPdfDestPage);
}
// Change double underscore to spaces in header text
AddText(Hdrs.strHdrs[iLoop].Replace("__"," "), F12Bold); // should be bold and first header is centered
}
}
public PdfDestination MyPdfDestTop
{
get
{
// FITH was acting strange and shifting towards bottom of the page as the number of pages increased
//Console.WriteLine("Top = {0}, {1}", _Top, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height);
return new PdfDestination(PdfDestination.XYZ, 0, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height, 1.5f);
}
}
public PdfDestination MyPdfDestPage => new PdfDestination(PdfDestination.FITV, 0);
private PdfOutline _MyErrorOutline = null;
public PdfOutline MyErrorOutline
{
get
{
if (_MyErrorOutline == null)
{
_MyErrorOutline = new PdfOutline(_MyPDFWriter.DirectContent.RootOutline, MyPdfDestPage, "Errors");
}
return _MyErrorOutline;
}
}
private PdfOutline _MyRootOutline = null;
public PdfOutline MyRootOutline
{
get
{
if (_MyRootOutline == null)
{
_MyRootOutline = new PdfOutline(_MyPDFWriter.DirectContent.RootOutline, MyPdfDestTop, "Referenced Objects");
}
return _MyRootOutline;
}
}
private void AddOutlineLevel(PdfOutline parentOutline, int iLoop, string hdr, PdfDestination pdfDest)
{
if (MyDocOutline.ContainsKey(iLoop))
MyDocOutline[iLoop] = new DocOutline(new PdfOutline(parentOutline, pdfDest, hdr), hdr);
else
MyDocOutline.Add(iLoop,new DocOutline(new PdfOutline(parentOutline, pdfDest, hdr), hdr));
}
public void RROEnd()
{
// Remove any headers that are left over
//Console.WriteLine("{0} headers cleaned up.", Hdrs.HdrCnt);
//Console.WriteLine("RRO End");
//Console.WriteLine("----------------------------------------------");
}
public void Msg()
{
// Set a message to the printer on its own
string szStr = RO_df.ReadText();
PutHeaderAndText(szStr);
//m_pPrinterOut->NewLine(1);
//m_pPrinterOut->PutChr(szStr);
//m_pPrinterOut->NewLine(1);
//Console.WriteLine("Message");
//Console.WriteLine("Message Text: {0}", szStr);
//Console.WriteLine("----------------------------------------------");
}
public void NoInformatEntered()
{
PutHeaderAndText("-- No information entered --");
}
public void PutHeaderAndText(string txt)
{
if (!Hdrs.printedLastHeader)
{
Chunk chk = LastHeader();
Phrase p = new Phrase();
PdfPCell cell = new PdfPCell();
p.Add(chk); // add the header chunk
cell.BackgroundColor = Color.WHITE;
cell.BorderColor = Color.WHITE;
cell.AddElement(p);
datatable.AddCell(cell);
}
PutText(txt);
}
public void Text()
{
// Get the lenght of the text string and read it in
short iValue = RO_df.ReadInteger16();
string szStr = "";
// B2016-247 If size is zero it is an empty string.
if (iValue > 0)
szStr = RO_df.ReadText(iValue);
//Console.WriteLine("[{0}.{0:X}]='{1}'",iValue,szStr);
string temp = szStr;
Chunk chk = LastHeader();
Phrase p = new Phrase();
PdfPCell cell = new PdfPCell();
if (MyROID != null)
{
chk.SetLocalDestination(string.Format("ROID={0}", MyROID.ToUpper())); // Destination
//Console.WriteLine("\"ROID\"\t\"{0}\"", MyROID.ToUpper());
MyROID = null;
}
p.Add(chk); // add the header chunk
cell.BackgroundColor = Color.WHITE;
cell.BorderColor = Color.WHITE;
bool isXYPlot = szStr.StartsWith("<<G");
if (isXYPlot || (iValue + curheaderlen) > 72 || (szStr.IndexOf('\r') != -1))
{
// If the length of the string plus the field title is greater
// than 72 characters or has a carriage return character in it
// then output the text on multiple lines
// the header goes on its own line
cell.AddElement(p);
datatable.AddCell(cell);
// text goes below the header
if (isXYPlot)
AddXYPlot(szStr); // xy plot - sometimes plots were put in text fields
else
PutText(temp); // it's just text
}
else
{
// Otherwise output the header and text on a single line
p.Add(ConvertDOSSuperAndSubScripts(szStr,F10));
cell.AddElement(p);
datatable.AddCell(cell);
//m_pPrinterOut->SetNumberOfNewLines(0);
//m_pPrinterOut->putline(0, temp);
}
//Console.WriteLine("Text");
//Console.WriteLine("Value: {0}", iValue);
//Console.WriteLine("Text: {0}", szStr);
//Console.WriteLine("----------------------------------------------");
}
public string KeyField()
{
// use the key field as the PDF bookbark
string szStr = RO_df.ReadText();
#pragma warning disable IDE0059 // Unnecessary assignment of a value - For Debugging
PdfOutline outl = new PdfOutline(MyDocOutline[Hdrs.HdrCnt - 1].MyOutline, MyPdfDestTop, szStr);
#pragma warning restore IDE0059 // Unnecessary assignment of a value
//DestSample(outl);
return szStr;
//Console.WriteLine("Key Field");
//Console.WriteLine("Key Text: {0}", szStr);
//Console.WriteLine("----------------------------------------------");
}
public string ROIDField()
{
// use the key field as the PDF bookbark
string szStr = RO_df.ReadText();
//For Dubugging
//PdfDestination pdfDest = new PdfDestination(PdfDestination.FITH, _MyPDFWriter.DirectContent.PdfDocument.PageSize.Height);
//PdfOutline outl = new PdfOutline(MyDocOutline[Hdrs.HdrCnt - 1].MyOutline, MyPdfDestTop, szStr);
//DestSample(outl);
return szStr;
//Console.WriteLine("Key Field");
//Console.WriteLine("Key Text: {0}", szStr);
//Console.WriteLine("----------------------------------------------");
}
// Read in the image filename, height, and width
public void ImageFile()
{
string fn = RO_df.ReadText();
#pragma warning disable IDE0059 // Unnecessary assignment of a value - for Debugging
short ht = RO_df.ReadInteger16();
short wd = RO_df.ReadInteger16();
#pragma warning restore IDE0059 // Unnecessary assignment of a value
//m_pPrinterOut->PrintImage(fn, wd, ht);
//Console.WriteLine("ImageFile");
//Console.WriteLine("Name: {0}", fn);
//Console.WriteLine("Height: {0}", ht);
//Console.WriteLine("Width: {0}", wd);
//Console.WriteLine("----------------------------------------------");
AddImage(fn);
}
// Read in the X/Y plot info.
public void XYPlot()
{
// Get the lenght of the text string and read it in
short iValue = RO_df.ReadInteger16();
string szStr = RO_df.ReadText(iValue);
Chunk chk = LastHeader();
Phrase p = new Phrase();
PdfPCell cell = new PdfPCell();
p.Add(chk); // add the header chunk
cell.BackgroundColor = Color.WHITE;
cell.BorderColor = Color.WHITE;
// the header goes on its own line
cell.AddElement(p);
datatable.AddCell(cell);
AddXYPlot(szStr);
//Console.WriteLine("XY Plot");
//Console.WriteLine("Value: {0}", iValue);
//Console.WriteLine("Text: {0}", szStr);
//Console.WriteLine("----------------------------------------------");
}
// Output the string. If it is a graph, print the graph.
// ParseForGraph contains the code to print the text.
public void PutText(string szStr)
{
if (szStr == null || szStr.Equals("NONE"))
{
//m_pPrinterOut->putchr("NONE");
//m_pPrinterOut->newline(2);
AddText("NONE", F10);
return;
}
//m_pPrinterOut->SetNumberOfNewLines(0);
AddText(szStr,F10);
//m_pPrinterOut->newline(2);
// Include margin so the Display Data can print with a margin of zero
//m_pPrinterOut->ParseForGraph(temp, margin);
}
// Output the last header that was push onto the header stack
// Printer::LastHeader contains the code to do this.
public Chunk LastHeader()
{
Chunk chk;// = new Chunk(m.Value, fnt);
string hdrtxt = "";
if (Hdrs.HdrCnt > 0)
hdrtxt = Hdrs.strHdrs[Hdrs.HdrCnt - 1];
hdrtxt += ": ";
chk = new Chunk(hdrtxt, F10Bold);
Hdrs.printedLastHeader = true;
return chk;
}
}// end CompSumROReport
public class Headers
{
public List<string> strHdrs;
public int HdrCnt;
public List<int> repeatCount;
public bool printedLastHeader;
public Headers()
{
HdrCnt = 0;
strHdrs = new List<string>();
repeatCount = new List<int>();
printedLastHeader = false;
}
}
public class RODataFile
{
readonly FileStream fs = null;
readonly BinaryReader br = null;
public RODataFile(string fname)
{
fs = new FileStream(fname,FileMode.Open);
br = new BinaryReader(fs);
}
public void close()
{
br.Close();
fs.Close();
}
public long GetFileLength() => fs.Length;
public long GetFilePointerPosition() => fs.Position;
// Read an integer value from the data file
public Int16 ReadInteger16()
{
try
{
return (Int16)br.ReadUInt16();
}
catch (Exception e)
{
Console.WriteLine("Exception : {0}", e.Message);
return -1;
}
}
// Read a text string from the data file and returns it.
// The calling program is responsible for free it
// with the "delete" operator.
public string ReadText() => ReadText(-1);
public string ReadText(Int16 i16CharCount)
{
short i16DataSize;
if (i16CharCount == -1)
i16DataSize = ReadInteger16();
else
i16DataSize = i16CharCount;
if (i16DataSize <= 0)
return null;
else
{
byte[] charbuff = new byte[i16DataSize + 1];
charbuff = br.ReadBytes(i16DataSize);
string str = "";
for (int i = 0; i < i16DataSize; i++)
str += Convert.ToChar(charbuff[i]).ToString();
return (str);
}
}
// Search through the file to find the next record
public long NextRecord()
{
short iType;
short RECORD_START = 255;
// While not the next record and not end of file get the next meta item
while ((iType = ReadInteger16()) != RECORD_START && iType != -1)
{
NextItem();
}
return fs.Seek(0, SeekOrigin.Current);
}
// Get the next meta item and discard the data
public long NextItem()
{
short iRecType = ReadInteger16();
short iNewCnt;
int iLoop;
switch (iRecType)
{
case 1: // Set Header
iNewCnt = ReadInteger16();
for (iLoop = 0; iLoop < iNewCnt; iLoop++)
{
ReadInteger16();
_ = ReadText();
}
break;
case 2: // Push Header
case 6: // Msg
case 7: // Key Field
case 100: // Text Field
case 101: // Plot Field
_ = ReadText();
break;
case 3: // Pop Header
case 4: // RRO Begin
case 5: // RRO End
case 103: // Multi Begin
case 104: // Multi End
case 0: // Do Nothing
// Do nothing
break;
case 102: // Image Field
_ = ReadText();
ReadInteger16();
ReadInteger16();
break;
}
return fs.Seek(0, SeekOrigin.Current);
}
// Get the block of data that is the record
public byte[] GetRecord(ref int size)
{
byte[] data;
// Get the current position
long lCurPos = fs.Seek(0, SeekOrigin.Current);
// Go to the end of the record and get the file position
ReadInteger16();
NextRecord();
long lEndRecord = fs.Seek(0, SeekOrigin.Current);
// Get the size of the record
size = (int)(lEndRecord - lCurPos);
// Retrieve the record from the file
data = new byte[size +1];
data = br.ReadBytes(size);
return data;
}
}
}