有没有办法在WPF中打印内存集合或可变大小?

我正在使用以下代码打印ListView控件。但是当内容大于垂直滚动条接管并切割内容时。

 PrintDialog printDialog = new PrintDialog();
                printDialog.ShowDialog();

                printDialog.PrintVisual(lvDocumentSummary, "testing printing!");
有帮助吗?

解决方案

要打印多个页面,您只需要使用一个实现DocumentPaginator的类,FixedDocument是一个比较复杂的实现,FlowDocument是一个更简单的实现。

FlowDocument fd = new FlowDocument();

foreach(object item in items)
{
    fd.Blocks.Add(new Paragraph(new Run(item.ToString())));
}

fd.Print();

PrintDialog pd = new PrintDialog();
pd.PrintDocument(fd);

其他提示

FixedDocument支持DataBinding(除了FlowDocument),就像任何其他xaml文档一样。只需将listview托管在fixeddocument中,并将其显示在DocumentViewer(具有内置打印支持)中。

但是,如果您的列表对于一个页面来说太长,则FixedDocument不会自动生成新页面(如flowdocument那样)。因此,您必须使用代码手动创建新页面,因为这不能在纯xaml中完成。

如果你想要从WPF进行精美的打印,你需要构建一个FixedDocument并进行打印,不幸的是,根据你要打印的内容,它可能非常复杂。

这里有一些示例代码可以创建一个FixedDocument: http://www.ericsink.com /wpf3d/B_Printing.html

这是一个2019年答案。一些旧答案不再适用,例如。 FlowDocumentReader没有 Print 方法。

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            FlowDocument fd = new FlowDocument();
            foreach (var item in COLLECTION) //<- put your collection here
            {
                fd.Blocks.Add(new Paragraph(new Run(item.ToString())));
            }

            PrintDialog pd = new PrintDialog();
            if (pd.ShowDialog() != true) return;

            fd.PageHeight = pd.PrintableAreaHeight;
            fd.PageWidth = pd.PrintableAreaWidth;

            IDocumentPaginatorSource idocument = fd as IDocumentPaginatorSource;

            pd.PrintDocument(idocument.DocumentPaginator, "Printing Flow Document...");
        }
    }

有趣的是,ListView是虚拟化的吗?如果是,则不绘制对象,这是可能的。请参阅Petzold的示例

这是我解决这个问题的方法。它有点不稳定但适用于我的场景。

我读取了我的收藏并将其转换为字符串。整个集合现在驻留在StringBuilder对象中。接下来,我将文本/字符串看到客户端计算机上的文件中,然后使用/ p运行记事本进程以打印文件的内容。

它可以正常打印内容。

最后,有一个计时器在5秒后调用并删除该文件。基本上在5秒内,请求已经发送到打印机队列。但更好的解决方案是确保以这种方式处理打印作业,您将100%确定作业已执行。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top