在C#中打印輸出時(shí),可以使用PrintDocument類來(lái)實(shí)現(xiàn)添加頁(yè)眉和頁(yè)腳。以下是一個(gè)簡(jiǎn)單的示例代碼:
using System;
using System.Drawing;
using System.Drawing.Printing;
public class PrintingExample
{
private static void PrintPage(object sender, PrintPageEventArgs e)
{
// 添加頁(yè)眉
string header = "頁(yè)眉內(nèi)容";
e.Graphics.DrawString(header, new Font("Arial", 12), Brushes.Black, new Point(50, 50));
// 添加頁(yè)腳
string footer = "頁(yè)腳內(nèi)容";
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);
// 設(shè)置打印機(jī)
PrintDialog pdialog = new PrintDialog();
pdialog.Document = pd;
if (pdialog.ShowDialog() == DialogResult.OK)
{
pd.Print();
}
}
}
在上面的示例中,我們定義了一個(gè)PrintPage方法來(lái)添加頁(yè)眉和頁(yè)腳內(nèi)容,并將其綁定到PrintDocument的PrintPage事件中。然后在Main方法中創(chuàng)建PrintDocument對(duì)象,并通過(guò)PrintDialog來(lái)選擇打印機(jī),最后調(diào)用Print方法來(lái)進(jìn)行打印。