I am attempting to print reports from our webserver but I ran into a problem where if the network printer is not mapped locally to the server then there is a considerable delay (20+ seconds) before the printer actually starts printing. If the printer is mapped then the problem goes away and the print job goes through almost immediately. Unfortunately due to the size of our company mapping all the possible printers to our webserver is infeasible.
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;
}
Example code here pulled pretty much straight from Microsoft's documentation. All the solutions I've seen have just recommended mapping the printers. Is there a way I can better performance without mapping? It seems like this question may be related by they did not get any responses.
After running a profile on the code (per suggestion the comments) 87% the time is spent in the PrintDocument.Print() method. The pd_PrintPage method takes almost no time so the problem is associated with whatever Print does under the hood.