用WPF做报表控件(六)

报表打印

前面的几项功能,我做的控件都比DevExpress的报表控件性能要好,唯独这个打印要差一些。但这也能用,毕竟打印的功能使用不多,四十页纸之内速度还是可以的。

报表控件使用FlowDocument来打印。我们需要把数据重新填充到FlowDocument里面。如下面的代码所示,把数据拼成一个XAML的字符串,然后渲染出页面:

StringBuilder flow_doc = new StringBuilder();
flow_doc.Append("<FlowDocument xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" FontSize=\"12\" FontFamily=\"微软雅黑\">");
flow_doc.Append("<FlowDocument.Resources><Style TargetType=\"Table\" x:Key=\"BorderedTable\"><Setter Property=\"CellSpacing\" Value=\"0\"></Setter><Setter Property=\"BorderThickness\" Value=\"1\"></Setter><Setter Property=\"BorderBrush\" Value=\"#000\"></Setter></Style><Style TargetType=\"TableCell\" x:Key=\"BorderedCell\"><Setter Property=\"BorderThickness\" Value=\"0.5\"></Setter><Setter Property=\"BorderBrush\" Value=\"#000\"></Setter><Setter Property=\"Padding\" Value=\"3\"></Setter></Style></FlowDocument.Resources>");

StringBuilder table = new StringBuilder();
table.Append("<Table Style=\"{StaticResource BorderedTable}\"><Table.Columns>");
table.Append(sb);
table.Append("</Table.Columns><TableRowGroup Name=\"rowsDetails\">");
table.Append("</TableRowGroup></Table>");

flow_doc.Append(table);
flow_doc.Append("</FlowDocument>");

FlowDocument本身是有分页功能的,但它遇到了DataGrid一开始遇到的问题:表头怎么放进去呢?

我使用的策略是:把FlowDocument的内容限制在页面的下方,上方留出一点点空白。然后在每一页纸渲染的重载函数里,把表头作为图片画进去!

先把表头保存成一张图片,放在内存里。

Global.HeadBmp = new RenderTargetBitmap((int)HeadGridContaner.ActualWidth, (int)HeadGridContaner.ActualHeight, 96d, 96d, PixelFormats.Default);
Global.HeadBmp.Render(HeadGridContaner);

然后我们需要继承DocumentPaginator类,重载其GetPage函数,把表头的图片画进去。

public override DocumentPage GetPage(int pageNumber)
{
    DocumentPage page = m_paginator.GetPage(pageNumber);
    ContainerVisual newpage = new ContainerVisual();

    DrawingVisual header = new DrawingVisual();
    using (DrawingContext ctx = header.RenderOpen())
    {
        ctx.DrawImage(Global.HeadBmp, new Rect() { X = 50, Y = 50, Width = Global.HeadBmp.Width, Height = Global.HeadBmp.Height });
    }

    newpage.Children.Add(page.Visual);
    newpage.Children.Add(header);

    //调整到A4纸大小
    double ratio = 1123 / page.Size.Width;
    newpage.Transform = new ScaleTransform(ratio, ratio);
    return new DocumentPage(newpage, new Size() { Width = page.Size.Width * ratio, Height = page.Size.Height * ratio }, new Rect() { X = page.BleedBox.X * ratio, Y = page.BleedBox.Y * ratio, Width = page.BleedBox.Width * ratio, Height = page.BleedBox.Height * ratio }, new Rect() { X = page.ContentBox.X * ratio, Y = page.ContentBox.Y * ratio, Width = page.ContentBox.Width * ratio, Height = page.ContentBox.Height * ratio });
}

至此,报表控件的功能基本完成。完整的代码下载:https://download.csdn.net/download/lweiyue/10646218

猜你喜欢

转载自blog.csdn.net/lweiyue/article/details/82496280