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);
}
Related
I Have looked around and I have not found a solid answeer to this question. I am trying to print my datagrid content when I press a button, the main problem is that my datagrid has too much data and only whatever is shown in the screen is printing. I need It to print all data and if the data does not fit in current page create a mew page and print the rest.
Here is my solution printing Data Grid View using System.Drawing.Printing
using System.Drawing.Printing;
private int PageCounter { get; set; } = 1;
private int RowCounter { get; set; }
Print Button
private void BtnPrint_Click(object sender, EventArgs e)
{
PrintDocument printDoc = new PrintDocument();
IQueryable<PaperSize> paperSizes = printDoc.PrinterSettings.PaperSizes.Cast<PaperSize>().AsQueryable();
printDoc.DefaultPageSettings.PaperSize = paperSizes.First(ps => ps.Kind == PaperKind.A4);
printDoc.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
pageCounter = 1;
printDoc.PrintPage += PrintDoc_PrintPage;
printDoc.Print();
}
Print Method
private void Print_Document(object sender, PrintPageEventArgs e)
{
if (e.Graphics == null)
throw new Exception("Unable to find page Graphics!");
int left = 30;
int cellLeft = left;
int top = 50;
int cellWidth = 0;
int headerHeight = 30;
string headerName = string.Empty;
string cellValue = string.Empty;
Rectangle rect = new();
int pageWidth = e.PageSettings.PaperSize.Width - 60;
int pageHeight = e.PageSettings.PaperSize.Height - 100;
Graphics g = e.Graphics;
Font font = new(FontFamily, 9);
Pen p = new(Brushes.Black, 1f);
Pen borderP = new(new SolidBrush(Color.FromArgb(240, 240, 240)), 1f);
StringFormat stringFormatCenter = new()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
StringFormat stringFormatRight = new()
{
Alignment = StringAlignment.Far,
LineAlignment = StringAlignment.Center
};
StringFormat stringFormatLeft = new()
{
LineAlignment = StringAlignment.Center
};
if (PageCounter == 1)
{
g.DrawRectangle(p, new Rectangle(left, top, pageWidth, 30));
top += 30;
g.DrawRectangle(p, new Rectangle(left, top, pageWidth, 30));
top += 30;
g.DrawRectangle(p, new Rectangle(left, top, pageWidth, 30));
top += 30;
g.DrawRectangle(p, new Rectangle(left, top, pageWidth / 2, 30));
g.DrawRectangle(p, new Rectangle(left + (pageWidth / 2), top, pageWidth / 2, 30));
top += 30;
top = 50;
g.DrawString
("Company Name"
, new Font(FontFamily, 14f, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth, 30)
, stringFormatCenter);
top += 30;
g.DrawString
("Business Type"
, new Font(FontFamily, 12f, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth, 30)
, stringFormatCenter);
top += 30;
g.DrawString
("Report Name"
, new Font(FontFamily, 12f, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth, 30)
, stringFormatCenter);
top += 30;
g.DrawString
("User Name: " + SelectedUser.Name
, new Font(FontFamily, 9, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth / 2, 30)
, stringFormatLeft);
g.DrawString
("Report Date: " + DateTime.Now.ToString("dd-mm-yyyy hh:mm:ss")
, new Font(FontFamily, 9, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left + (pageWidth / 2), top, pageWidth / 2, 30)
, stringFormatRight);
top += 30;
g.DrawString
("Login Id: " + SelectedUser.LoginId
, new Font(FontFamily, 9, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth / 2, 30)
, stringFormatLeft);
g.DrawString
("Printed By: " + LoggedUser.Name
, new Font(FontFamily, 9, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left + (pageWidth / 2), top, pageWidth / 2, 20)
, stringFormatRight);
top += 30;
g.DrawString
("Rights detail as follows:"
, new Font(FontFamily, 8, FontStyle.Bold)
, Brushes.Black
, new Rectangle(left, top, pageWidth, 20)
, stringFormatLeft);
top += 20;
}
g.FillRectangle(new SolidBrush(Color.FromArgb(234, 239, 250)), new Rectangle(left, top, pageWidth, headerHeight));
foreach (string name in PrintableRights.First().GetType().GetProperties().Select(p => p.Name))
{
if (name.Equals("SrNo"))
{
headerName = "Sr #";
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 8);
}
else if (name.Equals("Code"))
{
headerName = "Code";
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 20);
}
else if (name.Equals("Name"))
{
headerName = "Name";
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 57);
}
else if (name.Equals("HasRight"))
{
headerName = "Right";
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 15);
}
rect = new Rectangle(cellLeft, top, cellWidth, headerHeight);
g.DrawString(headerName, new Font(FontFamily, 10, FontStyle.Bold), Brushes.Black, rect, stringFormatLeft);
cellLeft += cellWidth;
}
top += headerHeight;
cellLeft = left;
while (RowCounter < PrintableRights.Count())
{
object row = PrintableRights.ElementAt(RowCounter);
cellLeft = left;
foreach (string name in row.GetType().GetProperties().Select(prop => prop.Name))
{
if (name.Equals("SrNo"))
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 8);
else if (name.Equals("Code"))
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 20);
else if (name.Equals("Name"))
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 57);
else if (name.Equals("HasRight"))
cellWidth = Convert.ToInt32(Convert.ToDecimal(pageWidth) / 100 * 15);
rect = new Rectangle(cellLeft, top, cellWidth, 20);
g.DrawRectangle(borderP, rect);
PropertyInfo? prop = row.GetType().GetProperty(name);
if (prop != null)
{
if (prop.PropertyType == typeof(bool))
{
var val = prop.GetValue(row, null);
if (val != null && (bool)val)
g.DrawString("Yes", font, Brushes.Black, rect, stringFormatLeft);
else if (val != null)
g.DrawString("No", font, Brushes.Black, rect, stringFormatLeft);
}
else if (prop.PropertyType == typeof(int))
{
var val = prop.GetValue(row, null);
if (val != null)
g.DrawString(((int)val).ToString("N0"), font, Brushes.Black, rect, stringFormatRight);
else
g.DrawString(string.Empty, font, Brushes.Black, rect, stringFormatRight);
}
else if (prop.PropertyType == typeof(string))
{
var val = prop.GetValue(row, null);
if(val != null)
g.DrawString((string)val, font, Brushes.Black, rect, stringFormatLeft);
else
g.DrawString(string.Empty, font, Brushes.Black, rect, stringFormatLeft);
}
}
cellLeft += cellWidth;
}
top += 20;
if (RowCounter < PrintableRights.Count() - 1)
{
if (top > pageHeight - 10)
{
RowCounter++;
break;
}
}
RowCounter++;
}
if (RowCounter <= PrintableRights.Count() - 1)
{
if (top + 10 > pageHeight)
{
g.DrawString("Continue....", new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 200, e.PageSettings.PaperSize.Height - 60);
g.DrawString("Page # " + PageCounter.ToString(), new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 100, e.PageSettings.PaperSize.Height - 60);
PageCounter++;
e.HasMorePages = true;
}
}
else if (e.HasMorePages)
{
g.DrawString("Continue....", new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 200, e.PageSettings.PaperSize.Height - 60);
g.DrawString("Page # " + PageCounter.ToString(), new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 100, e.PageSettings.PaperSize.Height - 60);
PageCounter++;
}
else
{
g.DrawString("Last Page.", new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 200, e.PageSettings.PaperSize.Height - 60);
g.DrawString("Page # " + PageCounter.ToString(), new Font(FontFamily, 7f), Brushes.Black, e.PageSettings.PaperSize.Width - 100, e.PageSettings.PaperSize.Height - 60);
}
}
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:
I have a card that has10cm height and 15cm width. I am trying to print a string on the following coordinates: 1,5cm from top to bottom and 3,5cm from the left to right. Until now i tried to use the bellow code that i found on msdn but with no luck. The code that i am using is :
System.IO.StreamReader fileToPrint;
System.Drawing.Font printFont;
private void printButton_Click(object sender, EventArgs e)
{
string printPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
fileToPrint = new System.IO.StreamReader(printPath + #"\myFile.txt");
printFont = new System.Drawing.Font("Arial", 10);
printDocument1.Print();
fileToPrint.Close();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
float yPos = 0f;
int count = 0;
float leftMargin = e.MarginBounds.Left;
float topMargin = e.MarginBounds.Top;
string line = null;
float linesPerPage = e.MarginBounds.Height/printFont.GetHeight(e.Graphics);
while (count < linesPerPage)
{
line = fileToPrint.ReadLine();
if (line == null)
{
break;
}
yPos = topMargin + count * printFont.GetHeight(e.Graphics);
e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
count++;
}
if (line != null)
{
e.HasMorePages = true;
}
}
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.
It happen only when I resize the form when the program is running.
I click the "-" and the program is minimised to the taskbar, then I see the error/exception message.
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
if (!_addingLines)
SplitText(this.Text);
if (_backBmpBU != null)
this._backBmp = MakeBackBmp(_backBmpBU);
if (this.BitmapModus)
{
UpdateBitmap();
}
}
private void UpdateBitmap()
{
if (_lines != null && _lines.Length > 0)
{
SizeF sz = new SizeF(0, 0);
float lineOrigHeight = sz.Height;
using (Graphics g = this.CreateGraphics())
{
sz = g.MeasureString("Teststring", this.Font);
if (this._additionalSpaceBetweenLines > 0)
sz = new SizeF(sz.Width, sz.Height + this._additionalSpaceBetweenLines);
}
this._textHeight = sz.Height * _lines.Length;
if (_bmp != null)
{
_bmp.Dispose();
_bmp = null;
}
try
{
if (this._textHeight > MAXHEIGHT)
throw new Exception("Text too long, for BitmapMode.");
_bmp = new Bitmap(this.ClientSize.Width, (int)Math.Ceiling(this._textHeight));
using (Graphics g = Graphics.FromImage(_bmp))
{
//set it to value you like...
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
using (SolidBrush b = new SolidBrush(this.ForeColor))
{
for (int i = 0; i < _lines.Length; i++)
{
SolidBrush bb = b;
if (TrimText)
_lines[i] = _lines[i].Trim();
sz = g.MeasureString(_lines[i], this.Font);
lineOrigHeight = sz.Height;
if (this._additionalSpaceBetweenLines > 0)
sz = new SizeF(sz.Width, sz.Height + this._additionalSpaceBetweenLines);
_posX = 0;
if (this.TextLayoutCentered)
_posX = (this.ClientSize.Width - sz.Width) / 2.0F;
bool drect = false;
bool colw = false;
int indx = -1;
int length = 0;
string textToFind = "";
Color fc = this.ForeColor;
Color bc = Color.Transparent;
Color rc = Color.Transparent;
if (Words != null && Words.Count > 0)
{
for (int ii = 0; ii < Words.Count; ii++)
{
if (_lines[i].Contains(Words[ii].WordOrText))
{
bb = new SolidBrush(Words[ii].ForeColor);
if (Words[ii].DrawRect)
drect = true;
if (Words[ii].ColorOnlyThisWord)
colw = true;
indx = _lines[i].IndexOf(Words[ii].WordOrText);
length = Words[ii].WordOrText.Length;
textToFind = Words[ii].WordOrText;
fc = Words[ii].ForeColor;
bc = Words[ii].BackColor;
rc = Words[ii].RectColor;
drect = Words[ii].DrawRect;
}
}
}
if (colw)
{
//reset b and create a new color brush
if (bb.Equals(b) == false)
bb.Dispose();
bb = b;
string ftext = _lines[i];
float cPosX = _posX;
using (SolidBrush bbb = new SolidBrush(fc))
{
while (indx > -1)
{
if (indx > 0)
g.DrawString(ftext.Substring(0, indx), this.Font, bb, new PointF(cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
cPosX += g.MeasureString(ftext.Substring(0, indx), this.Font).Width;
SizeF sfWord = g.MeasureString(ftext.Substring(indx, length), this.Font);
if (bc.ToArgb().Equals(Color.Transparent.ToArgb()) == false)
{
using (SolidBrush bbbb = new SolidBrush(bc))
g.FillRectangle(bbbb, cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sfWord.Width, sfWord.Height);
}
g.DrawString(ftext.Substring(indx, length), this.Font, bbb, new PointF(cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
cPosX += sfWord.Width;
ftext = ftext.Substring(indx + length);
if (textToFind.Length > 0)
indx = ftext.IndexOf(textToFind);
else
indx = -1;
}
if (ftext.Length > 0)
g.DrawString(ftext, this.Font, bb, new PointF(cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
}
}
else
{
if (bc.ToArgb().Equals(Color.Transparent.ToArgb()) == false)
{
using (SolidBrush bbbb = new SolidBrush(bc))
g.FillRectangle(bbbb, _posX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sz.Width, lineOrigHeight);
}
g.DrawString(_lines[i], this.Font, bb, new PointF(_posX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
}
if (drect)
{
if (rc.ToArgb().Equals(Color.Transparent.ToArgb()) == false)
using (Pen p = new Pen(rc))
g.DrawRectangle(p, _posX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sz.Width, lineOrigHeight);
}
if (bb.Equals(b) == false)
bb.Dispose();
if (DrawRect)
{
using (Pen p = new Pen(this.ForeColor))
{
if (DrawRectAroundText)
g.DrawRectangle(p, _posX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sz.Width, lineOrigHeight);
else
g.DrawRectangle(p, 0, sz.Height * i + _additionalSpaceBetweenLines / 2F, this.ClientSize.Width - 1, lineOrigHeight);
}
}
}
}
}
}
catch (Exception ex)
{
if (_bmp != null)
{
_bmp.Dispose();
_bmp = null;
}
this.BitmapModus = false;
//MessageBox.Show(ex.Message + " switching to Dynamic-Draw-Mode.");
OnSwitchModeOnError();
}
}
}
When the program is running and i minimize the form to the taskbar im getting exception:
Parameter is not valid
The full exception message:
System.ArgumentException was caught
HResult=-2147024809
Message=Parameter is not valid.
Source=System.Drawing
StackTrace:
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)
at ScrollLabelTest.ScrollLabel.UpdateBitmap() in e:\scrolllabel\ScrollLabel\ScrollLabel\ScrollLabel.cs:line 601
InnerException:
I had the same problem, with a huge list of errors in the Just-In-Time-Debugger. After several hours of searching I found my own way. Try this, no more exceptions!!
private void picMinimize_Click(object sender, EventArgs e)
{
try
{
panelUC.Visible = false; //change visible status of your form, etc.
this.WindowState = FormWindowState.Minimized; //minimize
minimizedFlag = true; //set a global flag
}
catch (Exception)
{
}
}
private void mainForm_Resize(object sender, EventArgs e)
{
//check if form is minimized, and you know that this method is only called if and only if the form get a change in size, meaning somebody clicked in the taskbar on your application
if (minimizedFlag == true)
{
panelUC.Visible = true; //make your panel visible again! thats it
minimizedFlag = false; //set flag back
}
}
Thumb up!