Sagar Upadhyay
Sagar Upadhyay

Reputation: 819

Printing multiple document in c# window application

In c# window application I having a trouble with printing documents, when its become more than 1 page. See the following code which I am using for printing document and its working fine, while there is a small document i.e only one page.

On print button's click event

    private void button1_Click(object sender, EventArgs e)
    {
        PrintDialog pd = new PrintDialog();
        PrintDocument doc = new PrintDocument();
        pd.Document = doc;
        doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
        DialogResult res = pd.ShowDialog();
        if (res == System.Windows.Forms.DialogResult.OK)
        {
            doc.Print();
        }
    }

And PrintPageEventHandler is as following.

    void doc_PrintPage(object sender, PrintPageEventArgs e)
    {
    //Fetching data from DB

        BillingApplicationEntities ent = new BillingApplicationEntities();
        List<tbCustBill> BillData = ent.tbCustBills.Where(s => s.BillId == 20133).ToList();

   //Printing doc

        Graphics grp = e.Graphics;

        Font fnt = new Font("Courier New", 12);
        float fontH = fnt.GetHeight();

        int startX = 10;
        int StartY = 10;
        int offset = 40;
        foreach (tbCustWorkDet d in WorkData)
        {
            string Pare = d.WorkName.PadRight(30);
            string pp = string.Format("{0:c}", d.Price).PadRight(30);

            string pl = Pare + pp;

            grp.DrawString(pl, fnt, new SolidBrush(Color.Black), startX, StartY + offset);

            offset += (int)fontH + 5;
           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;
            }
        }
        offset += 20;
        // And cont with other data to print
    }

This method is working fine and gives me my required o/p, but when data becomes more larger and its need more pages to print then in o/p it gives me only one page.

As I think for multiple pages we have to set following property to true

    e.HasMorePages = true;

But I don't know where and how to put this value...

In short I want to know how can I print multiple documents from above code?

In this code return will return to the function and entire execution start again, and so on this will become in Infinite loop. Please tell me how can I prevent with this problem.

Upvotes: 0

Views: 3450

Answers (1)

xpda
xpda

Reputation: 15813

Add e.HasMorePages = true; in the printpage handler, if there are more pages to print. This causes the handler to be called again. It is up to the handler to output the proper page.

Upvotes: 1

Related Questions