在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方法來進行打印。