c# printdocument
时间: 2023-08-30 07:11:10 浏览: 49
在C#中,可以使用PrintDocument类来打印文档。下面是一个简单的示例代码,演示如何使用PrintDocument类打印文本:
``` csharp
private void buttonPrint_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintPage);
pd.Print();
}
private void PrintPage(object sender, PrintPageEventArgs e)
{
Font font = new Font("Arial", 12);
e.Graphics.DrawString("Hello, World!", font, Brushes.Black, new PointF(0, 0));
}
```
在上面的代码中,我们创建了一个PrintDocument对象,并为其PrintPage事件设置了一个处理程序。在PrintPage事件处理程序中,我们定义了要打印的文本和字体,并使用Graphics对象的DrawString方法将其绘制到打印页面上。
最后,我们调用Print方法来打印文档。这将打开打印对话框,允许用户选择打印机和其他打印选项。如果您要直接打印而不显示打印对话框,则可以使用PrintDocument类的PrintController属性来设置打印控制器。例如,使用StandardPrintController类将文档直接发送到默认打印机:
``` csharp
pd.PrintController = new StandardPrintController();
```
此外,PrintDocument类还提供了其他有用的属性和方法,例如设置页边距、打印多页文档和打印预览等。有关更多详细信息,请参阅MSDN文档。