打印预览并在wpf中打印

时间:2012-10-30 05:18:35

标签: c# wpf

我有一个WPF表单,我需要打印它,我使用DocumentViewer进行打印。但是当我想要打印或预览时,我只看到第一页,而我有多个页面

private void Print(object sender, RoutedEventArgs e)
{
PrintSettings printSettings = PrintSettings.Default;
UIElement container = this.Content as UIElement;
ScrollViewer containerPanel = Helper.FindVisualChildren<ScrollViewer>(container).FirstOrDefault();
var origParentDirection = containerPanel.FlowDirection;
var origDirection = (containerPanel.Content as FrameworkElement).FlowDirection;
if (containerPanel != null && containerPanel.FlowDirection == FlowDirection.RightToLeft)
{
containerPanel.FlowDirection = FlowDirection.LeftToRight;
(containerPanel.Content as FrameworkElement).FlowDirection = FlowDirection.RightToLeft;
}
var window = new Window();
string tempFileName = System.IO.Path.GetTempFileName();
System.IO.File.Delete(tempFileName);
using (XpsDocument xpsDocument = new XpsDocument(tempFileName, FileAccess.ReadWrite, System.IO.Packaging.CompressionOption.Fast))
{
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
(containerPanel.Content as FrameworkElement).Margin = new Thickness(20);
writer.Write((containerPanel.Content as FrameworkElement), printSettings.PrintTicket);
var doc = xpsDocument.GetFixedDocumentSequence();
doc.PrintTicket = printSettings.PrintTicket;       
window.FlowDirection = System.Windows.FlowDirection.RightToLeft;
window.Content = new DocumentViewer { Document = doc };
window.Margin = new Thickness(10);
window.ShowDialog();
}
(containerPanel.Content as FrameworkElement).FlowDirection = origDirection;
containerPanel.FlowDirection = origParentDirection;
}

1 个答案:

答案 0 :(得分:0)

user1780436,我目前正在寻找类似的答案。您正在尝试打印面板,对吗?

我发现缩放元素是最大的问题。这带来了另一个问题,即缩放要打印的内容而不是实际的可见元素。您必须将元素复制到新元素。

public class Copy<T>
{
    public static T DeepCopy<T>(T element)
    {
        string xaml = XamlWriter.Save(element);
        StringReader xamlString = new StringReader(xaml);
        XmlTextReader xmlTextReader = new XmlTextReader(xamlString);
        var DeepCopyobject = (T)XamlReader.Load(xmlTextReader);
        return DeepCopyobject;
    }

}

myNewElement = XamlReader.Parse(XamlWriter.Save(myOldElement.DataContext)) as ElementType

我在多个站点上反复发现这个答案来复制/克隆一个元素,但是我遇到了string xaml = XamlWriter.Save(element);导致stackoverflow问题。

我目前正在使用。

myNewElement = new ElementType() { DataContext = myOldElement.DataContext }

你在那里使用的任何一个都会成为改变元素大小的问题。这就是我要找的。

我尝试了rendering pass,但这只是指出在我的情况下使用复制/克隆元素。虽然在写这篇文章的时候我确实得到了一些工作,但是给了我一个黑色图像,请注意我正在尝试缩放图表。

myNewElement.Width = newWidth;
myNewElement.Height = newHeight;

myNewElement.Measure(new System.Windows.Size(newWidth, newHeight));
myNewElement.Arrange(new Rect(0, 0, newWidth, newHeight));

我尝试了layout pass,但没有得到它。

我将继续努力,我会发布任何我发现的新内容。如果你找到答案,请也一样。

编辑 - 这就是我所做的。 My problem and solution

相关问题