1. 程式人生 > >C# 呼叫印表機列印圖片

C# 呼叫印表機列印圖片

是基於WPF的。
具體程式碼如下,列印時會有一個小彈窗一閃而過,還在繼續找辦法改進
由於目前使用的方法所需的變數型別和程式裡需要列印的圖片的變數型別不一樣,所以這裡我將需要列印的照片先儲存為檔案,然後再讀取進來。

 private void button4_Click(object sender, RoutedEventArgs e)
        {
            MainBitmap = (BitmapImage)image.Source;

            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames
.Add(BitmapFrame.Create(MainBitmap)); FileStream files = new FileStream("1.jpg", FileMode.Create, FileAccess.ReadWrite); encoder.Save(files); files.Close(); PrintDocument pd = new PrintDocument(); pd.DefaultPageSettings.PrinterSettings.PrinterName
= "Canon SELPHY CP1200"; PaperSize psize = new PaperSize(); foreach (PaperSize i in pd.PrinterSettings.PaperSizes) { if (i.PaperName == "P 無邊距 100x148mm 4x6\"") //無邊距可正常居中,有邊距0,0點位置需考慮邊距 { psize = i; break
; } Console.WriteLine(i.PaperName); } pd.DefaultPageSettings.PaperSize = psize; pd.PrintPage += (s, args) => { System.Drawing.Image i = System.Drawing.Image.FromFile("1.jpg"); System.Drawing.Rectangle m = args.PageBounds; if (i.Width < i.Height) i.RotateFlip(RotateFlipType.Rotate90FlipNone); if (i.Width >= i.Height) { if ((double)i.Width / (double)i.Height <= (double)m.Width / (double)m.Height) { int w = (int)((double)i.Width / (double)i.Height * (double)m.Height); int dx = (m.Width - w) / 2; m.X = dx; m.Y = 0; m.Width = w; } else { int h = (int)((double)i.Height / (double)i.Width * (double)m.Width); int dy = (m.Height - h) / 2; m.X = 0; m.Y = dy; m.Height = h; } } args.Graphics.DrawImage(i, m); }; pd.Print(); }