从文件中加载图像并使用WPF打印它...怎么做?

8
我正在寻找一个关于如何从文件加载图像并在页面上使用WPF打印的示例。我很难找到与WPF打印有关的好资料。
4个回答

26
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");
}

1
Tamir...没问题。如果我需要打印多张图片,我该怎么做? - Uthistran Selvaraj.
1
截断我的图像长度。高度几乎相同,但宽度计算错误。但打印驱动程序已经正确安装。有什么建议吗? - agileDev

2
如果你想要更多的控制,那么PrintDialog.PrintVisual会给你,但你需要将你的图像包装在FixedDocument中。
你可以在这里找到创建FixedDocument的简单代码: http://www.ericsink.com/wpf3d/B_Printing.html

1

玩弄这个。

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中加载图像,则不会显示正确的高度和宽度。


我知道这个问题很旧了,但是在搜索期间很难找到一些有用的信息。
希望我的帖子能帮助其他人。


0
只需加载图像并将其应用于视觉效果。然后使用PrintDialog来完成工作。
...
PrintDialog printer = new PrintDialog();

if (printer.ShowDialog()) {
  printer.PrintVisual(myVisual, "A Page Title");
}

1
不总是会产生非常优质的输出。 - AgentFire

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接