【问题标题】:Why do items on a child canvas not print with WPF为什么子画布上的项目不能使用 WPF 打印
【发布时间】:2015-06-24 14:16:54
【问题描述】:

试图构建一个页面以便打印。作为示例,我有以下内容 - 主要基于此 http://tech.pro/tutorial/881/printing-in-wpf

 PrintDialog printDialog = new PrintDialog();
 printDialog.PageRangeSelection = PageRangeSelection.AllPages;
 printDialog.UserPageRangeEnabled = true;
 var doPrint = printDialog.ShowDialog();
 if (doPrint == true)
 {        
            StackPanel myPanel = new StackPanel();
            myPanel.Margin = new Thickness(15);
            Image myImage = new Image();
            myImage.Width = 128;
            myImage.Stretch = Stretch.Uniform;
            myImage.Source = new BitmapImage(new Uri("C:\\Tree.jpg", UriKind.Absolute));
            myPanel.Children.Add(myImage);
            TextBlock myBlock = new TextBlock();
            myBlock.Text = "A Great Image.";
            myBlock.TextAlignment = TextAlignment.Center;
            myPanel.Children.Add(myBlock);

            Canvas canvasL = new Canvas();

            canvasL.Width = 300;
            canvasL.Height = 300;
            canvasL.Background = Brushes.LightSteelBlue;
            myPanel.Children.Add(canvasL);

            Line l = new Line();
            l.X1 = 0;
            l.Y1 = 0;
            l.Y1 = 10000;
            l.Y2 = 10000;

            l.Stroke = Brushes.Black;
            l.StrokeThickness = 5;

            canvasL.Children.Add(l);

            myPanel.Measure(new Size(printDialog.PrintableAreaWidth,
              printDialog.PrintableAreaHeight));
            myPanel.Arrange(new Rect(new Point(0, 0),
              myPanel.DesiredSize));

            printDialog.PrintVisual(myPanel, "A Great Image.");
}

图片显示。文字显示。画布显示为钴蓝色方块 - 但无处可见。

什么给了?

【问题讨论】:

    标签: c# wpf canvas printing


    【解决方案1】:

    您需要使用附加属性在画布上设置子项的位置。例如

    l.SetValue(Canvas.TopProperty, 10d);
    l.SetValue(Canvas.LeftProperty, 10d);
    l.SetValue(Canvas.RightProperty, 100d);
    l.SetValue(Canvas.BottomProperty, 100d);
    

    【讨论】:

    • "l" 没有 SetProperty,所​​以我有点困惑。 X1/Y1 X2/Y2 对设置是否不足以让它知道如何渲染?只要在屏幕上就足够了..
    • Canvas.SetTop(l, 10d);也不 l.SetValue(Canvas.TopProperty, 10d);有所作为。
    • 我又更新了——所有属性都需要设置。
    • 可悲的是,似乎没有帮助。我试过打印到“真正的”打印机和 OneNote(只是为了检查它不是驱动程序问题),但我仍然只得到一个蓝色方块
    【解决方案2】:

    啊。木偶戏。

    所以这个简单的例子是错误的,因为它设置了 Y1 两次。修复它,它就可以工作了。

    我更复杂的情况是使用 ActualWidth,它在打印时为 0(与在主 UI 中不同),因此没有显示任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多