我需要一点帮助。我想创建一个简单的类,只需要提供数据并打印文档。我想将所有设置和图形放在一个类中,只需调用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();
是否可以做这样的事情?
答案 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();