温馨提示×

C# 打印输出怎样添加页眉页脚

c#
小樊
117
2024-07-20 06:09:50
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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方法来进行打印。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c# xwpfdocument 的页眉和页脚如何设置

0