我想编写一个WPF程序,其中我想打印程序/窗口的特定部分。我只想要打印画布。 不幸的是整个窗口一直打印,但我只想要打印画布。
这是我的代码:
public partial class MainWindow : Window
{
string name;
public MainWindow()
{
InitializeComponent();
}
private void Text(double x, double y, string text)
{
canvasPrintExample.Children.Clear();
TextBlock textBlock = new TextBlock();
textBlock.Text = text;
textBlock.Foreground = new SolidColorBrush(Colors.Black);
Canvas.SetLeft(textBlock, x);
Canvas.SetTop(textBlock, y);
canvasPrintExample.Children.Add(textBlock);
}
private void tbxClientInfoName_TextChanged(object sender, TextChangedEventArgs e)
{
clientInfoName = tbxClientInfoName.Text;
Text(0, 0, name);
}
private void btnPrintCanvas_Click(object sender, RoutedEventArgs e)
{
PrintDialog prnt = new PrintDialog();
if (prnt.ShowDialog() == true)
{
Size pageSize = new Size(prnt.PrintableAreaWidth, prnt.PrintableAreaHeight);
canvasPrintExample.Measure(pageSize);
canvasPrintExample.Arrange(new Rect(0, 0, pageSize.Width, pageSize.Height));
prnt.PrintVisual(canvasPrintExample, "Print");
}
this.Close();
}
}
我尝试在'btnPrintCanvas_Click'
中更改此行Size pageSize = new Size(canvasPrintExample.Width, canvasPrintExample.Height);
我尝试过硬编码: 尺寸pageSize =新尺寸(200,400);
编辑 - 添加.xaml
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Factv001"
mc:Ignorable="d"
Title="MainWindow" Height="810" Width="1010" Background="LightGray">
<Grid>
<Canvas Name="canvasPrintExample" HorizontalAlignment="Left" Height="750" Margin="452,10,0,0" VerticalAlignment="Top" Width="530.3" Background="White"/>
<TextBox Name="tbxClientInfoName" HorizontalAlignment="Left" Height="23" Margin="10,31,0,0" TextWrapping="Wrap" Text="Name" VerticalAlignment="Top" Width="225" TextChanged="tbxClientInfoName_TextChanged"/>
<Button x:Name="btnPrintCanvas" Content="Print" HorizontalAlignment="Left" Margin="167,682,0,0" VerticalAlignment="Top" Width="75" Click="btnPrintCanvas_Click"/>
</Grid>