如何打印 DataGrid 的内容。我查看了以下帖子 如何在 WPF 应用程序中生成 FlowDocument 的“打印预览”?它只生成网格的可见部分而不是可滚动部分。我需要预览有多个页面,我认为我应该使用 FlowDocument,但我不知道如何去做。任何想法,将不胜感激。
问问题
8434 次
2 回答
4
我前段时间遇到过这个问题。我编写了一个从 DataGrid生成System.Windows.Documents.Table的方法。由于XpsDocumentWriter ,我将它放在 FlowDocument 中并生成了一个固定的文档。然后,您将拥有可以在DocumentViewer中可视化的 DataGrid 的完整分页视图
于 2012-10-23T08:58:35.893 回答
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 或任何其他控件...
用法:
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 放在一个包含标题控件的简单网格上,以便在我的论文上有一个标题。
于 2013-03-31T18:45:08.717 回答