我正在尝试从我们的网络服务器打印报告,但遇到了一个问题,如果网络打印机未在本地映射到服务器,那么在打印机实际开始打印之前会有相当长的延迟(20 多秒)。如果打印机被映射,那么问题就消失了,打印作业几乎立即完成。不幸的是,由于我们公司的规模,将所有可能的打印机映射到我们的网络服务器是不可行的。
streamToPrint = new StreamReader
("C:\\test.txt");
try
{
printFont = new Font("Arial", 10);
var pd = new PrintDocument();
pd.PrintPage += pd_PrintPage;
pd.PrintController = new StandardPrintController();
pd.PrinterSettings.PrinterName = "networkprinternamehere";
pd.Print();
}
finally
{
streamToPrint.Close();
}
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height /
printFont.GetHeight(ev.Graphics);
// Print each line of the file.
while (count < linesPerPage &&
((line = streamToPrint.ReadLine()) != null))
{
yPos = topMargin + (count *
printFont.GetHeight(ev.Graphics));
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
count++;
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
此处的示例代码几乎直接来自Microsoft 的文档。我见过的所有解决方案都建议映射打印机。有没有办法在没有映射的情况下获得更好的性能?似乎这个问题可能与他们没有得到任何答复有关。
在代码上运行配置文件(根据建议注释)后,87% 的时间花在了 PrintDocument.Print() 方法上。pd_PrintPage 方法几乎不需要任何时间,因此问题与 Print 在后台执行的任何操作有关。