打印RichTextBox

时间:2012-06-17 11:13:58

标签: c# printing richtextbox

设置图片

Image image = Image.FromFile(@"C:\a.jpg");
Clipboard.SetImage(image);
richTextBox1.Paste();

文字打印

PrintDialog printDialog = new PrintDialog();
PrintDocument documentToPrint = new PrintDocument();
printDialog.Document = documentToPrint;
if (printDialog.ShowDialog() == DialogResult.OK)
{
    StringReader reader = new StringReader(richTextBox1.Text);
    documentToPrint.PrintPage += new PrintPageEventHandler(DocumentToPrint_PrintPage);
    documentToPrint.Print();
}


private void DocumentToPrint_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    StringReader reader = new StringReader(richTextBox1.Text);
    float LinesPerPage = 0;
    float YPosition = 0;
    int Count = 0;
    float LeftMargin = e.MarginBounds.Left;
    float TopMargin = e.MarginBounds.Top;
    string Line = null;
    Font PrintFont = this.richTextBox1.Font;
    SolidBrush PrintBrush = new SolidBrush(Color.Black);

    LinesPerPage = e.MarginBounds.Height / PrintFont.GetHeight(e.Graphics);

    while (Count < LinesPerPage && ((Line = reader.ReadLine()) != null))
    {
        YPosition = TopMargin + (Count * PrintFont.GetHeight(e.Graphics));
        e.Graphics.DrawString(Line, PrintFont, PrintBrush, LeftMargin, YPosition, new StringFormat());
        Count++;
    }

    if (Line != null)
    {
        e.HasMorePages = true;
    }
    else
    {
        e.HasMorePages = false;
    }
    PrintBrush.Dispose();
}

此代码仅在richtextbox中打印文本 如何在richtextbox中打印文本和图像?

1 个答案:

答案 0 :(得分:0)

我认为,您需要使用文本和图片将rtf渲染到DocumentToPrint_PrintPage的重写函数e.Graphics。现在,该函数仅呈现来自RichTextBox.Text.

的文本

您需要阅读RichTextBox.rtf,然后解析它,并像e.Graphics.DrawStringdocs)一样为文本和e.Graphics.DrawImagedocs)绘制图像< / p>