This is my function to print a receipt for order, print is working but my problem is that print does not made a aligned records. i have attached a screen shot of output at the bottom please tell me what i do so output make good.
private void PrintReceipt(object sender, PrintPageEventArgs e)
{
//Graphics g = this.CreateGraphics();
Graphics graphic = e.Graphics;
Font font = new Font("Courier", 8);
Font Heading = new Font("Courier", 10);
float fontHeight = font.GetHeight();
int startX = 10;
int startY = 10;
int offset = 40;
int receipt_w = 400;
//int receipt_h = 0;
string company_name = "Welcome to Arslan Medicose";
string company_address = "Kohenoor One Jaranwala road faisalbad";
string company_phone = "Phone:+9233898937";
string developer_str = "Developed by: virk";
string developer_contact = "Phone:+923338989937";
string underLine = "-------------------------------------------------------------------------------------------------------";
SizeF size = graphic.MeasureString(company_name, Heading);
graphic.DrawString(company_name, Heading, new SolidBrush(Color.Black), (receipt_w - size.Width) / 2, startY);
//offset = offset + (int)fontHeight + 5;
size = graphic.MeasureString(company_address, Heading);
graphic.DrawString(company_address, font, new SolidBrush(Color.Black), (receipt_w - size.Width) / 2, startY + offset);
offset = offset + (int)fontHeight + 5;
size = graphic.MeasureString(company_phone, Heading);
graphic.DrawString(company_phone, font, new SolidBrush(Color.Black), (receipt_w - size.Width) / 2, startY + offset);
offset = offset + (int)fontHeight + 5;
graphic.DrawString(underLine, font, new SolidBrush(Color.Black), startX, startY + offset);
offset = offset + (int)fontHeight + 5;
int total_rows = cart_pro_gv.RowCount;
int recs = 1;
foreach (DataGridViewRow row in cart_pro_gv.Rows) {
if (recs < total_rows)
{
string pn = (null != row.Cells[1].Value) ? row.Cells[1].Value.ToString().Trim() : String.Empty;
string pq = (null != row.Cells[2].Value) ? row.Cells[2].Value.ToString().Trim() : String.Empty;
string pp = (null != row.Cells[3].Value) ? row.Cells[3].Value.ToString().Trim() : String.Empty;
string ppt = (null != row.Cells[4].Value) ? row.Cells[4].Value.ToString().Trim() : String.Empty;
string pline = string.Format("{0,-40}|{1,-15}|{2,-15}|{3,-15}", pn, pq, pp, ppt);
//string pline = string.Format("{0}|{1}|{2}|{3}", pn.PadRight(30), pq.PadRight(30), pp.PadRight(30), ppt.PadRight(30));
/*int padding = 3;
int maxCol0width = pn.Length;
int maxCol1width = pq.Length;
int maxCol2width = pp.Length;
int maxCol3width = ppt.Length;
string fmt0 = "{0,-" + (maxCol0width + padding) + "}";
string fmt1 = "{1,-" + (maxCol1width + padding) + "}";
string fmt2 = "{2,-" + (maxCol2width + padding) + "}";
string fmt3 = "{3,-" + (maxCol3width + padding) + "}";
string fmt = fmt0 + fmt1 + fmt2 + fmt3;
string pline = string.Format(fmt, pn, pq, pp, ppt);*/
graphic.DrawString(pline, font, Brushes.Black, startX, startY + offset);
offset = offset + (int)fontHeight + 5;
}
recs++;
}
// offset = offset + (int)fontHeight + 5;
graphic.DrawString(underLine, font, Brushes.Black , startX, startY + offset);
offset = offset + 10;
string total_paying = "Net Total: " + cart_total_label.Text;
graphic.DrawString(total_paying, font, new SolidBrush(Color.Black), startX, startY + offset);
}
Here is output that I am getting:
Related
Hi I have a form for pharmacy purchase but the print/confirm button have errors. The error occurs when it is printing. I just found this codes on a tutorial online and I want to use it.
This is the error I got when pdf is printing.
The error is from the float cash = float.Parse(txBCash.Text.Substring(1, 3));
This is the codes
private void btnConfirm_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
PrintDocument printDocument = new PrintDocument();
printDialog.Document = printDocument; //add the document to the dialog box...
printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(CreateReceipt); //add an event handler that will do the printing
//on a till you will not want to ask the user where to print but this is fine for the test envoironment.
DialogResult result = printDialog.ShowDialog();
if (result == DialogResult.OK)
{
printDocument.Print();
}
}
public void CreateReceipt(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int total = 0;
float cash = float.Parse(txBCash.Text.Substring(1, 3));
float change = 0.00f;
//this prints the reciept
Graphics graphic = e.Graphics;
Font font = new Font("Courier New", 12); //must use a mono spaced font as the spaces need to line up
float fontHeight = font.GetHeight();
int startX = 10;
int startY = 10;
int offset = 40;
graphic.DrawString(" Kwem Drugstore", new Font("Courier New", 18), new SolidBrush(Color.Black), startX, startY);
string top = "Item Name".PadRight(30) + "Price";
graphic.DrawString(top, font, new SolidBrush(Color.Black), startX, startY + offset);
offset = offset + (int)fontHeight; //make the spacing consistent
graphic.DrawString("----------------------------------", font, new SolidBrush(Color.Black), startX, startY + offset);
offset = offset + (int)fontHeight + 5; //make the spacing consistent
float totalprice = 0.00f;
foreach (string item in listViewOrders.Items)
{
//create the string to print on the reciept
string productDescription = item;
string productTotal = item.Substring(item.Length - 6, 6);
float productPrice = float.Parse(item.Substring(item.Length - 5, 5));
//MessageBox.Show(item.Substring(item.Length - 5, 5) + "PROD TOTAL: " + productTotal);
}
change = (cash - totalprice);
//when we have drawn all of the items add the total
offset = offset + 20; //make some room so that the total stands out.
graphic.DrawString("Total to pay ".PadRight(30) + String.Format("{0:c}", totalprice), new Font("Courier New", 12, FontStyle.Bold), new SolidBrush(Color.Black), startX, startY + offset);
offset = offset + 30; //make some room so that the total stands out.
graphic.DrawString("CASH ".PadRight(30) + String.Format("{0:c}", cash), font, new SolidBrush(Color.Black), startX, startY + offset);
offset = offset + 15;
graphic.DrawString("CHANGE ".PadRight(30) + String.Format("{0:c}", change), font, new SolidBrush(Color.Black), startX, startY + offset);
offset = offset + 30; //make some room so that the total stands out.
graphic.DrawString(" Thank-you for your purchase,", font, new SolidBrush(Color.Black), startX, startY + offset);
offset = offset + 15;
graphic.DrawString(" please come back soon!", font, new SolidBrush(Color.Black), startX, startY + offset);
}
}
I don't know if this is correct or if i'm doing it correctly. But please help me resolve this because for our project in our school.
Any type of response is greatly appreciated. Thank you in advance.
Array indexes in C# starts at zero, not at 1. And the second parameter of the Substring method is not the end position but the length of characters to retrieve. So your code asks for 3 characters from the txBCash textbox starting from the second character typed. If you want to get the first three characters then you should write
float cash = float.Parse(txBCash.Text.Substring(0, 3));
But a better approach is through float.TryParse that doesn't trigger an exception when the input is not a valid float. Of course you cannot be sure that your user types just 3 characters in that textbox, so I would remove also the starting and the length limits
float cash = 0.0;
if(!float.TryParse(txBCash.Text, out cash))
MessageBox.Show("Invalid value for cash");
I have a dgv where I add many products and codes, values etc, for the products, then I have the need to print out the contents.
Initially, I'm using this code:
private int _Line = 0;
void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Font myFont = new Font("Courier New", 08, FontStyle.Underline, GraphicsUnit.Point);
float lineHeight = myFont.GetHeight(e.Graphics) + 4;
float yLineTop = e.MarginBounds.Top;
int b = dataGridView1.Rows.Count;
for (int _Line = 0; _Line < b; _Line++)
{
if (yLineTop + lineHeight > e.MarginBounds.Bottom)
{
e.HasMorePages = true;
return;
}
//e.Graphics.DrawString("TEST: " + _Line, myFont, Brushes.Black,
// new PointF(e.MarginBounds.Left, yLineTop));
Graphics graphics = e.Graphics;
//Font font = new Font("Courier New", 8);
//float fontHeight = font.GetHeight();
int startX = 50;
int startY = 65;
int Offset = 40;
graphics.DrawString("Welcome to Bakery Shop - "+DateTime.Now+".", new Font("Courier New", 8), new SolidBrush(Color.Black), startX, startY + Offset);
Offset = Offset + 20;
string underLine = "------------------------------------------";
graphics.DrawString(underLine, new Font("Courier New", 8), new SolidBrush(Color.Black), startX, startY + Offset);
Offset = Offset + 20;
graphics.DrawString("" + label1.Text + "", new Font("Courier New", 10), new SolidBrush(Color.Black), startX, startY + Offset);
Offset = Offset + 20;
graphics.DrawString("Item", new Font("Courier New", 8), new SolidBrush(Color.Black), startX, startY + Offset);
graphics.DrawString("Cod.", new Font("Courier New", 8), new SolidBrush(Color.Black), startX+80, startY + Offset);
graphics.DrawString("Nome", new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 160, startY + Offset);
graphics.DrawString("Valor", new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 240, startY + Offset);
graphics.DrawString("Qtd.", new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 320, startY + Offset);
graphics.DrawString("Parcial", new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 400, startY + Offset);
graphics.DrawString("Desconto", new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 510, startY + Offset);
graphics.DrawString("Subtotal", new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 600, startY + Offset);
Offset = Offset + 20;
int a = dataGridView1.Rows.Count;
for (int i = 0; i < a; i++)
{
graphics.DrawString(Convert.ToString(dataGridView1.Rows[i].Index+1), new Font("Courier New", 8), new SolidBrush(Color.Black), startX, startY + Offset + 30);
graphics.DrawString("\t" + Convert.ToString(dataGridView1.Rows[i].Cells[0].Value), new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 10, startY + Offset + 30);
graphics.DrawString("\t" + Convert.ToString(dataGridView1.Rows[i].Cells[1].Value), new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 90, startY + Offset + 30);
graphics.DrawString("\t" + Convert.ToString(dataGridView1.Rows[i].Cells[2].Value), new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 180, startY + Offset + 30);
graphics.DrawString("\t" + Convert.ToString(dataGridView1.Rows[i].Cells[3].Value), new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 270, startY + Offset + 30);
graphics.DrawString("\t" + Convert.ToString(dataGridView1.Rows[i].Cells[4].Value), new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 340, startY + Offset + 30);
graphics.DrawString("\t" + Convert.ToString(dataGridView1.Rows[i].Cells[5].Value), new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 430, startY + Offset + 30);
graphics.DrawString("\t" + Convert.ToString(dataGridView1.Rows[i].Cells[6].Value), new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 570, startY + Offset + 30);
Offset = Offset + 20;
graphics.DrawString("\t" +), new Font("Courier New", 8), new SolidBrush(Color.Black), startX + 570, startY + Offset + 30);
Offset = Offset + 20;
}
Offset = Offset + 20;
Offset = Offset + 20;
Offset = Offset + 20;
graphics.DrawString("Total - " + textBox7.Text + ".", new Font("Courier New", 8), new SolidBrush(Color.Black), startX, startY + Offset);
Offset = Offset + 20;
graphics.DrawString("Troco - " + textBox3.Text + ".", new Font("Courier New", 8), new SolidBrush(Color.Black), startX, startY + Offset);
Offset = Offset + 20;
yLineTop += lineHeight;
}
e.HasMorePages = false;
}
Beside some strange behaviour that I'm going to work later, I noticed that a single line has to have each element well aligned so that, it doesn't print information above informartion.
Then I thought that, If I convert the full row and add a space between each cell, and print the array, it would never display info above info, even when as example the "code" is too big, so it would not be showed above/mixed with the "name" column.
Is this a better way? How do I start to make that? Because everywhere I look at, the solution is to pass a single cell as string.
In my case, each row, would have 6 columns, many thanks in advance!
Fixed like this:
int a = dataGridView1.Rows.Count;
for (int i = 0; i < a; i++)
{
string[] dgvtoarray = { Convert.ToString(dataGridView1.Rows[i].Index + 1), Convert.ToString(dataGridView1.Rows[i].Cells[0].Value), Convert.ToString(dataGridView1.Rows[i].Cells[1].Value), Convert.ToString(dataGridView1.Rows[i].Cells[2].Value), Convert.ToString(dataGridView1.Rows[i].Cells[3].Value), Convert.ToString(dataGridView1.Rows[i].Cells[4].Value), Convert.ToString(dataGridView1.Rows[i].Cells[5].Value), Convert.ToString(dataGridView1.Rows[i].Cells[6].Value) };
var result = string.Join(" | ", dgvtoarray);
graphics.DrawString(Convert.ToString(result), new Font("Courier New", 8), new SolidBrush(Color.Black), startX, startY + Offset + 30);
Offset = Offset + 20;
}
The best way to print from datagridview is transferring data to Excel worksheet.
Microsoft.Office.Interop.Excel.Worksheet ws;
try
{
Microsoft.Office.Interop.Excel.Application Excell = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = Excell.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
ws = (Microsoft.Office.Interop.Excel.Worksheet)Excell.ActiveSheet;
Excell.Visible = true;
}
catch (Exception)
{
return;
}
int i = 1;
foreach (DataGridViewColumn clm in dgw.Columns)
{
ws.Cells[2, i] = clm.Name;
Microsoft.Office.Interop.Excel.Range xcell = ws.Cells[2, i];
Microsoft.Office.Interop.Excel.Borders brd1 = xcell.Borders;
xcell.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
brd1.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
brd1.Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlMedium;
i++;
}
Microsoft.Office.Interop.Excel.Range row = ws.Cells[2, i];
row.EntireRow.Font.Bold = true;
Microsoft.Office.Interop.Excel.Range fcell = ws.Cells[1, 1];
Microsoft.Office.Interop.Excel.Range lcell = ws.Cells[1, i - 1];
Microsoft.Office.Interop.Excel.Range space = ws.get_Range(fcell, lcell);
space.Merge(true);
space.EntireRow.Font.Bold = true;
ws.Cells[1, 1] = //Your text here
Microsoft.Office.Interop.Excel.Borders brd = space.Borders;
aralik.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
int m = 3;
foreach (DataGridViewRow rows in dgw.Rows)
{
for (int p = 1; p < i; p++)
{
if (rows.Cells[p-1].Value.ToString()=="")
{
string str = string.Empty;
foreach (Control item in cList)
{
if (item.Name=="lbl_"+(rows.Index.ToString())+"_"+((p-1).ToString()))
{
str = item.Text;
ws.Cells[m, p] = str;
}
}
}
else
{
ws.Cells[m, p] = rows.Cells[p - 1].Value;
}
}
m++;
}
ws.Columns.AutoFit();
This is my code from a school examination application. Hope this helps.
the sample panorama image url https://upload.wikimedia.org/wikipedia/commons/3/3b/360%C2%B0_Hoher_Freschen_Panorama_2.jpg which i saved in my pc and generate tile from that image programmatically and got
error like out of memory
this line throw the error Bitmap bmLevelSource =
(Bitmap)Bitmap.FromFile(levelSourceImage);
here is my program code in c# which throw the error
double maxZoom = 5;
string FILEPATH = #"C:\test\img.jpg";
string TARGETFOLDER = #"C:\test\Src";
bool REMOVEXISTINGFILES = true;
if (!System.IO.File.Exists(FILEPATH))
{
Console.WriteLine("file not exist");
return;
}
if (maxZoom >= 10)
{
Console.WriteLine("Scale multiplier should be an integer <=10");
return;
}
//Read image
Bitmap bmSource;
try
{
bmSource = (Bitmap)Bitmap.FromFile(FILEPATH);
}
catch
{
Console.WriteLine("image file not valid");
return;
}
//check directory exist
if (!System.IO.Directory.Exists(TARGETFOLDER))
{
System.IO.Directory.CreateDirectory(TARGETFOLDER);
}
else if (REMOVEXISTINGFILES)
{
string[] files = System.IO.Directory.GetFiles(TARGETFOLDER);
foreach (string file in files)
System.IO.File.Delete(file);
string[] dirs = System.IO.Directory.GetDirectories(TARGETFOLDER);
foreach (string dir in dirs)
System.IO.Directory.Delete(dir, true);
}
int actualHeight = bmSource.Height;
int actualWidth = bmSource.Width;
if (((actualHeight % 256) != 0)
||
((actualWidth % 256) != 0))
{
Console.WriteLine("image width and height pixels should be multiples of 256");
return;
}
int actualResizeSizeWidth = 1;
int level = 0;
while (level <= maxZoom)
{
string leveldirectory = System.IO.Path.Combine(TARGETFOLDER, String.Format("{0}", level));
if (!System.IO.Directory.Exists(leveldirectory))
System.IO.Directory.CreateDirectory(leveldirectory);
int rowsInLevel = Convert.ToInt32(Math.Pow(2, level));
actualResizeSizeWidth = 256 * rowsInLevel;
//create image to parse
int actualResizeSizeHeight = (actualHeight * actualResizeSizeWidth) / actualWidth;
Bitmap resized = new Bitmap(bmSource, new Size(actualResizeSizeWidth, actualResizeSizeHeight));
string levelSourceImage = System.IO.Path.Combine(leveldirectory, "level.png");
resized.Save(levelSourceImage);
for (int x = 0; x < rowsInLevel; x++)
{
string levelrowdirectory = System.IO.Path.Combine(leveldirectory, String.Format("{0}", x));
if (!System.IO.Directory.Exists(levelrowdirectory))
System.IO.Directory.CreateDirectory(levelrowdirectory);
Bitmap bmLevelSource = (Bitmap)Bitmap.FromFile(levelSourceImage);
//generate tiles
int numberTilesHeight = Convert.ToInt32(Math.Ceiling(actualResizeSizeHeight / 256.0));
for (int y = 0; y < numberTilesHeight; y++)
{
Console.WriteLine("Generating Tiles " + level.ToString() + " " + x.ToString() + " " + y.ToString()); int heightToCrop = actualResizeSizeHeight >= 256 ? 256 : actualResizeSizeHeight;
Rectangle destRect = new Rectangle(x * 256, y * 256, 256, heightToCrop);
//croped
Bitmap bmTile = bmLevelSource.Clone(destRect, System.Drawing.Imaging.PixelFormat.DontCare);
//full tile
Bitmap bmFullTile = new Bitmap(256, 256);
Graphics gfx = Graphics.FromImage(bmFullTile);
gfx.DrawImageUnscaled(bmTile, 0, 0);
bmFullTile.Save(System.IO.Path.Combine(levelrowdirectory, String.Format("{0}.png", y)));
bmFullTile.Dispose();
bmTile.Dispose();
}
}
level++;
}
i comment the below code when i run the program
if (((actualHeight % 256) != 0)
||
((actualWidth % 256) != 0))
{
Console.WriteLine("image width and height pixels should be multiples of 256");
return;
}
what is the fault for which i got the error called "Out of Memory"
Thanks
Edit
actual image height and width was 1250 and 2500.
actualResizeSizeWidth 256
actualResizeSizeHeight 128
i include a panorama image url in this post at top. can u plzz download url and execute my code at your end to see memory issue is coming?
Code Update
i modify the code a bit and dispose some Bitmap.
dispose like this way
bmLevelSource.Dispose(); and resized.Dispose();
while (level <= maxZoom)
{
string leveldirectory = System.IO.Path.Combine(TARGETFOLDER, String.Format("{0}", level));
if (!System.IO.Directory.Exists(leveldirectory))
System.IO.Directory.CreateDirectory(leveldirectory);
int rowsInLevel = Convert.ToInt32(Math.Pow(2, level));
actualResizeSizeWidth = 256 * rowsInLevel;
//create image to parse
int actualResizeSizeHeight = (actualHeight * actualResizeSizeWidth) / actualWidth;
Bitmap resized = new Bitmap(bmSource, new Size(actualResizeSizeWidth, actualResizeSizeHeight));
string levelSourceImage = System.IO.Path.Combine(leveldirectory, "level.png");
resized.Save(levelSourceImage);
for (int x = 0; x < rowsInLevel; x++)
{
string levelrowdirectory = System.IO.Path.Combine(leveldirectory, String.Format("{0}", x));
if (!System.IO.Directory.Exists(levelrowdirectory))
System.IO.Directory.CreateDirectory(levelrowdirectory);
Bitmap bmLevelSource = (Bitmap)Bitmap.FromFile(levelSourceImage);
//generate tiles
int numberTilesHeight = Convert.ToInt32(Math.Ceiling(actualResizeSizeHeight / 256.0));
for (int y = 0; y < numberTilesHeight; y++)
{
Console.WriteLine("Generating Tiles " + level.ToString() + " " + x.ToString() + " " + y.ToString()); int heightToCrop = actualResizeSizeHeight >= 256 ? 256 : actualResizeSizeHeight;
Rectangle destRect = new Rectangle(x * 256, y * 256, 256, heightToCrop);
//croped
Bitmap bmTile = bmLevelSource.Clone(destRect, System.Drawing.Imaging.PixelFormat.DontCare);
//full tile
Bitmap bmFullTile = new Bitmap(256, 256);
Graphics gfx = Graphics.FromImage(bmFullTile);
gfx.DrawImageUnscaled(bmTile, 0, 0);
bmFullTile.Save(System.IO.Path.Combine(levelrowdirectory, String.Format("{0}.png", y)));
bmFullTile.Dispose();
bmTile.Dispose();
}
bmLevelSource.Dispose();
}
level++;
resized.Dispose();
}
please see my bit modified code and give suggestion now.
I'm currently working on Tracking Object by Color on my WebCam, and i have it going so far but i want to add an option to draw multiple Objects. Until now it only Draws a Rectangle around the biggest Object.
BlobCounter blobcounter = new BlobCounter();
blobcounter.MinHeight = 100;
blobcounter.MinWidth = 100;
blobcounter.ObjectsOrder = ObjectsOrder.Size;
blobcounter.ProcessImage(grayImage);
Rectangle[] rects = blobcounter.GetObjectsRectangles();
if (checkBox1.Checked == false)
{
if (rects.Length > 0)
{
Rectangle objectRect1 = rects[0];
Graphics g = Graphics.FromImage(video);
using (Pen pen = new Pen(Color.LightGreen, 3))
{
g.DrawRectangle(pen, objectRect1);
PointF drawPoin = new PointF(objectRect1.X, objectRect1.Y);
int objectX = objectRect1.X + objectRect1.Width / 2 - video.Width / 2;
int objectY = video.Height / 2 - (objectRect1.Y + objectRect1.Height / 2);
PointF drawPoin2 = new PointF(objectRect1.X, objectRect1.Y + objectRect1.Height + 4);
String Blobinformation = "X= " + objectX.ToString() + " Y= " + objectY.ToString() + "\nSize=" + objectRect1.Width + ", " + objectRect1.Height;
g.DrawString(Blobinformation, new Font("Arial", 12), new SolidBrush(Color.LightSkyBlue), drawPoin2);
}
g.Dispose();
}
}
else
{
??????????
}
Adding a simple foreach loop should suffice. I don't know how efficient the drawing is, but I'm almost certain it wont be a problem with a few rectangles.
else
{
if (rects.Length > 0)
{
foreach (Rectangle objectRect in rects)
{
Graphics g = Graphics.FromImage(video);
using (Pen pen = new Pen(Color.LightGreen, 3))
{
g.DrawRectangle(pen, objectRect);
PointF drawPoin = new PointF(objectRect.X, objectRect.Y);
int objectX = objectRect.X + objectRect.Width / 2 - video.Width / 2;
int objectY = video.Height / 2 - (objectRect.Y + objectRect.Height / 2);
PointF drawPoin2 = new PointF(objectRect.X, objectRect.Y + objectRect.Height + 4);
String Blobinformation = "X= " + objectX.ToString() + " Y= " + objectY.ToString() + "\nSize=" + objectRect.Width + ", " + objectRect.Height;
g.DrawString(Blobinformation, new Font("Arial", 12), new SolidBrush(Color.LightSkyBlue), drawPoin2);
}
g.Dispose();
}
}
}
I was testing a "Print Preview" button and it worked fine. After closing its PrintPreview window I clicked the "Print Preview" button again and this time it showed a blank page! I cannot figure out why this is happening. Have searched this site and many others so I am posting this question. Any ideas would be greatly appreciated.
Here's the related code:
private void buttonPrintPreview_Click(object sender, EventArgs e)
{
page = 0;
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
}
private void buttonPrint_Click(object sender, EventArgs e)
{
page = 0;
printDialog1.Document = printDocument1;
if (printDialog1.ShowDialog() == DialogResult.OK)
{
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
printDocument1.DefaultPageSettings.Landscape = false;
printDocument1.Print();
//printDocument1.Dispose();
}
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
//define margins
float leftMargin = 70.0f; //good room for hole punches!
float topMargin = 20.0f;
float lineInc = 20.0f;
//--------------------------------------------
string eiNum = string.Empty;
string eiDesc = string.Empty;
string partNum = string.Empty;
string partDesc = string.Empty;
string price = string.Empty;
string partType = string.Empty;
string partQty = string.Empty;
string thisEndItem = string.Empty;
string textToPrint = string.Empty;
Font printFontArial10 = new Font("Arial", 10, FontStyle.Regular);
Font printFontArial10Bold = new Font("Arial", 10, FontStyle.Bold);
Font printFontArial14 = new Font("Arial", 14, FontStyle.Bold);
Font printFontCour8 = new Font("Courier New", 8, FontStyle.Regular);
if (page == 0 && counter == 0)
{
// draw image/logo
Image Logo = Image.FromFile(Settings.Default.LogoPath);
g.DrawImage(Logo, leftMargin, 35f);
// draw title
textToPrint = "TIW Purchasing - Master Buy List";
e.Graphics.DrawString(textToPrint, printFontArial14, Brushes.Black, leftMargin + 160f, 54f);
// date
DateTime thisDay = DateTime.Today;
textToPrint = thisDay.ToString("d");
e.Graphics.DrawString(textToPrint, printFontArial10, Brushes.Black, leftMargin + 280f, 76f);
eiNum = listView1.Items[0].Text;
eiDesc = listView1.Items[0].SubItems[1].Text;
if (eiDesc.Length > 80)
eiDesc = eiDesc.Substring(0, 80) + "...";
textToPrint = eiNum + " - " + eiDesc;
e.Graphics.DrawString(textToPrint, printFontArial10Bold, Brushes.Black, leftMargin, topMargin + 90);
}
else if (page > 0)
{
double remainder = counter % amtperpage;
if (remainder == 0) //---means we're at the top of the page
{
//title & version
textToPrint = "TIW Purchasing - Master Buy List";
e.Graphics.DrawString(textToPrint, printFontArial10Bold, Brushes.Black, leftMargin + 120, 54f);
textToPrint = "(continued from page " + page + ")";
e.Graphics.DrawString(textToPrint, printFontArial10, Brushes.Black, leftMargin + 400, 54f);
}
}
if (page == 0)
lineInc = 90;
else
lineInc = 78;
int stop = counter + amtperpage;
if (stop > listView1.Items.Count)
stop = listView1.Items.Count;
while (counter < stop)
{
thisEndItem = listView1.Items[counter].SubItems[0].Text;
partNum = listView1.Items[counter].SubItems[2].Text;
partDesc = listView1.Items[counter].SubItems[3].Text;
price = listView1.Items[counter].SubItems[4].Text;
partType = listView1.Items[counter].SubItems[5].Text;
partQty = listView1.Items[counter].SubItems[6].Text;
if (thisEndItem == eiNum) //---still working on the same end item
{
lineInc += 12;
textToPrint = partNum;
e.Graphics.DrawString(textToPrint, printFontArial10, Brushes.Black, leftMargin + 10, topMargin + lineInc);
if (partDesc.Length > 70)
partDesc = partDesc.Substring(0, 70) + "...";
textToPrint = partDesc;
e.Graphics.DrawString(textToPrint, printFontArial10, Brushes.Black, leftMargin + 70, topMargin + lineInc);
textToPrint = price;
e.Graphics.DrawString(textToPrint, printFontArial10, Brushes.Black, leftMargin + 600, topMargin + lineInc);
textToPrint = partType;
e.Graphics.DrawString(textToPrint, printFontArial10, Brushes.Black, leftMargin + 630, topMargin + lineInc);
textToPrint = partQty;
e.Graphics.DrawString(textToPrint, printFontArial10, Brushes.Black, leftMargin + 670, topMargin + lineInc);
}
else //---starting a new end item
{
lineInc += 16;
eiNum = listView1.Items[counter].Text;
eiDesc = listView1.Items[counter].SubItems[1].Text;
if (eiDesc.Length > 80)
eiDesc = eiDesc.Substring(0, 80) + "...";
textToPrint = eiNum + " - " + eiDesc;
e.Graphics.DrawString(textToPrint, printFontArial10Bold, Brushes.Black, leftMargin, topMargin + lineInc);
}
counter++;
}
//---footer-------------------------------
DateTime dateTime = DateTime.Now;
textToPrint = "eView " + EViewMethods.eviewVersion + " " + Environment.UserName + " " + String.Format("{0:F}", dateTime);
e.Graphics.DrawString(textToPrint, printFontCour8, Brushes.Black, leftMargin, 1060f);
printpagenum = page + 1;
textToPrint = printpagenum.ToString();
e.Graphics.DrawString(textToPrint, printFontArial10Bold, Brushes.Black, leftMargin + 740, 1060f);
//----------------------------------------
page++;
e.HasMorePages = counter < listView1.Items.Count;
}
Here's the corrected code:
private void buttonPrintPreview_Click(object sender, EventArgs e)
{
page = 0;
counter = 0;
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
}
private void buttonPrint_Click(object sender, EventArgs e)
{
page = 0;
counter = 0;
printDialog1.Document = printDocument1;
if (printDialog1.ShowDialog() == DialogResult.OK)
{
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
printDocument1.DefaultPageSettings.Landscape = false;
printDocument1.Print();
//printDocument1.Dispose();
}
}
public Form1()
{
InitializeComponent();
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
}