please some one help me , i have to print a document in multiple pages in c#, i went through internet then used this code but not working, (loop is again start after printing one page )
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
try
{
Graphics graphic = e.Graphics;
SolidBrush brush = new SolidBrush(Color.Black);
Font font = new Font("Courier New", 12);
float pageWidth = e.PageSettings.PrintableArea.Width;
float pageHeight = e.PageSettings.PrintableArea.Height;
float fontHeight = font.GetHeight();
int startX = 40;
int startY = 30;
int offsetY = 40;
for (int i = 0; i < 100; i++ )
{
graphic.DrawString("Line: " + i, font, brush, startX, startY + offsetY);
offsetY += (int)fontHeight;
if (offsetY >= pageHeight)
{
e.HasMorePages = true;
offsetY = 0;
return;
}
else
{
e.HasMorePages = false;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Whenever you set e.HasMorePages = true, it will just fire the printDocument1_PrintPage() event handler again. You need to keep a class variable for i, so that it won't restart at 0 every time the next page prints. Don't declare it locally inside the event handler.
private class MyPrinter
{
private int i = 0;
private void Print()
{
i = 0;
printDocument1.Print();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
.....
.....
.....
while (i < 100)
{
graphic.DrawString("Line: " + i, font, brush, startX, startY + offsetY);
offsetY += (int)fontHeight;
if (offsetY >= pageHeight)
{
e.HasMorePages = true;
offsetY = 0;
return;
}
else
{
e.HasMorePages = false;
}
i = i + 1;
}
}
}
Related
when I click on print preview button. it shows my listed items. but when I close print preview screen and add some more items and click on print preview. it shows only that items which I enter later. I clear my old added Items.
here is my code which I'm trying
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawString("Date: " + DateTime.Now.ToShortDateString(), new Font("Calibri", 11, FontStyle.Regular), Brushes.Black, new Point(300, 150));
e.Graphics.DrawString("Customer Name: " + customername.Text.Trim(), new Font("Calibri", 11, FontStyle.Regular), Brushes.Black, new Point(20, 150));
int yPos = 200;
int xPos = 20;
int brandyPos = 180;
for (int i = numberOfItemsPrintedSoFar; i < beltlist.Count; i++)
{
numberOfItemsPerPage++;
if (numberOfItemsPerPage <= 15 && count <= 3)
{
numberOfItemsPrintedSoFar++;
if (numberOfItemsPrintedSoFar <= beltlist.Count)
{
e.Graphics.DrawString(beltlist[i].BrandName, new Font("Calibri", 11, FontStyle.Regular), Brushes.Black, new Point(xPos, brandyPos));
brandyPos = yPos + 20;
e.Graphics.DrawString(beltlist[i].BeltSize.ToString() + "--" + beltlist[i].QTY.ToString(), new Font("Calibri", 11, FontStyle.Regular), Brushes.Black, new Point(20, yPos));
yPos += 20;
}
else
{
e.HasMorePages = false;
}
}
else
{
count++;
yPos = 180;
xPos += 150;
numberOfItemsPerPage = 0;
if (count > 3)
{
e.HasMorePages = true;
xPos = 20;
count = 1;
return;
}
}
}
}
I want to print 50 labels per sheet (5 columns and 10 rows). When it goes to the 11th row it should switch to the next page. I have tried e.hasMorePages in several ways, but sometimes it gets overlapped on the same page.
Here is my code:
private void MakingLabel(int curentIndex,List<BarcodesSpecs> List)
{
int ListRows = List.Count;
BarcodesSpecs barcodesSpecs = List.ElementAt(curentIndex);
BarCode_ItemCode = barcodesSpecs.ItemCodeMain;
BarCode_Description = barcodesSpecs.Description;
BarCode_SalePrice = barcodesSpecs.SalePrice;
BarCode_Size = barcodesSpecs.Size;
BarCode_Colour = barcodesSpecs.Colour;
barCode_LabelToPrint = Convert.ToInt16(barcodesSpecs.QtyToPrint);
}
int xCord = 0, yCord = 0;
int CurentIndex = 0;
int MaxCharactersInString = 26;
private void printBarcodes_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
for (CurentIndex = 0; CurentIndex < BcList.Count; CurentIndex++)
{
MakingLabel(CurentIndex, BcList);
for (int i = 0; i < barCode_LabelToPrint; i++) //// making Copies means How many Labels Of this Item Needed
{
if (xCord >= 750)
{
xCord = 0;
yCord += 115;
}
if (BarCode_Description.Length > MaxCharactersInString)
{
BarCode_Description = BarCode_Description.Substring(0, MaxCharactersInString);
}
e.Graphics.DrawString("ALPIAL SUITING", new Font("Arial", 10, FontStyle.Bold), Brushes.Black, new Point(xCord, yCord + 10));
e.Graphics.DrawString("Rs" + BarCode_SalePrice + "/-", new Font("Arial", 14, FontStyle.Bold), Brushes.Black, new Point(xCord, yCord + 21));
e.Graphics.DrawString("Size: " + BarCode_Size + " Colour: " + BarCode_Colour, new Font("Arial", 07, FontStyle.Regular), Brushes.Black, new Point(xCord, yCord + 42));
e.Graphics.DrawString(BarCode_Description, new Font("Arial", 07, FontStyle.Bold), Brushes.Black, new Point(xCord, yCord + 52));
e.Graphics.DrawString(BarCode_ItemCode, new Font("Arial", 06, FontStyle.Bold), Brushes.Black, new Point(xCord, yCord + 62));
Zen.Barcode.Code128BarcodeDraw barcode = Zen.Barcode.BarcodeDrawFactory.Code128WithChecksum;
e.Graphics.DrawImage(barcode.Draw(BarCode_ItemCode, 25), xCord, yCord + 72);
xCord += 160;
}
}
}
The result I am getting is in the picture, any help will be appreciated thanks!
Somewhere along the line, you will need to check if yCord is beyond the bottom of the page. If it is, you need to set HasMorePages to true and exit the PrintPage handler. It will be called again for the next page. You'll have to keep track of which labels you have already printed outside the PrintPage handler and continue from that point.
Here's a sample I did to simulate labels printing. I only drew a square to represent the label. I had to do a little math to figure out the spacing so you will likely have to adjust this for your situation.
private static void doPrintPreview()
{
var pd = new PrintDocument();
pd.PrintPage += pd_PrintPage;
var prv = new PrintPreviewDialog();
prv.Document = pd;
prv.ShowDialog();
}
//Units are in 1/100 of an inch
private static float leftMargin = 100f; //Page margins
private static float rightMargin = 750f;
private static float topMargin = 100f;
private static float bottomMargin = 1000f;
private static int numLabelsToPrint = 200; //How many we want to print
private static int numLabelsPrinted = 0; //How many we have already printed
private static float labelSizeX = 75; //Label size
private static float labelSizeY = 75f;
private static float labelGutterX = 7.14f; //Space between labels
private static float labelGutterY = 7.5f;
static void pd_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.PageUnit = GraphicsUnit.Display; //Units are 1/100 of an inch
//start at the left and top margin of the page for a new page
float xPos = leftMargin;
float yPos = topMargin;
using (var p2 = new Pen(Brushes.Red, 3.0f))
{
//While there are still labels to print
while (numLabelsPrinted < numLabelsToPrint)
{
//Draw the label (i just drew a square)
e.Graphics.DrawRectangle(Pens.Red, xPos, yPos, labelSizeX, labelSizeY);
numLabelsPrinted++;
//Set the x position for the next label
xPos += (labelSizeX + labelGutterX);
//If the label will be printed beyond the right margin
if ((xPos + labelSizeX) > rightMargin)
{
//Reset the x position back to the left margin
xPos = leftMargin;
//Set the y position for the next row of labels
yPos += (labelSizeY + labelGutterY);
//If the label will be printed beyond the bottom margin
if ((yPos + labelSizeY) > bottomMargin)
{
//Reset the y position back to the top margin
yPos = topMargin;
//If we still have labels to print
if (numLabelsPrinted < numLabelsToPrint)
{
//Tell the print engine we have more labels and then exit.
e.HasMorePages = true;
//Notice after setting HasMorePages to true, we need to exit from the method.
//The print engine will call the PrintPage method again so we can continue
//printing on the next page.
break; //you could also just use return here
}
}
}
}
}
}
Below is a Method which prints Testing string. I am unable to figure out why this gives unlimited new pages with same contents. I need to print a new page after 30th round.
private void PrintSetup(Graphics g, System.Drawing.Printing.PrintPageEventArgs e)
{
float linesPerPage = 0;
int count = 0;
float leftMargin = e.MarginBounds.Left;
float topMargin = e.MarginBounds.Top;
float rightMargin = e.MarginBounds.Right;
float bottomMargin = e.MarginBounds.Bottom;
float Height = e.MarginBounds.Height;
float Width = e.MarginBounds.Width;
float FontHeight = NormalFont.GetHeight();
linesPerPage = Height / NormalFont.GetHeight(e.Graphics);
while (count < linesPerPage)
{
g.DrawString("Test " + count, NormalFont, BlackBrush, leftMargin, topMargin + Line(count));
if (count > 30)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
}
count++;
}
}
You never reset count once you reached 30.
Thank you Everyone for Answering me... After long long time i founded what happened.. and the below code works fine.
Which will Create a new page if the count goes out of bounds.
Hope this will help for the beginners. thanks
_Line = 0;
void printDocument1_PrintPage( object sender, System.Drawing.Printing.PrintPageEventArgs e )
{
float lineHeight = NormalFont.GetHeight(e.Graphics) + 4;
float yLineTop = e.MarginBounds.Top;
yLineTop = yLineTop + 100;
for ( ; _Line <= 100 ; _Line++ )
{
if ( yLineTop + lineHeight > e.MarginBounds.Bottom )
{
e.HasMorePages = true;
return;
}
e.Graphics.DrawString( "TEST: " + _Line, NormalFont, Brushes.Black, new PointF( e.MarginBounds.Left, yLineTop ) );
yLineTop += lineHeight;
}
e.HasMorePages = false;
}
Continuation of thread: C# Invalidate troubles. I created the class but now I get an Error 2 Embedded statement cannot be a declaration or labeled statement. And I am trying to create the "Car" by Car aCar = new Car(50,100); that is where I am getting the error.
Thanks for the suggestions.
class Car
{
private Pen pen1 = new Pen(Color.Blue, 2F);
private Pen pen2 = new Pen(Color.Green, 2F);
int cost = 0;
int x, y;
Graphics g;
public Car(int x, int y)
{
this.x = x;
this.y = y;
}
public void printCar()
{
g.DrawEllipse(pen1, x, y, 30, 30);
g.DrawEllipse(pen1, x + 100, y, 30, 30);
g.DrawRectangle(pen2, x - 5, y + 50, 140, 50);
g.DrawLine(pen2, x + 15, y + 50, x + 30, y + 90);
g.DrawLine(pen2, x + 30, y + 90, x + 90, y + 90);
g.DrawLine(pen2, x + 90, y + 90, x + 110, y + 50);
// Create string to draw.
String drawString = "Price: " + (cost).ToString("C");
// Create font and brush.
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(Color.Black);
// Create point for upper-left corner of drawing.
PointF drawPoint = new PointF(50, 95);
// Draw string to screen.
g.DrawString(drawString, drawFont, drawBrush, drawPoint);
}
public partial class Form1 : Form
{
private Pen pen1 = new Pen(Color.Blue, 2F);
private Pen pen2 = new Pen(Color.Green, 2F);
private double cost ;
private int days = 0;
private double air;
private double automatic;
int count;
int m = 50;
Car aCar = new Car(50, 60);
public Form1()
{
InitializeComponent();
days = int.Parse(textBox1.Text);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "Van")
{
cost = 110;
label1.Text = "The Cost of van per day" + (cost).ToString("C");
textBox1.Text = "1";
textBox1.Focus();
}
else if (comboBox1.SelectedItem.ToString() == "Car")
{
cost = 85.20;
label1.Text = "The Cost of car per day" + (cost).ToString("C");
textBox1.Text = "1";
textBox1.Focus();
}
else
{
cost = 135;
label1.Text = "Van" + (cost).ToString("C");
textBox1.Text = "1";
textBox1.Focus();
}
}
private void button1_Click(object sender, EventArgs e)
{
count++;
button1.Text = "Move";
pictureBox1.Invalidate();
if(count == 2)
button1.Text = "Reset";
if (count == 3)
{
textBox1.Text = "0";
count = 0;
comboBox1.Text = "select type of vehical";
checkBox1.Checked = false;
checkBox2.Checked = false;
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(Color.White);
if (count == 1)
aCar.printCar();
if (count == 2)
}
private void Form1_Load(object sender, EventArgs e)
{
}
The end of your picturebox1_Paint method opens an if statement but doesn't actually contain a body. That is illegal:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.Clear(Color.White);
if (count == 1)
aCar.printCar();
if (count == 2) // <-- This is illegal since the if statement is just dangling
}
You have to pass the Graphic object you are getting from the Paint event:
Public void printCar(Graphic g)
{
// etc, etc
}
So that when you call it:
aCar.printCar(e.Graphics);
Although there are some tutorials on web, I'm still lost on why this doesn't print multiple pages correctly. What am I doing wrong?
public static void printTest()
{
PrintDialog printDialog1 = new PrintDialog();
PrintDocument printDocument1 = new PrintDocument();
printDialog1.Document = printDocument1;
printDocument1.PrintPage +=
new PrintPageEventHandler(printDocument1_PrintPage);
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
{
printDocument1.Print();
}
}
static void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics graphic = e.Graphics;
SolidBrush brush = new SolidBrush(Color.Black);
Font font = new Font("Courier New", 12);
e.PageSettings.PaperSize = new PaperSize("A4", 850, 1100);
float pageWidth = e.PageSettings.PrintableArea.Width;
float pageHeight = e.PageSettings.PrintableArea.Height;
float fontHeight = font.GetHeight();
int startX = 40;
int startY = 30;
int offsetY = 40;
for (int i = 0; i < 100; i++)
{
graphic.DrawString("Line: " + i, font, brush, startX, startY + offsetY);
offsetY += (int)fontHeight;
if (offsetY >= pageHeight)
{
e.HasMorePages = true;
offsetY = 0;
}
else {
e.HasMorePages = false;
}
}
}
You can find an example of this code's printed result here: Printed Document
You never return from the loop. Change it to:
if (offsetY >= pageHeight)
{
e.HasMorePages = true;
offsetY = 0;
return; // you need to return, then it will go into this function again
}
else {
e.HasMorePages = false;
}
In addition you need to change the loop to start at the current number on the 2nd page instead of restarting with i=0 again.