Create multiple label over the multiple ellipse - c#

I have 6 ellipse and 6 label. I want to add labels over the ellipse. 2 of labels is OK but the others not.
In debug mode there is no error.
Here is the code:
private void Form1_Paint(object sender, PaintEventArgs e)
{
int locY = 200, locX = 10, i = 0;
for (int k = 0; k < 3; k++)
{
locX += 40;
for (int j = 0; j < 2; j++)
{
locY += 30;
Pen pen = new Pen(Color.Red, 10);
e.Graphics.DrawEllipse(pen, new Rectangle(locX, locY, 10, 10));
Label label = new Label();
label.Text = i.ToString();
label.Location = new Point(locX,locY);
label.BackColor = Color.Transparent;
Controls.Add(label);
i++;
}
locY = 200;
}
}
Here is the output:

You should also create that Pen outside of the loop and make sure to dispose of it.
Here's an example using DrawString() as described in the comments:
private void Form1_Paint(object sender, PaintEventArgs e)
{
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
int locY = 200, locX = 10, i = 0;
using (Pen pen = new Pen(Color.Red, 10))
{
for (int k = 0; k < 3; k++)
{
locX += 40;
for (int j = 0; j < 2; j++)
{
locY += 30;
Rectangle rc = new Rectangle(locX, locY, 10, 10);
e.Graphics.DrawEllipse(pen, rc);
SizeF szF = e.Graphics.MeasureString(i.ToString(), this.Font);
Rectangle rc2 = new Rectangle(new Point(rc.Left + rc.Width / 2, rc.Top + rc.Height / 2), new Size(1, 1));
rc2.Inflate((int)szF.Width, (int)szF.Height);
e.Graphics.DrawString(i.ToString(), this.Font, Brushes.Black, rc2, sf);
i++;
}
locY = 200;
}
}
}

Related

how to draw into image bounding box in c#

i tried to draw into BMB image and i measure bounding box of each character i want to draw but nothing happen what's the wrong please ?
this is the code which draw the text
private void button2_Click(object sender, EventArgs e)
{
Bitmap bitmap = (Bitmap)Image.FromFile(imagepath);//load the image file
Bitmap newBitmap = new Bitmap(bitmap.Width, bitmap.Height);
PointF GLocation = new PointF(float.Parse(textBox1.Text), float.Parse(textBox2.Text));
/* PointF XLocation = new PointF(float.Parse(textBox3.Text), float.Parse(textBox4.Text));
PointF HLocation = new PointF(float.Parse(textBox5.Text), float.Parse(textBox6.Text));
PointF ZLocation = new PointF(float.Parse(textBox7.Text), float.Parse(textBox8.Text));
PointF YLocation = new PointF(float.Parse(textBox9.Text), float.Parse(textBox10.Text));
PointF KLocation = new PointF(float.Parse(textBox11.Text), float.Parse(textBox12.Text));
PointF FLocation = new PointF(float.Parse(textBox13.Text), float.Parse(textBox14.Text));
PointF ELocation = new PointF(float.Parse(textBox15.Text), float.Parse(textBox16.Text));*/
Graphics grPhoto = Graphics.FromImage(newBitmap);
grPhoto.DrawImage(bitmap, new Rectangle(0, 0, newBitmap.Width, newBitmap.Height), 0, 0, newBitmap.Width, newBitmap.Height, GraphicsUnit.Pixel);
//MessageBox.Show(measureAlphabet('G', arial).ToString());
int x = (int)measureAlphabet('G', arial).Width;
int y = (int)measureAlphabet('G', arial).Height;
Rectangle rec = measureAlphabet('G', arial);
for (int G = int.Parse(textBox1.Text); G <= G + x; G++)
{
for (G = int.Parse(textBox2.Text); G <= G + y; G++)
{
Color pixelcolor = newBitmap.GetPixel(x,y);
if (pixelcolor.R != 255 && pixelcolor.G != 255 && pixelcolor.B != 255)
{
using (Graphics graphics = Graphics.FromImage(newBitmap))
{
using (arial)
{
graphics.DrawString(firstchar, arial, Brushes.Blue, GLocation);
}
}
}
}
}
/* using (Graphics graphics = Graphics.FromImage(newBitmap))
{
using (arial)
{
graphics.DrawString(secondchar, arial, Brushes.Red, XLocation);
graphics.DrawString(thirdchar, arial, Brushes.Brown, HLocation);
graphics.DrawString(fourthchar, arial, Brushes.DarkCyan, ZLocation);
graphics.DrawString(fifthchar, arial, Brushes.DarkGreen, YLocation);
graphics.DrawString(sixthchar, arial, Brushes.Coral, KLocation);
graphics.DrawString(seventhchar, arial, Brushes.Salmon, FLocation);
graphics.DrawString(eighthchar, arial, Brushes.SeaGreen, ELocation);
}
}*/
bitmap.Dispose();
// newBitmap.Dispose();
newBitmap.Save(imagepath);
}
method which measure bounding box
public Rectangle measureAlphabet(char alph, Font font)
{
SizeF size = CreateGraphics().MeasureString(alph.ToString(), font);
Bitmap bmp = new Bitmap((int)size.Width, (int)size.Height);
Graphics grp = Graphics.FromImage(bmp);
grp.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);
grp.DrawString(alph.ToString(), font, Brushes.Black, new PointF(0, 0));
Bitmap img = (Bitmap)bmp;
int x = 0, y = 0, width = 0, height = 0;
for (int i = 0; i < img.Width; i++)
for (int j = 0; j < img.Height; j++)
if (img.GetPixel(i, j).B < 2)
{
x = i;
goto jmp1;
}
jmp1:;
for (int i = img.Width - 1; i >= 0; i--)
for (int j = 0; j < img.Height; j++)
if (img.GetPixel(i, j).B < 2)
{
width = i - x;
goto jmp2;
}
jmp2:;
for (int i = 0; i < img.Height; i++)
for (int j = 0; j < img.Width; j++)
if (img.GetPixel(j, i).B < 2)
{
y = i;
goto jmp3;
}
jmp3:;
for (int i = img.Height - 1; i >= 0; i--)
for (int j = 0; j < img.Width; j++)
if (img.GetPixel(j, i).B < 2)
{
height = i - y;
goto jmp4;
}
jmp4:;
Rectangle resultRectangle = new Rectangle(x, y, width, height);
return resultRectangle;
}

Can rectangle be split in rows and columns?

private void panel1_Paint(object sender, PaintEventArgs e)
{
Pen mypen = default(Pen);
mypen = new Pen(System.Drawing.Color.Red, 3);
mypen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
//For Dash Line in Rectangle
Pen mypen1 = default(Pen);
mypen1 = new Pen(System.Drawing.Color.Blue, 1);
mypen1.DashStyle![enter image description here][2] = System.Drawing.Drawing2D.DashStyle.Dash;
//Pen mypen2 =default(Pen);
//mypen2 = new Pen(System.Drawing.Color.Yellow, 3);
//mypen2.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
//Pen mypen3 = default(Pen);
//mypen3 = new Pen(System.Drawing.Color.Violet, 1);
//mypen3.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
L1 = Rect1LT.X + 5;
T1 = Rect1LT.Y + 5;
W1 = Rect1RB.X - Rect1LT.X;
H1 = Rect1RB.Y - Rect1LT.Y;
e.Graphics.DrawRectangle(mypen, new System.Drawing.Rectangle(L1, T1, W1, H1));
e.Graphics.DrawRectangle(mypen1, new System.Drawing.Rectangle(L1, T1, W1, H1));
e.Graphics.DrawRectangle(Pens.Blue, new System.Drawing.Rectangle(Rect1LT.X, Rect1LT.Y, 10, 10));
e.Graphics.DrawRectangle(Pens.Blue, new System.Drawing.Rectangle(Rect1RT.X, Rect1RT.Y, 10, 10));
e.Graphics.DrawRectangle(Pens.Blue, new System.Drawing.Rectangle(Rect1LB.X, Rect1LB.Y, 10, 10));
e.Graphics.DrawRectangle(Pens.Blue, new System.Drawing.Rectangle(Rect1RB.X, Rect1RB.Y, 10, 10));
e.Graphics.FillRectangle(Brushes.Blue, Rect1LT);
e.Graphics.FillRectangle(Brushes.Blue, Rect1RT);
e.Graphics.FillRectangle(Brushes.Blue, Rect1LB);
e.Graphics.FillRectangle(Brushes.Blue, Rect1RB);
e.Graphics.DrawRectangle(Pens.Blue, new System.Drawing.Rectangle(Rect1T.X, Rect1T.Y, 10, 10));
e.Graphics.DrawRectangle(Pens.Blue, new System.Drawing.Rectangle(Rect1R.X, Rect1R.Y, 10, 10));
e.Graphics.DrawRectangle(Pens.Blue, new System.Drawing.Rectangle(Rect1B.X, Rect1B.Y, 10, 10));
e.Graphics.DrawRectangle(Pens.Blue, new System.Drawing.Rectangle(Rect1L.X, Rect1L.Y, 10, 10));
e.Graphics.FillRectangle(Brushes.Blue, Rect1T);
e.Graphics.FillRectangle(Brushes.Blue, Rect1R);
e.Graphics.FillRectangle(Brushes.Blue, Rect1B);
e.Graphics.FillRectangle(Brushes.Blue, Rect1L);
DataGridView dg1 = new DataGridView();
//while (!exit)
//{
// var time = GetTime();
// Update(time);
// Render(time);
//}
}
I want to Divide Rectangle in Rows and Columns and Size of Rows and Column can be changeable at runtime? and No of Rows and Columns also can be changeable? I don't want to split whole rectangle I just want to divide them in rectangle.
Here is a simplfied example:
int cols = 7; int rows = 11;
private void panel1_Paint(object sender, PaintEventArgs e)
{
Rectangle Rect = // your Rectangle!
Rectangle pRect = Rect; // panel2.ClientRectangle;
float width = 1f * pRect.Width / cols;
float height = 1f * pRect.Height / rows;
using (Pen pen = new Pen(System.Drawing.Color.Blue, 1))
{
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
for (int c = 0; c < cols; c++)
for (int r = 0; r < rows; r++)
{
RectangleF rect = new RectangleF(pRect.X + c * width, pRect.Y + r * height,
width, height);
e.Graphics.FillRectangle(Brushes.Coral, rect);
// e.Graphics.DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height);
}
for (int c = 0; c < cols; c++) e.Graphics.DrawLine(pen,
pRect.X + c * width, pRect.Y, pRect.X + c * width, pRect.Y + pRect.Height);
for (int r = 0; r < rows; r++) e.Graphics.DrawLine(pen,
pRect.X, pRect.Y + r * height, pRect.X + pRect.Width, pRect.Y + r * height);
e.Graphics.DrawRectangle(Pens.Red,
pRect.X, pRect.Y, pRect.Width - 1, pRect.Height - 1);
}
}
Note a few changes:
The border color and the fill color must not be the same.
The fill must come first or it will overwrite the border
I work with floats to fill the panel completely; if the cols and rows don't divide into the panel/rectangle size evenly, the recangles will not all have the same sizes ..
At first I have ignored your DashStyle. If you want to have a DashStyle you must completely change your plan! The reason is that if you draw Rectangles in a grid you..
..either have them overlapping and then the dashes will get in each others way. There is a DashOffset parameter but I don't think it can be twisted to make it work over any grid.
..or you need to draw the rectangles inside the grid cells but then they will be twice a thick and the patterns still will disturb each other.
Instead you simply draw only a few lines as shown!
Here is my example with Dashes:

Place a grid of labels on a form

I'm trying to place a grid of labels on my winforms app. First, I'm populating a list of label objects of size (200 x 50) and then trying to place them so that when x reaches the width of the form (581), I increment y by 50 + 1
Here is my code:
private List<Label> _labels;
private int xOffset = 10;
private int yOffset = 10;
public Form1()
{
InitializeComponent();
_labels = new List<Label>();
for(var i = 0; i <= 20; i++)
_labels.Add(new Label() { Name = "lbl" + i, Height = 50, Width = 200, MinimumSize = new Size(200, 50), BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D, Text = "Label "+i});
// 581, 517
var x = 0;
var y = 0;
foreach (var lbl in _labels)
{
if (x >= 580)
{
x = 0;
y = y + lbl.Height + 2;
lbl.Location = new Point(x, y);
}
this.Controls.Add(lbl);
x += x + lbl.Width;
}
}
It's only placing the even labels from the list on new lines. I'm not sure what I'm doing wrong.
I'm trying to place all of the labels in a grid like design. When one row is full, go to the next row and continue placing labels from the list on that new "row"
You need to move the Location setting code out of the resetting loop:
foreach (var lbl in _labels)
{
if (x >= 580)
{
x = 0;
y = y + lbl.Height + 2;
}
lbl.Location = new Point(x, y);
this.Controls.Add(lbl);
x += lbl.Width;
}
The problematic part is here
x += x + lbl.Width; //+= x
change it to
x += lbl.Width;
Get the
lbl.Location = new Point(x, y);
out of the if statement
if (x >= 580)
{
x = 0;
y = y + lbl.Height + 2;
//lbl.Location = new Point(x, y);
}
lbl.Location = new Point(x, y);
this.Controls.Add(lbl);
x += lbl.Width;
Try this using a Docked FlowLayoutPanel:
public partial class Form1 : Form
{
List<Label> labels;
public Form1()
{
InitializeComponent();
this.labels=new List<Label>();
AddLabelsToFrom(20);
}
void AddLabelsToFrom(int count)
{
for (int i=0; i<count; i++)
{
var lbl=new Label() { Name="lbl"+i, Height=50, Width=200, MinimumSize=new Size(200, 50), BorderStyle=System.Windows.Forms.BorderStyle.Fixed3D, Text="Label "+i };
labels.Add(lbl);
flowLayoutPanel1.Controls.Add(lbl);
}
}
}
void SetGridLabel()
{
for (int i = 0; ; i++)
{
for (int j = 0; ; j++)
{
Label L = new Label();
L.TextAlign = ContentAlignment.MiddleCenter;
L.AutoSize = false;
L.Size = new Size(70, 70);
L.Text = "Test_" + j + "_" + i;
L.Location = new Point(j * L.Size.Width, i * L.Size.Height);
if ((i + 1) * L.Size.Height > this.Size.Height)
return;
if ((j + 1) * L.Size.Width > this.Size.Width)
break;
this.Controls.Add(L);
}
}
}
private List<Label> _labels;
public Form1()
{
InitializeComponent();
_labels = new List<Label>();
for (var i = 0; i <= 20; i++)
_labels.Add(new Label()
{
Name = "lbl" + i, Height = 50,Width = 200,
Size = MinimumSize = new Size(200, 50),
Location = new Point(i * 200 % 600, 50 * (i * 200 / 600)),
BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D,
Text = "Label " + i
});
foreach (var lbl in _labels) this.Controls.Add(lbl);
}

Can't draw on a form that was created by the code

I have faced a new and strange issue , i want to draw a simple eclipse in a form that is being created in the code that is called IM. The code for drawing it is here :
System.Drawing.Graphics graphicsObj;
graphicsObj = IM.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Green, 5);
Rectangle myRectangle = new Rectangle(0, 0, 10, 10);
graphicsObj.DrawEllipse(myPen, myRectangle);
IM.Show();
This doesn't draw anything but when I change IM.CreateGraphics() to this.CreateGraphics() it draws it on the original form perfectly. what am I missing ?
The code for creating the form IM :
Form IM = new Form();
IM.FormBorderStyle = FormBorderStyle.FixedSingle;
IM.Width = 500;
IM.Height = 500;
Full code :
private void button5_Click(object sender, EventArgs e)
{
int maxx = 0, maxy = 0;
int minx = 1000000000, miny = 1000000000;
int[] xts = new int[1000];
int[] yts = new int[1000];
int[] xps = new int[1000];
int[] yps = new int[1000];
int countert = -1;
int counterp = -1;
Form IM = new Form();
IM.FormBorderStyle = FormBorderStyle.FixedSingle;
System.IO.StreamReader file1 =
new System.IO.StreamReader("./MainProgram/Target.txt");
while (file1.Peek() >= 0)
{
countert++;
string line = file1.ReadLine();
string[] words = line.Split();
xts[countert] = Convert.ToInt32(words[0]);
if (xts[countert] > maxx) maxx = xts[countert];
if (xts[countert] < minx) minx = xts[countert];
yts[countert] = Convert.ToInt32(words[1]);
if (yts[countert] > maxy) maxy = yts[countert];
if (yts[countert] < miny) miny = yts[countert];
}
System.IO.StreamReader file2 =
new System.IO.StreamReader("./MainProgram/Pagepos.txt");
while (file2.Peek() >= 0)
{
counterp++;
string line = file2.ReadLine();
string[] words = line.Split();
xps[counterp] = Convert.ToInt32(words[0]);
if (xps[counterp] > maxx) maxx = xps[counterp];
if (xps[counterp] < minx) minx = xps[counterp];
yps[counterp] = Convert.ToInt32(words[1]);
if (yps[counterp] > maxy) maxy = yps[counterp];
if (yps[counterp] < miny) miny = yps[counterp];
}
int sizex = maxx - minx;
int sizey = maxy - miny;
int meghyas=1;
while ((sizey / meghyas > 500) || (sizex / meghyas > 500))
{
meghyas++;
}
IM.Width = (int) (sizex/meghyas);
IM.Height = (int) (sizey/meghyas);
//Start Of drawing
IM.Show();
System.Drawing.Graphics graphicsObj;
graphicsObj = IM.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Green, 5);
Rectangle myRectangle = new Rectangle(0, 0, 10, 10);
graphicsObj.DrawEllipse(myPen, myRectangle);
}
You have to show form IM first:
Form IM = new Form();
IM.FormBorderStyle = FormBorderStyle.FixedSingle;
IM.Width = 500;
IM.Height = 500;
IM.Show();
System.Drawing.Graphics graphicsObj;
graphicsObj = IM.CreateGraphics();
Pen myPen = new Pen(System.Drawing.Color.Green, 5);
Rectangle myRectangle = new Rectangle(0, 0, 10, 10);
graphicsObj.DrawEllipse(myPen, myRectangle);

How to Print images on paper using PrintDocument

My problem is that is that my code prints the images overlapping each other. I do not know how to change the x and y positions. The printer should print 3 images per row and then move to the next row.
private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
for (int serial = 0; serial < SaveBeforePrint.Count; serial++)
{
String intercharacterGap = "0";
String str = '*' + SaveBeforePrint[serial].ToUpper() + '*';
int strLength = str.Length;
for (int i = 0; i < SaveBeforePrint[serial].Length; i++)
{
string barcodestring = SaveBeforePrint[serial].ToUpper();
if (alphabet39.IndexOf(barcodestring[i]) == -1 || barcodestring[i] == '*')
{
e.Graphics.DrawString("INVALID BAR CODE TEXT", Font, Brushes.Red, 10, 10);
return;
}
}
String encodedString = "";
for (int i = 0; i < strLength; i++)
{
if (i > 0)
encodedString += intercharacterGap;
encodedString += coded39Char[alphabet39.IndexOf(str[i])];
}
int encodedStringLength = encodedString.Length;
int widthOfBarCodeString = 0;
double wideToNarrowRatio = 3;
if (align != AlignType.Left)
{
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
widthOfBarCodeString += (int)(wideToNarrowRatio * (int)weight);
else
widthOfBarCodeString += (int)weight;
}
}
int x = 0;
int wid = 0;
int yTop = 0;
SizeF hSize = e.Graphics.MeasureString(headerText, headerFont);
SizeF fSize = e.Graphics.MeasureString(code, footerFont);
int headerX = 0;
int footerX = 0;
int printonpage = 0;
if (align == AlignType.Left)
{
x = leftMargin;
headerX = leftMargin;
footerX = leftMargin;
}
else if (align == AlignType.Center)
{
x = (Width - widthOfBarCodeString) / 2;
headerX = (Width - (int)hSize.Width) / 2;
footerX = (Width - (int)fSize.Width) / 2;
}
else
{
x = Width - widthOfBarCodeString - leftMargin;
headerX = Width - (int)hSize.Width - leftMargin;
footerX = Width - (int)fSize.Width - leftMargin;
}
if (showHeader)
{
yTop = (int)hSize.Height + topMargin;
e.Graphics.DrawString(headerText, headerFont, Brushes.Black, headerX, topMargin);
}
else
{
yTop = topMargin;
}
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
wid = (int)(wideToNarrowRatio * (int)weight);
else
wid = (int)weight;
e.Graphics.FillRectangle(i % 2 == 0 ? Brushes.Black : Brushes.White, x, yTop, wid, height);
x += wid;
}
yTop += height;
if (showFooter)
e.Graphics.DrawString(SaveBeforePrint[serial], footerFont, Brushes.Black, footerX, yTop);
}
}
Desired output :
I am getting :
As you can see the last digit is overlapping. I want to draw it next to the previous one
I have observed the code and found the issue.. in panel1_print u are not incrementing the values properly..
I have made the required changes now u will get the 4 bar in a line and 5th one in another line - check the attached image.
just replace ur panel1_Paint with this new code thats it you can find the changes..
I have marked them as
//start changes by Deepak
..
..
..
//end changes by Deepak
and also declare two variables loopValX and loopValY as int
here is the code..
private void panel1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
int loopValX = 0;
int loopValY = -150;
for (int serial = 0; serial < SaveBeforePrint.Count; serial++)
{
String intercharacterGap = "0";
String str = '*' + SaveBeforePrint[serial].ToUpper() + '*';
int strLength = str.Length;
for (int i = 0; i < SaveBeforePrint[serial].Length; i++)
{
string barcodestring = SaveBeforePrint[serial].ToUpper();
if (alphabet39.IndexOf(barcodestring[i]) == -1 || barcodestring[i] == '*')
{
e.Graphics.DrawString("INVALID BAR CODE TEXT", Font, Brushes.Red, 10, 10);
return;
}
}
String encodedString = "";
for (int i = 0; i < strLength; i++)
{
if (i > 0)
encodedString += intercharacterGap;
encodedString += coded39Char[alphabet39.IndexOf(str[i])];
}
int encodedStringLength = encodedString.Length;
int widthOfBarCodeString = 0;
double wideToNarrowRatio = 3;
if (align != AlignType.Left)
{
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
widthOfBarCodeString += (int)(wideToNarrowRatio * (int)weight);
else
widthOfBarCodeString += (int)weight;
}
}
SizeF hSize = e.Graphics.MeasureString(headerText, headerFont);
SizeF fSize = e.Graphics.MeasureString(SaveBeforePrint[serial], footerFont);
int headerX = 0;
int footerX = 0;
if (align == AlignType.Left)
{
x = leftMargin;
headerX = leftMargin;
footerX = leftMargin;
}
else if (align == AlignType.Center)
{
x = (Width - widthOfBarCodeString) / 2;
headerX = (Width - (int)hSize.Width) / 2;
footerX = (Width - (int)fSize.Width) / 2;
}
else
{
x = Width - widthOfBarCodeString - leftMargin;
headerX = Width - (int)hSize.Width - leftMargin;
footerX = Width - (int)fSize.Width - leftMargin;
}
if (showHeader)
{
y = (int)hSize.Height + topMargin;
e.Graphics.DrawString(headerText, headerFont, Brushes.Black, headerX, topMargin);
}
else
{
y = topMargin;
}
//start changes by Deepak
if (serial % 4 == 0)
{
loopValX = 0;
loopValY += 150;
}
else
{
loopValX += 150;
}
x += loopValX;
y += loopValY;
footerX += loopValX;
//end changes by Deepak
for (int i = 0; i < encodedStringLength; i++)
{
if (encodedString[i] == '1')
wid = (int)(wideToNarrowRatio * (int)weight);
else
wid = (int)weight;
e.Graphics.FillRectangle(i % 2 == 0 ? Brushes.Black : Brushes.White, x, y, wid, height);
x += wid;
}
y += height;
if (showFooter)
e.Graphics.DrawString(SaveBeforePrint[serial], footerFont, Brushes.Black, footerX, y);
}
}
You Should do it with the help of a DataGridView (That Contains Images in a Column).
The Images Will Then Print in each new row or column (by modifying as your desire)
The Following Class will do your work by passing it the whole DataGridView And Header in its constructor.
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Linq;
namespace Waqas
{
internal class ClsPrint
{
#region Variables
private int iCellHeight = 0; //Used to get/set the datagridview cell height
private int iTotalWidth = 0; //
private int iRow = 0; //Used as counter
private bool bFirstPage = false; //Used to check whether we are printing first page
private bool bNewPage = false; // Used to check whether we are printing a new page
private int iHeaderHeight = 0; //Used for the header height
private StringFormat strFormat; //Used to format the grid rows.
private ArrayList arrColumnLefts = new ArrayList(); //Used to save left coordinates of columns
private ArrayList arrColumnWidths = new ArrayList(); //Used to save column widths
private PrintDocument _printDocument = new PrintDocument();
private DataGridView gw = new DataGridView();
private string _ReportHeader;
#endregion
public ClsPrint(DataGridView gridview, string ReportHeader)
{
_printDocument.DefaultPageSettings.Landscape = true;
_printDocument.DefaultPageSettings.PaperSize.RawKind = (int)PaperKind.A4;
_printDocument.DefaultPageSettings.Margins = new Margins(30, 30, 30, 30);
//_printDocument.DefaultPageSettings.PaperSize.PaperName = "A4";
_printDocument.PrintPage += new PrintPageEventHandler(_printDocument_PrintPage);
_printDocument.BeginPrint += new PrintEventHandler(_printDocument_BeginPrint);
gw = gridview;
_ReportHeader = ReportHeader;
}
public void PrintForm()
{
//Open the print preview dialog
PrintPreviewDialog objPPdialog = new PrintPreviewDialog();
objPPdialog.Document = _printDocument;
objPPdialog.ShowIcon = false;
objPPdialog.Text = "Print Preview";
objPPdialog.WindowState = FormWindowState.Maximized;
objPPdialog.ShowDialog();
}
private void _printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
//try
//{
//Set the left margin
int iLeftMargin = e.MarginBounds.Left;
//Set the top margin
int iTopMargin = e.MarginBounds.Top;
//Whether more pages have to print or not
bool bMorePagesToPrint = false;
int iTmpWidth = 0;
//For the first page to print set the cell width and header height
if (bFirstPage)
{
foreach (DataGridViewColumn GridCol in gw.Columns)
{
iTmpWidth = ((int) (Math.Floor((double) ((double) GridCol.Width/
(double) iTotalWidth*(double) iTotalWidth*
((double) e.MarginBounds.Width/(double) iTotalWidth)))));
iHeaderHeight = (int) (e.Graphics.MeasureString(GridCol.HeaderText,
GridCol.InheritedStyle.Font, iTmpWidth).Height) + 60;
// Save width and height of headers
arrColumnLefts.Add(iLeftMargin);
arrColumnWidths.Add(iTmpWidth);
iLeftMargin += iTmpWidth;
}
}
//Loop till all the grid rows not get printed
while (iRow <= gw.Rows.Count - 1)
{
DataGridViewRow GridRow = gw.Rows[iRow];
//Set the cell height
iCellHeight = GridRow.Height + 30;
int iCount = 0;
//Check whether the current page settings allows more rows to print
if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
{
bNewPage = true;
bFirstPage = false;
bMorePagesToPrint = true;
break;
}
else
{
if (bNewPage)
{
//Draw Header
e.Graphics.DrawString(_ReportHeader,
new Font("Calibri Light", 20, FontStyle.Bold),
new SolidBrush(Color.Black), e.MarginBounds.Left,
e.MarginBounds.Top+20 - e.Graphics.MeasureString(_ReportHeader,
new Font(gw.Font, FontStyle.Bold),
e.MarginBounds.Width).Height - 13);
String strDate = DateTime.Now.ToString("dd-MMM-yy hh:mm tt");
//Draw Date
e.Graphics.DrawString(strDate,
new Font("Calibri Light", 12, FontStyle.Bold), Brushes.Black,
e.MarginBounds.Left-20 +
(e.MarginBounds.Width - e.Graphics.MeasureString(strDate,
new Font(gw.Font, FontStyle.Bold),
e.MarginBounds.Width).Width),
e.MarginBounds.Top+30 - e.Graphics.MeasureString(_ReportHeader,
new Font(new Font(gw.Font, FontStyle.Bold),
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
//Draw Columns
iTopMargin = e.MarginBounds.Top+30;
DataGridViewColumn[] _GridCol = new DataGridViewColumn[gw.Columns.Count];
int colcount = 0;
//Convert ltr to rtl
foreach (DataGridViewColumn GridCol in gw.Columns)
{
_GridCol[colcount++] = GridCol;
}
for (int i =0; i <= (_GridCol.Count() - 1); i++)
{
e.Graphics.FillRectangle(new SolidBrush(Color.Gainsboro),
new Rectangle((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawRectangle(new Pen(Color.Black),
new Rectangle((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawString(_GridCol[i].HeaderText,
new Font("Calibri Light", 12, FontStyle.Bold),
new SolidBrush(Color.Black),
new RectangleF((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iHeaderHeight), strFormat);
iCount++;
}
bNewPage = false;
iTopMargin += iHeaderHeight;
}
iCount = 0;
DataGridViewCell[] _GridCell = new DataGridViewCell[GridRow.Cells.Count];
int cellcount = 0;
//Convert ltr to rtl
foreach (DataGridViewCell Cel in GridRow.Cells)
{
_GridCell[cellcount++] = Cel;
}
//Draw Columns Contents
for (int i =0; i <=(_GridCell.Count() - 1); i++)
{
if (_GridCell[i].Value != null)
{
if (_GridCell[i].GetType() != typeof (DataGridViewImageCell))
{
e.Graphics.DrawString(_GridCell[i].FormattedValue.ToString(),
new Font("Calibri Light", 10),
new SolidBrush(Color.Black),
new RectangleF((int) arrColumnLefts[iCount],
(float) iTopMargin,
(int) arrColumnWidths[iCount], (float) iCellHeight),
strFormat);
}
else
{
Image img = Common.byteArrayToImage((byte[]) _GridCell[i].Value);
Rectangle m = new Rectangle((int) arrColumnLefts[iCount],iTopMargin,
(int) arrColumnWidths[iCount], iCellHeight);
if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
}
e.Graphics.DrawImage(img, m);
}
}
//Drawing Cells Borders
e.Graphics.DrawRectangle(new Pen(Color.Black),
new Rectangle((int) arrColumnLefts[iCount], iTopMargin,
(int) arrColumnWidths[iCount], iCellHeight));
iCount++;
}
}
iRow++;
iTopMargin += iCellHeight;
}
//If more lines exist, print another page.
if (bMorePagesToPrint)
e.HasMorePages = true;
else
e.HasMorePages = false;
//}
//catch (Exception exc)
//{
// KryptonMessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
// MessageBoxIcon.Error);
//}
}
private void _printDocument_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
try
{
strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Center;
strFormat.LineAlignment = StringAlignment.Center;
strFormat.Trimming = StringTrimming.EllipsisCharacter;
arrColumnLefts.Clear();
arrColumnWidths.Clear();
iCellHeight = 0;
iRow = 0;
bFirstPage = true;
bNewPage = true;
// Calculating Total Widths
iTotalWidth = 0;
foreach (DataGridViewColumn dgvGridCol in gw.Columns)
{
iTotalWidth += dgvGridCol.Width;
}
}
catch (Exception ex)
{
KryptonMessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
as
ClsPrint _ClsPrint = new ClsPrint(myDataGridView, "MyHeader");
_ClsPrint.PrintForm();
Your position variables are being declared inside the loop, meaning that they are reset for each pass through the loop. Keep position variables for X and Y outside of the loop over serial and adjust it for the total width (and height, if you start a new row of barcodes) of each barcode.

Categories