最近, 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);
}
}