Question

I'm using PrintDocument to print some text on the lower right corner of the page. I currently have the starting top position to be a static about 2 inches from the bottom. The problem I'm running into is that the text prints down and if it has several lines then it gets cut off the page.

I the solution I want to implement is to set start to be the bottom of the page have the text print up so nothing gets cropped.

Has anyone worked on something like this?

Here is my code

private void StampPrintPage(object sender, PrintPageEventArgs e)
{
    string fontFamily = "Courier New";
    float xOffset = 0; // Right Offset
    float yOffset = 0; // Top Offset

    float normalSize = 7.0F;
    float mediumSize = 9.0F;
    float largerSize = 10.0F;

    // Detailed Information
    foreach (DataGridViewRow item in this.dgTest.Rows)
    {
        this.StampPrintLine(e, item.cell[0].value, fontNormal, ref xOffset, ref yOffset);
    }

    // Indicate that no more data to print, and the Print Document can now send the print data to the spooler.
    e.HasMorePages = false;
}

private void StampPrintLine(PrintPageEventArgs e, string lineText, Font lineFont, ref float xOffset, ref float yOffset)
{
    StringFormat format = new StringFormat();
    format.Alignment = StringAlignment.Center;

    e.Graphics.DrawString(lineText, lineFont, Brushes.Black, xOffset, yOffset, format);
    StampIncrementOffset(ref yOffset, lineFont, e);
    return;
}

private void StampIncrementOffset(ref float yOffset, Font lineFont, PrintPageEventArgs e)
{
    yOffset += lineFont.GetHeight(e.Graphics);
}
Was it helpful?

Solution

First you have to decide which you want:

  1. Print within a fixed 2 inch space.
  2. Print as much height as it needs to accommodate all text.

If you choose #1, your space is inflexible and cropping is inevitable.

If you choose #2, then you will need to calculate the total height, and then set your starting point according to that:

This is not a working example, but should be enough to get you going:

String strLines = String.Empty;
foreach (DataGridViewRow item in this.dgTest.Rows)
{
    if (!String.IsNullOrEmpty(strLines))
        strLines += "\n";
    strLines += item.Cells[0].Value;
}
Size proposedSize = new Size(100, 100);  //maximum size you would ever want to allow
StringFormat flags = new StringFormat(StringFormatFlags.LineLimit);  //wraps
Size textSize = TextRenderer.MeasureText(strLines, fontNormal, proposedSize, flags);
Int32 xOffset = e.MarginBounds.Right - textSize.Width;  //pad?
Int32 yOffset = e.MarginBounds.Bottom - textSize.Height;  //pad?
e.Graphics.DrawString(strLines, fontNormal, Brushes.Black, xOffset, yOffset, flags);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top