wpf - 如何在 WPF 中打印一组用户控件?

标签 wpf printing .net-4.5

说我有以下小UserControl :

<StackPanel>
   <TextBlock Text="{Binding Title, StringFormat=Name: {0}}" FontWeight="Bold"/>
   <Separator/>
   <ItemsControl ItemsSource="{Binding Items}">
      <ItemsControl.ItemTemplate>
         <DataTemplate>
            <TextBlock Text="{Binding Path=. ,StringFormat=Detail: {0}}"/>
         </DataTemplate>
      </ItemsControl.ItemTemplate>
  </ItemsControl>
  <Line Stroke="Black" HorizontalAlignment="Stretch" Margin="0,10"
                X2="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"
                StrokeDashArray="2 2" StrokeThickness="1" />
</StackPanel>

我的应用程序将生成这些控件的集合,然后应该使用自动分页打印它们。 ItemsControl 中显示的项目数是可变的。我在网上搜了一下,在 Pro WPF 4.5 Unleashed 中阅读了有关打印的章节,但我仍然不知道如何实现这一点。

非常欢迎任何指导。

编辑:欢迎任何指导。由于我在 View 模型中有可用的数据,因此将其数据重定向到其他地方不会太困难。但是哪里?

最佳答案

由于您需要自动分页,您需要创建一个 DocumentPaginator目的。

以下内容盗自this example并针对您的情况进行了修改:

/// <summary>
/// Document paginator.
/// </summary>
public class UserControlDocumentPaginator : DocumentPaginator
{
    private readonly UserControlItem[] userControlItems;
    private Size pageSize;

    private int pageCount;

    private int maxRowsPerPage;
    /// <summary>
    /// Constructor.
    /// </summary>
    /// <param name="userControlItems">The list of userControl items to display.</param>
    /// <param name="pageSize">The size of the page in pixels.</param>
    public UserControlDocumentPaginator
    (
        UserControlItem[] userControlItems,
        Size pageSize
    )
    {
        this.userControlItems = userControlItems;
        this.pageSize = pageSize;
        PaginateUserControlItems();
    }

    /// <summary>
    /// Computes the page count based on the number of userControl items
    /// and the page size.
    /// </summary>
    private void PaginateUserControlItems()
    {
        double actualHeight;
        foreach (var uc in userControlItems)
        {
            actualHeight += uc.ActualHeight;
        }
        pageCount = (int)Math.Ceiling(actualHeight / pageSize.Height);
    }

    /// <summary>
    /// Gets a range of userControl items from an array.
    /// </summary>
    /// <param name="array">The userControl items array.</param>
    /// <param name="start">Start index.</param>
    /// <param name="end">End index.</param>
    /// <returns></returns>
    private static UserControlItem[] GetRange(UserControlItem[] array, int start, int end)
    {
        List<UserControlItem> userControlItems = new List<UserControlItem>();
        for (int i = start; i < end; i++)
        {
            if (i >= array.Count())
            {
                break;
            }
            userControlItems.Add(array[i]);
        }
        return userControlItems.ToArray();
    }

    #region DocumentPaginator Members

    /// <summary>
    /// When overridden in a derived class, gets the DocumentPage for the
    /// specified page number.
    /// </summary>
    /// <param name="pageNumber">
    /// The zero-based page number of the document page that is needed.
    /// </param>
    /// <returns>
    /// The DocumentPage for the specified pageNumber, or DocumentPage.Missing
    /// if the page does not exist.
    /// </returns>
    public override DocumentPage GetPage(int pageNumber)
    {
        // Compute the range of userControl items to display
        int start = pageNumber * maxRowsPerPage;
        int end = start + maxRowsPerPage;

        UserControlListPage page = new UserControlListPage(GetRange(userControlItems, start, end), pageSize);
        page.Measure(pageSize);
        page.Arrange(new Rect(pageSize));

        return new DocumentPage(page);
    }
    /// <summary>
    /// When overridden in a derived class, gets a value indicating whether
    /// PageCount is the total number of pages.
    /// </summary>
    public override bool IsPageCountValid
    {
        get { return true; }
    }

    /// <summary>
    /// When overridden in a derived class, gets a count of the number of
    /// pages currently formatted.
    /// </summary>
    public override int PageCount
    {
        get { return pageCount; }
    }

    /// <summary>
    /// When overridden in a derived class, gets or sets the suggested width
    /// and height of each page.
    /// </summary>
    public override System.Windows.Size PageSize
    {
        get
        {
            return pageSize;
        }
        set
        {
            if (pageSize.Equals(value) != true)
            {
                pageSize = value;
                PaginateUserControlItems();
            }
        }
    }

    /// <summary>
    /// When overridden in a derived class, returns the element being paginated.
    /// </summary>
    public override IDocumentPaginatorSource Source
    {
        get { return null; }
    }

    #endregion

}

然后在你的代码后面为你的 Window ,获取您的用户控件列表(将 YourUserControlContainer 替换为您的 Window 中的容器名称)。创建一个名为 PrintButton 的按钮并附上 Click事件到 PrintButton_Click下面的方法。在适当的地方放入代码:
List<UserControl> userControlItems = new List<UserControl>();

// 8.5 x 11 paper
Size pageSize = new Size(816, 1056);

private void PrintButton_Click(object sender, RoutedEventArgs e)
{
    userControlItems = YourUserControlContainer.Children.ToList();
    UserControlDocumentPaginator paginator = new UserControlDocumentPaginator
    (
        userControlItems.ToArray(),
        pageSize
    );
    var dialog = new PrintDialog();
    if (dialog.ShowDialog() != true) return;
    dialog.PrintDocument(paginator, "Custom Paginator Print Job");
}

编辑 你说得对,我忘记上课了。你需要这样的东西:
public partial class UserControlListPage : UserControl
{
    private readonly UserControlItem[] userControlItems;

    private readonly Size pageSize;

    public UserControlListPage
    (
        UserControlItem[] userControlItems,
        Size pageSize
    )
    {
        InitializeComponent();
        this.userControlItems = userControlItems;
        this.pageSize = pageSize;
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);

        Point point = new Point(0, 0);
        foreach (UserControlItem item in userControlItems)
        {
            point.X = 0;
            itemImageSource = CopyControlToImageSource(item);
            drawingContext.DrawImage(itemImageSource, point);
            point.Y += itemImageSource.Height;
        }
    }
}

然后某处放这个:
/// <summary>
/// Gets an image "screenshot" of the specified UIElement
/// </summary>
/// <param name="source">UIElement to screenshot</param>
/// <param name="scale" value="1">Scale to render the screenshot</param>
/// <returns>Byte array of BMP data</returns>
private static byte[] GetUIElementSnapshot(UIElement source, double scale = 1)
{
    double actualHeight = source.RenderSize.Height;
    double actualWidth = source.RenderSize.Width;

    double renderHeight = actualHeight * scale;
    double renderWidth = actualWidth * scale;

    RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32);
    VisualBrush sourceBrush = new VisualBrush(source);

    DrawingVisual drawingVisual = new DrawingVisual();
    DrawingContext drawingContext = drawingVisual.RenderOpen();

    using (drawingContext)
    {
        drawingContext.PushTransform(new ScaleTransform(scale, scale));
        drawingContext.DrawRectangle(sourceBrush, null, new Rect(new System.Windows.Point(0, 0), new System.Windows.Point(actualWidth, actualHeight)));
    }
    renderTarget.Render(drawingVisual);

    Byte[] _imageArray = null;

    BmpBitmapEncoder bmpEncoder = new BmpBitmapEncoder();
    bmpEncoder.Frames.Add(BitmapFrame.Create(renderTarget));

    using (MemoryStream outputStream = new MemoryStream())
    {
        bmpEncoder.Save(outputStream);
        _imageArray = outputStream.ToArray();
    }

    return _imageArray;
}

public static System.Windows.Media.Imaging.BitmapImage CopyControlToImageSource(UIElement UserControl)
{
    ImageConverter ic = new ImageConverter();
    System.Drawing.Image img = (System.Drawing.Image)ic.ConvertFrom(GetUIElementSnapshot(UserControl));
    MemoryStream ms = new MemoryStream();
    img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
    System.Windows.Media.Imaging.BitmapImage image = new BitmapImage();
    image.BeginInit();
    ms.Seek(0, SeekOrigin.Begin);
    image.StreamSource = ms;
    image.EndInit();            
    return image;
}

关于wpf - 如何在 WPF 中打印一组用户控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21951054/

相关文章:

Python Selenium 打印另存为 PDF 等待文件名输入

html - CSS 在打印时指定整页宽度?

c# - EF5 启动项目 :Error Running transformation: Please overwrite the replacement token '$edmxInputFile$'

c# - GCHandle.FromIntPointer 没有按预期工作

c# - 当发生某些 WPF 数据绑定(bind)更新时,有什么方法可以获取事件?

c# - 如何在 WPF 工具包日历控件中绑定(bind) BlackoutDates?

c# - 如何在 MVVM 模式 wpf 中绑定(bind) StrokeDashArray 属性

c# - 无法使用/clr 选项从 Visual C++ 项目加载 CLR

python - 打印乐谱 - Pygame

c# - 如何等待所有异步操作?