我读过一两次来自WPF / Silverlight的打印视觉效果有一些缺点,所以人们通常倾向于使用FlowDocument或FixedDocument进行打印。
我想打印一些图形强烈的仪表板,直接打印视觉似乎是最简单的方法。我不必关心分页,因为我想要打印的每个仪表板都应该放在一页上。
在选择这种打印方式之前,我还必须考虑一些缺点吗?
答案 0 :(得分:0)
您可以通过在FrameworkElement中托管Visual对象,然后将FrameworkElement作为FixedPage的内容添加到FixedDocument来打印它们。 Visual主机看起来像这样:
/// <summary>
/// Implements a FrameworkElement host for a Visual
/// </summary>
public class VisualHost : FrameworkElement
{
Visual _visual;
/// <summary>
/// Gets the number of visual children (always 1)
/// </summary>
protected override int VisualChildrenCount
{
get { return 1; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="visual">The visual to host</param>
public VisualHost(Visual visual)
{
_visual = visual;
AddVisualChild(_visual);
AddLogicalChild(_visual);
}
/// <summary>
/// Get the specified visual child (always
/// </summary>
/// <param name="index">Index of visual (should always be 0)</param>
/// <returns>The visual</returns>
protected override Visual GetVisualChild(int index)
{
if (index != 0)
throw new ArgumentOutOfRangeException("index out of range");
return _visual;
}
}
然后你可以添加它们并像这样打印出来:
// Start the fixed document
FixedDocument fixedDoc = new FixedDocument();
Point margin = new Point(96/2, 96/2); // Half inch margins
// Add the visuals
foreach (Visual nextVisual in visualCollection)
{
// Host the visual
VisualHost host = new VisualHost(nextVisual);
Canvas canvas = new Canvas();
Canvas.SetLeft(host, margin.X);
Canvas.SetTop(host, margin.Y);
canvas.Children.Add(host);
// Make a FixedPage out of the canvas and add it to the document
PageContent pageContent = new PageContent();
FixedPage fixedPage = new FixedPage();
fixedPage.Children.Add(canvas);
((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
}
// Write the finished FixedDocument to the print queue
XpsDocumentWriter xpsDocumentWriter = PrintQueue.CreateXpsDocumentWriter(queue);
xpsDocumentWriter.Write(fixedDoc);