【问题标题】:C# printing IssuesC# 打印问题
【发布时间】:2013-05-27 14:33:43
【问题描述】:
    private void printReceipt()
    {
        printDialog.Document = printDocument;

        DialogResult result = printDialog.ShowDialog();

        if (result != DialogResult.OK) return;
        try
        {
            sPrint = new StreamReader(
                     new MemoryStream(
                         Encoding.ASCII.GetBytes(richTextBoxResult.Text)));

            printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);

            printDocument.Print();
        }
        catch (Exception e)
        {
            MessageBox.Show("Failed to print \n" + e.Message);

        }
        finally
        {
            if (sPrint != null)
                sPrint.Close();
        }
    }

    void printDocument_PrintPage(object sender, PrintPageEventArgs e)
    {
        // No of lines that fit on to the page
        float linesPerPage = e.MarginBounds.Height / richTextBoxResult.Font.GetHeight(e.Graphics);

        float fontHeight = richTextBoxResult.Font.GetHeight(e.Graphics);

        for (int count = 0; count < linesPerPage && !sPrint.EndOfStream; count++)
        {
            e.Graphics.DrawString(sPrint.ReadLine(),
                richTextBoxResult.Font,
                Brushes.Black,
                e.MarginBounds.Left,
                e.MarginBounds.Top + (count * fontHeight),
                new StringFormat());
        }
        e.HasMorePages = !sPrint.EndOfStream;          

    }

我的问题:-

  1. 我需要在打印时正确调整所有文本框内容。 (冗长的单行没有打印,而是跳出页面)
  2. 是否可以在打印菜单下启用打印范围选项? (在输出 GUI 上,假设我的文本内容可以放在多个页面上)

请帮忙。 谢谢。

【问题讨论】:

  • 您是否考虑过使用报告?多做一些工作来实现,但必须满足你想要的。
  • 正确打印富文本需要 hocus pocus。但在this KB article 中有详细记录
  • 使用 ASCII 编码有什么特别的原因吗?丢弃 Unicode 支持似乎是一种浪费。您可以使用 StringReader 消除整个问题和 MemoryStream。
  • @HansPassant 非常感谢。非常有用的链接。

标签: c# .net


【解决方案1】:

至于您的字符串在打印时超出范围,请像现在一样使用Graphics.DrawString,但使用不同的参数。 Graphics.DrawString 有一组不同的参数,可让您定义字符串必须适合的矩形的高度和宽度。如果你给它适当的宽度,当同一行上的最后一个单词不适合并开始换行时,字符串将被“断开”。

像这样:

e.Graphics.DrawString(sPrint.ReadLine(),
            richTextBoxResult.Font,
            Brushes.Black,
            new RectangleF(x, y, p.DefaultPageSettings.PrintableArea.Width, p.DefaultPageSettings.PrintableArea.Height));

请注意上面的代码,硬编码页面的限制可能不是一个好主意,但你明白了。

至于你的第二个问题,如果我理解正确的话:你想测量你的字符串在哪个点不适合你的页面(垂直)?您可以为此使用Graphics.MeasureString。我一直在为同样的事情苦苦挣扎,我发现这是性能更高的选项之一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多