Search code examples
c#.netgdi+gdisystem.drawing

How to print text to bottom left corner in page in C#


Code below is used to print order. Order can have variable number of lines written out by first DrawString call.

Text

Bottom line1
Bottom line2

must appear in bottom left corner in page.

Code below uses hard coded value e.MarginBounds.Top + 460 to print this. How to remove this hard-coded value so that text is printed in bottom of page ?

   var doc = new PrintDocument();
   doc.PrinterSettings.PrinterName = "PDFCreator";
   doc.PrintPage += new PrintPageEventHandler(ProvideContent);
   doc.Print();

    void ProvideContent(object sender, PrintPageEventArgs e)
    {
        e.Graphics.DrawString("string containing variable number of lines", new Font("Arial", 12),
            Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top);

        e.Graphics.DrawString("Bottom line1\r\nBottom line2", new Font("Courier", 10), Brushes.Black,
                    e.MarginBounds.Left, e.MarginBounds.Top + 460);
     }

Solution

  • Measure your string, then move up that height from the bottom?

        void ProvideContent(object sender, PrintPageEventArgs e)
        {
            e.Graphics.DrawString("string containing variable number of lines", new Font("Arial", 12),
                Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top);
    
    
            string bottom = "Bottom line1\r\nBottom line2";
            Font courier = new Font("Courier", 10);
            Size sz = TextRenderer.MeasureText(bottom, courier);
            e.Graphics.DrawString(bottom, courier, Brushes.Black,
                        e.MarginBounds.Left, e.MarginBounds.Bottom - sz.Height);
        }