The best way to print info from a dgv - c#

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.

Related

How to print data to next page in C# PrintDocument

I have written this code to print a lab report. It works fine but when I click on the print button and if the data of the report is more than one page it doesn't create the next page. Now I want the multiple-page setting I am totally confused about how to do it.
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int position = 60;
for (int j = NoOfItemsTill; j < types.Count; j++)
{
e.Graphics.DrawString(types[j], new Font("Arial", 16, FontStyle.Bold), Brushes.Black, new Point(30, yposition - 30 + position));
e.Graphics.DrawImage(imae, 33, yposition + position, imae.Width, imae.Height);
e.Graphics.DrawString("Test", new Font("Arial", 12, FontStyle.Bold), Brushes.Black, new Point(40, yposition + 5 + position));
e.Graphics.DrawString("Normal Value", new Font("Arial", 12, FontStyle.Bold), Brushes.Black, new Point(310, yposition + 5 + position));
e.Graphics.DrawString("Result ", new Font("Arial", 12, FontStyle.Bold), Brushes.Black, new Point(560, yposition + 5 + position));
if (checkBox1showprise.Checked == true)
{
e.Graphics.DrawString("Price ", new Font("Arial", 12, FontStyle.Bold), Brushes.Black, new Point(700, yposition + 5 + position));
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells[1].Value.ToString() == types[j])
{
e.Graphics.DrawString(dataGridView1.Rows[i].Cells[2].Value.ToString(), new Font("Arial", 12, FontStyle.Regular), Brushes.Black, new Point(30, yposition + 50 + position));
e.Graphics.DrawString(dataGridView1.Rows[i].Cells[3].Value.ToString(), new Font("Arial", 12, FontStyle.Regular), Brushes.Black, new Point(310, yposition + 50 + position));
e.Graphics.DrawString(dataGridView1.Rows[i].Cells[4].Value.ToString(), new Font("Arial", 12, FontStyle.Regular), Brushes.Black, new Point(560, yposition + 50 + position));
if (checkBox1showprise.Checked == true)
{
e.Graphics.DrawString(dataGridView1.Rows[i].Cells[5].Value.ToString(), new Font("Arial", 12, FontStyle.Regular), Brushes.Black, new Point(700, yposition + 50 + position));
}
position += 25;
}
}
yposition = yposition + 100;
}
// reset vaerables
// NoOfItemPerpage = 0;
NoOfItemsTill = 0;
}
I want that after every 5 elements of my array, the next page is created and the data is printed onto the next page.

WPF - print datagrid contents

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);
}
}

Printing receipt from the listview

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");

Program printing resized images on different OS version

I have a working code, on both the target machine, and my own machine. However, my machine is a W10, and the target is a W7. The code below should draw 5 barcodes on the right half of the page, however, when I use it on the target machine, one of two scenarios happen, depending on how I change the code. If I make the width of the barcode too big, it will go beyond the edge of the page and it will not be readable. If I make the width slightly too small, it resizes the whole barcode, and it becomes to small, again unreadable. I assume that this is a problem with the print drivers in which, they are different for both W10 and W7 (I used the same printer on both machines, same settings as well).
Is there a problem with my code and how do I change it?
private void DocumentDrucker_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Graphics graphic = e.Graphics;
//SolidBrush brush = new SolidBrush(Color.Black);
Font font = new Font("Courier New", 80, FontStyle.Bold);
Font fontK = new Font("Courier New", 30, FontStyle.Bold);
Font fontKleinst = new Font("Courier New", 15, FontStyle.Bold);
float pageWidth = e.PageSettings.PrintableArea.Width;
float pageHeight = e.PageSettings.PrintableArea.Height;
float fontHeight = font.GetHeight();
int startX = 0;
int startY = 0;
int offsetY = 0;
float imageH = Properties.Resources.pfeilO.Height;
float imageW = Properties.Resources.pfeilO.Width;
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
//var imagePoint = new Point(Convert.ToInt32(pageWidth * 0.55), offsetY);
var barcodePoint = new Point(Convert.ToInt32(pageWidth * 0.66), 0);
for (; elemente < ZumDrucken.Items.Count; elemente++)
{
var currentItem = ZumDrucken.Items[elemente];
graphic.DrawString(currentItem.Text.Substring(4, 3), fontK, Brushes.Black, startX, startY +offsetY+20);
graphic.DrawString("Typ:"+currentItem.Text.Substring(0,3), fontKleinst, Brushes.Black, startX, (startY + offsetY + 30+fontK.Height));
graphic.DrawString(currentItem.Text.Substring(7), font, Brushes.Black, (startX+75), startY + offsetY);
var currentImage = Properties.Resources.pfeilU;
bool lastCharIsAOne = currentItem.Text[currentItem.Text.Length - 1] == '1';
if (currentItem.Checked == lastCharIsAOne)
{
currentImage = Properties.Resources.pfeilO;
}
graphic.DrawImage(currentImage, Convert.ToInt32((pageWidth * 0.55)), offsetY+20, imageW, imageH);
b.EncodedImage?.Dispose();
//b.Encode(TYPE.CODE128A, "SBD" + currentItem.Text.Substring(0, 3) + currentItem.Text.Substring(4), Color.Black, Color.Transparent,Convert.ToInt32(pageWidth-50), Convert.ToInt32(pageHeight * 0.151));
b.Encode(TYPE.CODE128A, "SBD" + currentItem.Text.Substring(0, 3) + currentItem.Text.Substring(4), Color.Black, Color.Transparent, 570, 135);
barcodePoint.Y = offsetY;
graphic.DrawImage(b.EncodedImage, barcodePoint);
offsetY = offsetY + 163;
if (offsetY >= pageWidth-120)
{
e.HasMorePages = true;
offsetY = 0;
elemente++;
graphic.Dispose();
b.Dispose();
font.Dispose();
fontK.Dispose();
fontKleinst.Dispose();
return;
}
else
{
e.HasMorePages = false;
}
}
graphic.Dispose();
b.Dispose();
font.Dispose();
fontK.Dispose();
fontKleinst.Dispose();
}
Here is also the code where I set all the margins to 0, and change the paper mode to landscape.
private void Drucken_Click(object sender, EventArgs e)
{
DocumentDrucker.DocumentName = "Dokument";
elemente = 0;
DruckDialog.Document = DocumentDrucker;
DocumentDrucker.DefaultPageSettings.Landscape = true;
DocumentDrucker.DefaultPageSettings.Margins.Top = 0;
DocumentDrucker.DefaultPageSettings.Margins.Left = 0;
DocumentDrucker.DefaultPageSettings.Margins.Right = 0;
DocumentDrucker.DefaultPageSettings.Margins.Bottom = 0;
if (DruckDialog.ShowDialog() == DialogResult.OK)
DocumentDrucker.Print();
}

string.Format does not made alignment with fixed width

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:

Categories