WPF 打印

时间:2021-03-28 13:57:05

1、

System.Windows.Controls.PrintDialog printDialog = new System.Windows.Controls.PrintDialog();
if (printDialog.ShowDialog() == true)
{

string doc =
"茶位费 3.00 1 3.00\n" +
"基围虾 0.00 1 0.00\n" +
"火爆肥肠 38.00 1 38.00\n";

Run run = new Run(doc);
TextBlock visual = new TextBlock();
visual.Inlines.Add(run);
visual.Margin = new Thickness(20, 5, 5, 5);
visual.TextWrapping = TextWrapping.Wrap;
visual.LayoutTransform = new ScaleTransform(1, 1);
Size pageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight);
visual.Measure(pageSize);
visual.Arrange(new Rect(0, 0, pageSize.Width, pageSize.Height));
printDialog.PrintVisual(visual, "doc");

}

2、

System.Windows.Controls.PrintDialog printDialog = new System.Windows.Controls.PrintDialog();
if (printDialog.ShowDialog() == true)
{

Run run = new Run("this is sad story!");

TextBlock visual = new TextBlock();
visual.Inlines.Add(run);

visual.Margin = new Thickness(15);

visual.TextWrapping = TextWrapping.Wrap;
visual.LayoutTransform = new ScaleTransform(5, 5);

Size pageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight);
visual.Measure(pageSize);

visual.Arrange(new Rect(0, 0, pageSize.Width, pageSize.Height));

printDialog.PrintVisual(visual, "A Scaled Drawing");

}

3、

WPF 中保存 window(窗口)或者canvas成图片

 

最近需要用到这个功能,搜了一下不少代码有问题 ,找到一个效果比较好的,支持多级子元素 记一下.

WPF 打印
private void button_save_window_Click(object sender, RoutedEventArgs e)
{ util.SaveWindow(this,96,"d:\\window.png");
} private void button_save_canvas_Click(object sender, RoutedEventArgs e)
{ util.SaveCanvas(this,this.canvas1, 96, "d:\\canvas.png");
}
} public static class util
{
public static void SaveWindow(Window window, int dpi, string filename)
{ var rtb = new RenderTargetBitmap(
(int)window.Width, //width
(int)window.Width, //height
dpi, //dpi x
dpi, //dpi y
PixelFormats.Pbgra32 // pixelformat
);
rtb.Render(window); SaveRTBAsPNG(rtb, filename); } public static void SaveCanvas(Window window, Canvas canvas, int dpi, string filename)
{
Size size = new Size(window.Width , window.Height );
canvas.Measure(size);
//canvas.Arrange(new Rect(size)); var rtb = new RenderTargetBitmap(
(int)window.Width, //width
(int)window.Height, //height
dpi, //dpi x
dpi, //dpi y
PixelFormats.Pbgra32 // pixelformat
);
rtb.Render(canvas); SaveRTBAsPNG(rtb, filename);
} private static void SaveRTBAsPNG(RenderTargetBitmap bmp, string filename)
{
var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp)); using (var stm = System.IO.File.Create(filename))
{
enc.Save(stm);
}
}
WPF 打印