我正在寻找一个关于如何从文件加载图像并在页面上使用WPF打印的示例。我很难找到与WPF打印有关的好资料。
var bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.UriSource = new Uri("");
bi.EndInit();
var vis = new DrawingVisual();
using (var dc = vis.RenderOpen())
{
dc.DrawImage(bi, new Rect { Width = bi.Width, Height = bi.Height });
}
var pdialog = new PrintDialog();
if (pdialog.ShowDialog() == true)
{
pdialog.PrintVisual(vis, "My Image");
}
玩弄这个。
Tamir的答案是一个很好的答案,但问题是它使用了原始图像的大小。
我自己写了一个解决方案,如果图像小于页面大小,则不会拉伸图像,并将图像带到页面上,如果图像太大,则可以用于多个副本,并且可以与两种方向一起使用。
PrintDialog dlg = new PrintDialog();
if (dlg.ShowDialog() == true)
{
BitmapImage bmi = new BitmapImage(new Uri(strPath));
Image img = new Image();
img.Source = bmi;
if (bmi.PixelWidth < dlg.PrintableAreaWidth ||
bmi.PixelHeight < dlg.PrintableAreaHeight)
{
img.Stretch = Stretch.None;
img.Width = bmi.PixelWidth;
img.Height = bmi.PixelHeight;
}
if (dlg.PrintTicket.PageBorderless == PageBorderless.Borderless)
{
img.Margin = new Thickness(0);
}
else
{
img.Margin = new Thickness(48);
}
img.VerticalAlignment = VerticalAlignment.Top;
img.HorizontalAlignment = HorizontalAlignment.Left;
for (int i = 0; i < dlg.PrintTicket.CopyCount; i++)
{
dlg.PrintVisual(img, "Print a Large Image");
}
}
目前它只适用于带有路径的文件中的图片,但是通过一点工作,您可以使其适应并仅传递BitmapImage。
如果您的打印机支持无边框打印,则可以使用它。
必须使用BitmapImage的方式,因为它加载图像的默认大小。
如果直接在Windows.Controls.Image中加载图像,则不会显示正确的高度和宽度。
我知道这个问题很旧了,但是在搜索期间很难找到一些有用的信息。
希望我的帖子能帮助其他人。
...
PrintDialog printer = new PrintDialog();
if (printer.ShowDialog()) {
printer.PrintVisual(myVisual, "A Page Title");
}