private void DisposeXpsDocWriter() { if (_xpsDocWriter != null) { _xpsDocWriter.WritingCompleted -= WritingCompleted; _xpsDocWriter.WritingProgressChanged -= WritingProgressChanged; _xpsDocWriter = null; } if (_docPaginator != null) { _docPaginator.Dispose(); _docPaginator = null; } _printedElement = null; _originalSize = null; }
public bool Print(Printer printer, int pageCount, Func <Size, PageOrientation> getOrientation, Func <int, int, Size, Visual> getPage, Action <WritingProgressChangedEventArgs> progressChanged, Action <WritingCompletedEventArgs> printCompleted) { if (printer == null || string.IsNullOrEmpty(printer.Name)) { return(false); } using (var printQueue = GetPrinter(printer.Name)) { if (printQueue == null) { return(false); } var printTicket = GetPrintTicket(printQueue, printer.Ticket); /*The first way * var printDialog = new PrintDialog(); * printDialog.PrintQueue = printer; * printDialog.PrintTicket = printTicket; */ //The second way printQueue.UserPrintTicket = printTicket; //Page Size 1 inch = 96 pixels Size originalPageSize; try { var pageImageableArea = printQueue.GetPrintCapabilities(printTicket).PageImageableArea; originalPageSize = new Size(pageImageableArea.ExtentWidth, pageImageableArea.ExtentHeight); } catch { originalPageSize = new Size(printTicket.PageMediaSize.Width.Value, printTicket.PageMediaSize.Height.Value); } //Page Orientation if (getOrientation != null) { if (getOrientation(originalPageSize) == PageOrientation.Landscape) { //exchange width and height originalPageSize = new Size(originalPageSize.Height, originalPageSize.Width); printTicket.PageOrientation = System.Printing.PageOrientation.Landscape; } else { printTicket.PageOrientation = System.Printing.PageOrientation.Portrait; } } else { if (printTicket.PageOrientation == System.Printing.PageOrientation.Landscape) { originalPageSize = new Size(originalPageSize.Height, originalPageSize.Width); } } try { //The first way //printDialog.PrintDocument(new LabelDocPaginator(pageCount, originalPageSize, getSpecifiedPage), "Print Label"); //The second way DisposeXpsDocWriter(); _printCompleted = printCompleted; _progressChanged = progressChanged; _xpsDocWriter = PrintQueue.CreateXpsDocumentWriter(printQueue); _xpsDocWriter.WritingCompleted += WritingCompleted; _xpsDocWriter.WritingProgressChanged += WritingProgressChanged; _docPaginator = new PrintDocPaginator(pageCount, originalPageSize, getPage); _xpsDocWriter.WriteAsync(_docPaginator); } catch (Exception ex) { DisposeXpsDocWriter(); _printCompleted = null; _progressChanged = null; return(false); } } return(true); }