Hello everyone,
I have a situation to print PDF document as a batch from Web API.
And I have used System.Drawing.Printing Library to print them.
I have noticed the ‘Caution’ mentioned on Microsoft site (https://docs.microsoft.com/en-us/dotnet/api/system.drawing.printing?view=net-5.0) as below.
Specifications:
1) We are using network printers.
2) Windows server 2016 standard.
Caution:
Classes within the System.Drawing.Printing namespace are not supported for use within a Windows service or ASP.NET application or service.
Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions.
As mentioned in the caution I am facing some unexpected problems intermittently during print operation as below.
Problems:
1) Pages are missing in the PDF documents. Example: Out of 10 pages 5th page is missed.
2) Documents are missing, example: out of 100 documents 99/ 95 printed. Some of them is missed.
Exception occured in PrintPdf method: The handle is invalid System.ComponentModel.Win32Exception (0x80004005): The handle is invalid
at System.Drawing.Printing.StandardPrintController.OnStartPrint(PrintDocument document, PrintEventArgs e)
at System.Drawing.Printing.PrintController.Print(PrintDocument document)
at System.Drawing.Printing.PrintDocument.Print()
Code snippet:
using (var document = _pdfDocumentWrapper.Load(stream))
{
using (var printDocument = _pdfDocumentWrapper.CreatePrinterDocument(document))
{
var printerName = printerconfiguration;
Print(printDocument, printerName);
}
}
private void Print(PrintDocument printDocument, string printerName)
{
var printerSettings = new PrinterSettings { PrinterName = printerName };
var pageSettings = new PageSettings(printerSettings) { Margins = new Margins(0, 0, 0, 0) };
printDocument.PrinterSettings = printerSettings;
printDocument.DefaultPageSettings = pageSettings;
printDocument.PrintController = new StandardPrintController();
printDocument.BeginPrint += PrintDocument_BeginPrint;
printDocument.PrintPage += PrintDocument_PrintPage;
printDocument.EndPrint += PrintDocument_EndPrint;
printDocument.Print();
}
Any suggestions or alternative approach for the same would be greatly appreciated.