我有两个程序,一个是Windows服务,另一个是Windows窗体应用程序。它们具有完全相同的代码,用于打印一个A4页面。它们都打印到同一台网络打印机,然后开始在0,0位置绘图。
private void pd_PrintCustomsDocument(object sender, PrintPageEventArgs ev)
{
Graphics g = ev.Graphics;
g.PageUnit = GraphicsUnit.Millimeter;
using (Font courierBig = new Font("Courier", 15))
{
g.DrawString("Shipping Invoice", courierBig, Brushes.Black, new Point(0, 0));
// etc
}
}
Windows窗体应用程序正确打印文档,使用页边距。但该服务正好在纸张的边缘开始打印。 从服务和Windows窗体应用程序打印gdi +之间有区别吗?
实际打印的代码分为基础和子类,用于覆盖默认打印机设置,例如从不同托盘中选择页面:
public class PrintBehaviour : IDisposable
{
private string mPrinterName;
private PrintPageEventHandler mHandler;
private PrintDocument mDocument = new PrintDocument();
public PrintBehaviour(string name, PrintPageEventHandler handler)
{
mPrinterName = name;
mHandler = handler;
mDocument.PrintController = new StandardPrintController();
}
public virtual void SettingsOverride(PrintDocument doc) {}
public void Print()
{
SettingsOverride(mDocument);
mDocument.PrinterSettings.PrinterName = mPrinterName;
mDocument.PrintPage += new PrintPageEventHandler(mHandler);
mDocument.Print();
}
public void Dispose()
{
mDocument.Dispose();
}
}
public sealed class CustomsPrintBehaviour : PrintBehaviour
{
private string mPaperTray;
public CustomsPrintBehaviour(string name, PrintPageEventHandler handler, string paperTray)
: base(name, handler)
{
mPaperTray = paperTray;
}
public override void SettingsOverride(PrintDocument doc)
{
base.SettingsOverride(doc);
doc.DefaultPageSettings.Landscape = true;
foreach (PaperSource source in doc.PrinterSettings.PaperSources)
{
if (source.SourceName.Trim().ToUpper() == mPaperTray)
{
doc.DefaultPageSettings.PaperSource = source;
PaperSize size = new PaperSize { RawKind = (int)PaperKind.A4 };
doc.DefaultPageSettings.PaperSize = size;
break;
}
}
}
}
并且这样调用:
using (var pb = new CustomsPrintBehaviour(_customsPrinter, pd_PrintCustomsDocument, kv["PaperTray"].ToUpper()))
{
pb.Print();
}
答案 0 :(得分:1)
来自MSDN:
GDI +函数和类不支持在a中使用 Windows服务。试图使用这些函数和类 Windows服务可能会产生意外问题,例如减少 服务性能和运行时异常或错误。