代码改变世界

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

  AnyKoro  阅读(331)  评论(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);

}

}
复制代码


编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示