I have a situation to print PDF document as a batch(parallel) from Web API. And I have used System.Drawing.Printing Library to print them.
I have noticed the ‘Caution’ mentioned on the Microsoft site (https://docs.microsoft.com/en-us/dotnet/api/system.drawing.printing?view=net-5.0) as below.
Caution: Classes within the System.Drawing.Printing namespace is 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 was facing some unexpected exceptions intermittently during print operation as below.
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:
public void PrintPdf(Stream stream, string printerconfiguration)
{
if (stream == null)
throw new NullReferenceException(nameof(stream));
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 = GetInstalledPrinter(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;
Print(printDocument);
}
Any suggestions or alternative approach for the same would be greatly appreciated.
User contributions licensed under CC BY-SA 3.0