在C#中打印输出时,可以使用PrintDocument类来实现添加页眉和页脚。以下是一个简单的示例代码:
using System;
using System.Drawing;
using System.Drawing.Printing;
public class PrintingExample
{
private static void PrintPage(object sender, PrintPageEventArgs e)
{
// 添加页眉
string header = "页眉内容";
e.Graphics.DrawString(header, new Font("Arial", 12), Brushes.Black, new Point(50, 50));
// 添加页脚
string footer = "页脚内容";
e.Graphics.DrawString(footer, new Font("Arial", 12), Brushes.Black, new Point(50, e.PageBounds.Height - 100));
}
public static void Main()
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(PrintPage);
// 设置打印机
PrintDialog pdialog = new PrintDialog();
pdialog.Document = pd;
if (pdialog.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
}
}
在上面的示例中,我们定义了一个PrintPage方法来添加页眉和页脚内容,并将其绑定到PrintDocument的PrintPage事件中。然后在Main方法中创建PrintDocument对象,并通过PrintDialog来选择打印机,最后调用Print方法来进行打印。