如何打印DataGrid的内容。我查看了以下帖子 How can I produce a "print preview" of a FlowDocument in a WPF application?它只生成网格的可见部分而不是可滚动部分。我需要预览有多个页面,我想我应该使用FlowDocument但我不知道如何去做。任何想法,将不胜感激。
答案 0 :(得分:4)
前段时间我有这个问题。我编写了一个从DataGrid生成 System.Windows.Documents.Table 的方法。由于 XpsDocumentWriter ,我把它放在FlowDocument中并生成了一个固定的文档。然后,您将拥有DataGrid的完整分页视图,您可以在 DocumentViewer
中显示该视图。答案 1 :(得分:2)
使用此: 它工作正常。
public class UIPrinter
{
#region Properties
public Int32 VerticalOffset { get; set; }
public Int32 HorizontalOffset { get; set; }
public String Title { get; set; }
public UIElement Content { get; set; }
#endregion
#region Initialization
public TimelinePrinter()
{
HorizontalOffset = 20;
VerticalOffset = 20;
Title = "Print " + DateTime.Now.ToMyStringWithTime();
}
#endregion
#region Methods
public Int32 Print()
{
var dlg = new PrintDialog();
if (dlg.ShowDialog() == true)
{
//---FIRST PAGE---//
// Size the Grid.
Content.Measure(new Size(Double.PositiveInfinity,
Double.PositiveInfinity));
Size sizeGrid = Content.DesiredSize;
//check the width
if (sizeGrid.Width > dlg.PrintableAreaWidth)
{
MessageBoxResult result = MessageBox.Show(Properties.Resources.s_EN_Question_PrintWidth, "Print", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.No)
throw new PrintAborted(Properties.Resources.s_EN_Info_PrintingAborted);
}
// Position of the grid
var ptGrid = new Point(HorizontalOffset, VerticalOffset);
// Layout of the grid
Content.Arrange(new Rect(ptGrid, sizeGrid));
//print
dlg.PrintVisual(Content, Title);
//---MULTIPLE PAGES---//
double diff;
int i = 1;
while ((diff = sizeGrid.Height - (dlg.PrintableAreaHeight - VerticalOffset*i)*i) > 0)
{
//Position of the grid
var ptSecondGrid = new Point(HorizontalOffset, -sizeGrid.Height + diff + VerticalOffset);
// Layout of the grid
Content.Arrange(new Rect(ptSecondGrid, sizeGrid));
//print
int k = i + 1;
dlg.PrintVisual(Content, Title + " (Page " + k + ")");
i++;
}
return i;
}
throw new PrintAborted(Properties.Resources.s_EN_Info_PrintingAborted);
}
#endregion
}
它在多个页面上打印带有所选打印机的Datagrid或任何其他Control ...
用法:
MessageBoxResult result = MessageBox.Show(Properties.Resources.s_EN_Question_Print, "Print", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
try
{
var border = VisualTreeHelper.GetChild(MyDataGrid, 0) as Decorator;
if (border != null)
{
var scrollViewer = border.Child as ScrollViewer;
if (scrollViewer != null)
{
scrollViewer.ScrollToTop();
scrollViewer.ScrollToLeftEnd();
}
}
Title = _initialTitle + " - " + Properties.Resources.s_EN_Info_Printing;
var myPrinter = new UIPrinter{ Title = Title, Content = PrintGrid };
int nbrOfPages = myPrinter.Print();
Title = _initialTitle + " - " + Properties.Resources.s_EN_Info_PrintingDone + " (" + nbrOfPages + " Pages)";
}
catch (PrintAborted ex)
{
Title = _initialTitle + " - " + ex.Message;
}
}
编辑: 我将我的Datagrid放在一个包含标题控件的简单网格上,以便在我的纸上有一个标题。