代码改变世界

【翻译】打印RichTextBox内容:(寻找空闲打印机)

2011-11-29 17:16  AnyKoro  阅读(322)  评论(0编辑  收藏  举报

http://blogs.msdn.com/b/llobo/archive/2007/01/24/printing-richtextbox-content-find-the-idle-printer.aspx

最近, Praj发表了关于打印RichTextBox内容的博文。一般,如果你使用documentPaginator或者visual,你可能因一些文本剪贴而终止。这可不是好事。当打印时容易出的bug是打印对话框。通常,我想使用空闲的打印机,而不是让我等待。下面是我针对此修改的代码。

 

foreach (PrintQueue pq in GetPrintQueues("\\\\servername"))

{

if (!pq.IsBusy)

{

Print(pq);

return;

}

}

private IEnumerable<PrintQueue> GetPrintQueues(string servername)

{

PrintServer ps;



if (string.IsNullOrEmpty(servername))

{

// local printer name

ps = new LocalPrintServer();

}

else

{

// network printer share

ps = new PrintServer(servername);

}



return ps.GetPrintQueues();

}

void Print(PrintQueue pq)

{

TextRange sourceDocument = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);

MemoryStream stream = new MemoryStream();

sourceDocument.Save(stream, DataFormats.Xaml);



// Clone the source document's content into a new FlowDocument.

FlowDocument flowDocumentCopy = new FlowDocument();

TextRange copyDocumentRange = new TextRange(flowDocumentCopy.ContentStart, flowDocumentCopy.ContentEnd);

copyDocumentRange.Load(stream, DataFormats.Xaml);



// Create a XpsDocumentWriter object, open a Windows common print dialog.

// This methods returns a ref parameter that represents information about the dimensions of the printer media.

XpsDocumentWriter docWriter = PrintQueue.CreateXpsDocumentWriter(pq);

PageImageableArea ia = pq.GetPrintCapabilities().PageImageableArea;

PrintTicket pt = pq.UserPrintTicket;



if (docWriter != null && ia != null)

{

DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocumentCopy).DocumentPaginator;

// Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device.

paginator.PageSize = new Size((double)pt.PageMediaSize.Width, (double)pt.PageMediaSize.Height);

Thickness pagePadding = flowDocumentCopy.PagePadding;

flowDocumentCopy.PagePadding = new Thickness(

Math.Max(ia.OriginWidth, pagePadding.Left),

Math.Max(ia.OriginHeight, pagePadding.Top),

Math.Max((double)pt.PageMediaSize.Width - (double)(ia.OriginWidth + ia.ExtentWidth), pagePadding.Right),

Math.Max((double)pt.PageMediaSize.Height - (double)(ia.OriginHeight + ia.ExtentHeight), pagePadding.Bottom));

flowDocumentCopy.ColumnWidth = double.PositiveInfinity;

// Send DocumentPaginator to the printer.

docWriter.Write(paginator);

}

}