【问题标题】:C# PrintDocument align lower right cornerC# PrintDocument 对齐右下角
【发布时间】:2014-01-24 05:00:15
【问题描述】:

我正在使用 PrintDocument 在页面的右下角打印一些文本。我目前的起始顶部位置是距离底部约 2 英寸的静态位置。我遇到的问题是文本打印下来,如果它有几行,那么它就会被切断。

我想要实施的解决方案是将开始设置为页面底部,让文本打印出来,这样就不会裁剪任何内容。

有人做过类似的事情吗?

这是我的代码

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

【问题讨论】:

    标签: c# winforms alignment printdocument


    【解决方案1】:

    首先你必须决定你想要哪个:

    1. 在固定的 2 英寸空间内打印。
    2. 打印所需的高度以容纳所有文本。

    如果你选择#1,你的空间是不灵活的,裁剪是不可避免的。

    如果你选择#2,那么你需要计算总高度,然后根据这个设置你的起点:

    这不是一个有效的例子,但应该足以让你继续前进:

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

    【讨论】:

    • 谢谢,我试试看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多