开发者

WPF/Silverlight: Printing of Visuals - Drawbacks

I 开发者_开发技巧read once or twice that printing visuals from WPF/Silverlight has some drawbacks so people usually tend to use FlowDocument or FixedDocument for printing.

I want to print some graphically intense dashboards and printing the visual directly seems to be the easiest way to go. I don't have to care about pagination since every dashboard I want to print is supposed to fit on one page.

Are there still drawbacks I must consider before choosing this way of printing?


You can print Visual objects by hosting them in a FrameworkElement and then adding the FrameworkElement to a FixedDocument as content of a FixedPage. The Visual host looks like this:

/// <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;
    }
}

Then you can add them and print them like this:

        // 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜