WPF printing of multiple pages with preview

折月煮酒 提交于 2019-12-05 13:01:59

You can print a visual to an XPS. However, as I understand it, it is your job to manage pages. If your visual is too big to fit on a page, you need to find a way to split it onto multiple pages.

The source code I posted here prints a list of items over many pages:

https://bitbucket.org/paulstovell/samples/src/a323f0c65ea4/XPS%20Report%20Generator/

If you can find a way to split your visuals (perhaps create 3 forms, with 15 items per form) into pages, you can then use this:

using (var doc = new XpsDocument("P:\\Test2.xps", FileAccess.Write))
{
    var writer = XpsDocument.CreateXpsDocumentWriter(doc);
    var collator = writer.CreateVisualsCollator();

    collator.BeginBatchWrite();
    collator.Write(form1);
    collator.Write(form2);
    collator.Write(form3);
    collator.EndBatchWrite();
}

var doc2 = new XpsDocument("P:\\Test2.xps", FileAccess.Read);

var seq = doc2.GetFixedDocumentSequence();

var window = new Window();
window.Content = new DocumentViewer {Document = seq};
window.ShowDialog();

Also, note that if you're newing up a visual and printing it, you'll need to size it first, otherwise you may get an empty screen. Here's an example of generating a page of data (of course you'd change the sizes to fit an A4 sheet).

private StackPanel CreatePage()
{
    var panel = new StackPanel();
    panel.Width = 1000;
    panel.Height = 1000;

    for (var i = 0; i < 10; i++)
    {
        panel.Children.Add(new TextBlock() {Text = "Item " + i});
    }

    panel.Measure(new Size(1000, 1000));
    panel.Arrange(new Rect(0, 0, 1000, 1000));

    return panel;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!