经过:
开始试过FlowDocument的方式通过xpsdocumentviewer来预览,但是流文档的方式数据绑定是硬伤;
试过通过对窗口活用户控件截图然后插入word文件在进行打印,但是截图的质量达不到要求;最后摸索出了以下(多页打印)这种方式。
1、单个页面打印
var window = new MyWindow();
PrintDialog printDialog = new PrintDialog();
if(printDialog.ShowDialog() == true)
{
//横向或者竖向
//printDialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
printDialog.PrintVisual(window , "test");
}
2、多个页面打印
多个页面指的是WPF中的窗口或者用户控件
使用XPSDocumentViewer控件进行预览,然后用它自带的打印功能或者自己写打印
效果:
代码:
/// <summary>
/// 根据用户控件列表创建文档
/// </summary>
/// <param name="list"></param>
public void CreateDocument(List<UserControl> list)
{
FixedDocument fixedDoc = new FixedDocument();
foreach (var item in list)
{
PageContent pageContent = new PageContent();
FixedPage fixedPage = new FixedPage();
//如果有需要可以对page进行旋转
//fixedPage.RenderTransformOrigin = new Point(0.5, 0.37);
//RotateTransform rotateTransform = new RotateTransform();
//rotateTransform.Angle = 90;
//fixedPage.RenderTransform = rotateTransform;
fixedPage.HorizontalAlignment = HorizontalAlignment.Left;
fixedPage.VerticalAlignment = VerticalAlignment.Top;
fixedPage.Children.Add(item);
double pageWidth = 96 * 8.5;
double pageHeight = 96 * 11;
//由于要横向展示,所以高度和宽度进行调换
fixedPage.Width = pageHeight + 60;
fixedPage.Height = pageWidth;
((IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
}
documentViewer1.Document = fixedDoc;
}
private void PrintButton_Click(object sender, RoutedEventArgs e)
{
PrintDialog printDialog = new PrintDialog();
if(printDialog.ShowDialog() == true)
{
//printDialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
printDialog.PrintTicket.Duplexing = Duplexing.TwoSidedShortEdge;
printDialog.PrintDocument(documentViewer1.Document.DocumentPaginator, "值班记录");
}
}
经过两天的多个方案尝试,最终实现了一次打印任务打印多页的功能,希望能帮助小伙伴们少走弯路。