不同类别的打印功能

时间:2014-05-13 19:07:04

标签: c# printdocument

我需要一点帮助。我想创建一个简单的类,只需要提供数据并打印文档。我想将所有设置和图形放在一个类中,只需调用print函数。我的printdocument类看起来像这样。

class printticket
{
    PrintDocument ticket; 

    public void printticket()
    {
        ticket = new PrintDocument();
    }

    public void writeHeader(string h)
    {
        Graphics g = printargs.Graphics;
        StringFormat fs = new StringFormat();
        fs.Alignment = StringAlignment.Center;
        Rectangle r = new Rectangle(X, Y, pargs.MarginBounds.Width, (int)g.MeasureString(h, defaultFont).Height);
        g.DrawString(h, defaultFont, Brushes.Black, r, fs);
        Y += r.Height;
    }

    void print()
    {
        ticket.print();
    }
}

现在我想这样调用这个函数:

var printticket = new printticket();
printticket.writeHeader("this is a testing string");
printticket.print();

是否可以做这样的事情?

1 个答案:

答案 0 :(得分:1)

我能想到的最佳方法是在PrintTicket类的构造函数中传入您想要打印的所需字符串,稍后将在writeHeader方法中使用。 writeHeader方法与PrintPage事件绑定,因此可以访问PrintPageEventArgs。

所以你的PrintTicket课程看起来像是:

public class PrintTicket {
    private PrintDocument _ticket;

    private string _header;
    private Font _defaultFont;

    private int X;
    private int Y;

    public PrintTicket(string header) {
        _ticket = new PrintDocument();
        _ticket.PrintPage += new PrintPageEventHandler(this.writeHeader);
        _header = header;
    }

    private void writeHeader(object sender, PrintPageEventArgs e) {
        Graphics g = e.Graphics;
        StringFormat fs = new StringFormat();
        fs.Alignment = StringAlignment.Center;
        Rectangle r = new Rectangle(X, Y, e.MarginBounds.Width, (int)g.MeasureString(_header, _defaultFont).Height);
        g.DrawString(_header, _defaultFont, Brushes.Black, r, fs);
        Y += r.Height;     
    }

    public void Print() {
        _ticket.Print();
    }        
}

你会这样称呼它:

PrintTicket t = new PrintTicket("This is what I want to print out");
t.Print();