C#使用PrintDocument类连接打印机进行标签打印

在C#中可以使用.NET中的打印机类(例如PrintDocument)来创建和管理打印作业。使用该类来设置打印机、页面设置、打印事件等。

设置打印机属性

PrintDocument pd = new PrintDocument();
pd.DocumentName = "My Document"; // 设置文档名称
pd.PrinterSettings.PrinterName = "Printer Name"; // 设置打印机名称


处理打印事件

pd.PrintPage += (sender, e) =>
{
    // 在此处绘制打印内容(可以使用Graphics对象绘制打印内容)
};

页面设置

pd.DefaultPageSettings.Landscape = true; // 设置横向打印

pd.DefaultPageSettings.Margins = new Margins(50, 50, 50, 50); // 设置页边距

执行打印操作

pd.Print(); // 开始打印

简单示例

using System;
using System.Drawing;
using System.Drawing.Printing;

public class LabelPrinter
{
    public void PrintLabel(string labelText)
    {
        PrintDocument pd = new PrintDocument();
        pd.PrintPage += (sender, args) =>
        {
            using (Font font = new Font("Arial", 12))
            {
                args.Graphics.DrawString(labelText, font, Brushes.Black, new PointF(100, 100));
            }
        };

        pd.Print();
    }
}
 

猜你喜欢

转载自blog.csdn.net/qq_33790894/article/details/131657849