在WPF中使用PrintDialog.PrintDocument方法进行打印
使用PrintDialog.PrintDocument方法进行打印需要提前布局流文档,流文档不能直接在编辑器中显示,可以考虑在用户控件或者窗口中进行布局后,将代码拷贝进流文档中。
对流文档进行数据赋值时,可以考虑在流文档中预定义TextBlock文本,对其进行命名。之后在渲染时,通过遍历源数据中的属性名,在流文档中查找相应的TextBlock文本,找到后对其进行赋值。
打印参数设置等思路可以参考:
1、流文档示例
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" FontFamily="宋体">
2、打印实体类
public class PrintModel { ////// 批号 /// public string BatchNumber { get; set; } /// /// 订单号 /// public string OrderNumber { get; set; } /// /// 物料代码 /// public string MaterialNumber { get; set; } }
3、渲染类
public interface IDocumentRenderer { void Render(FlowDocument doc, object data); } public class CommonDocumentRenderer : IDocumentRenderer { public void Render(FlowDocument doc, object data) { var model = data as PrintModel; if (model == null) { throw new ArgumentException("data is not PrintModel"); } var type = typeof(PrintModel); var properties = type.GetProperties(); foreach (var property in properties) { //文本赋值 if (doc.FindName(property.Name) is TextBlock textBlock) { textBlock.Text = property.GetValue(model)?.ToString(); } } } }
4、打印代码示例
public void Print(FlowDocument document, object data, string printer, int copyCount) { var renderer = new CommonDocumentRenderer(); renderer.Render(document, data); Print(document, printer, entity.Description, copyCount); } ////// 打印 /// /// 流文档 /// 打印机名称 /// 打印描述 /// 打印个数 public static void Print(FlowDocument document, string printer, string description, int copyCount) { var localPrintServer = new LocalPrintServer(); var printQueue = localPrintServer.GetPrintQueue(printer); if (printQueue.IsInError) { throw new Exception("打印机处于错误状态"); } var printDialog = new PrintDialog { PrintQueue = printQueue, //打印队列 PrintTicket = {CopyCount = copyCount} //打印个数 }; //设置纸张大小 var pageWidth = (int) Math.Ceiling(printDialog.PrintableAreaWidth); //小标签:114 var pageHeight = (int) Math.Ceiling(printDialog.PrintableAreaHeight); //小标签:227 printDialog.PrintTicket.PageMediaSize = new PageMediaSize(pageWidth, pageHeight); //设置纸张边距 var paperSize = GetPaperSize(printer); //小标签:118*246 var offsetX = (int) Math.Ceiling((paperSize.Width - pageWidth) / 2f); var offsetY = (int) Math.Ceiling((paperSize.Height - pageHeight) / 2f); document.PagePadding = new Thickness(offsetX, offsetY, offsetX, offsetY); //打印 var paginator = ((IDocumentPaginatorSource) document).DocumentPaginator; printDialog.PrintDocument(paginator, description); }