我正在编写一个新的WPF应用程序,该应用程序创建了一些视觉元素,然后尝试在Poloroid打印机上进行打印。我使用WPF中的System.Printing类成功进行了打印,如下所示:

Dim Pd As PrintDialog = New PrintDialog()
Dim Ps = New LocalPrintServer()
Dim PrintQueue = New PrintQueue(Ps, "Poloroid Printer")
Pd.PrintQueue = PrintQueue
Pd.PrintVisual(Me.Grid1, "Print Job 1")  'this prints out perfectly


问题在于,poloroid打印机具有一个SDK,可用于在卡背面的Magstrip上进行写入。我有一个使用System.Drawing.Printing中的PrintPageEventArgs的工作示例,但找不到WPF世界的任何紧密匹配项。这是该代码:

Private Sub PrintPage(ByVal sender as Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
  '...

  ' Obtain the device context for this printer
  deviceContext = e.Graphics.GetHdc().ToInt32()

  '... device context is used in SDK to write to magstrip

  e.Graphics.ReleaseHdc(New IntPtr(deviceContext))
End Sub


所以,我的问题是:

如何使用System.Drawing.Printing打印现有标记(XAML)

要么

System.Printing中是否有事件可与SDK对话并获取Int32 deviceContext?

并且我尝试RenderTargetBitmap类以将WPF中的视觉效果渲染为位图并将位图转换为System.Drawing.Bitmap

RenderTargetBitmap bitmapSource;
...
bitmapSource.Render(visual);
...
using(MemoryStream outStream = new MemoryStream())
{
 BitmapEncoder enc = new BmpBitmapEncoder();
 enc.Frames.Add(BitmapFrame.Create(bitmapSource));
 enc.Save(outStream);
 System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
 ...
}


但是印刷并不清晰和完美。

最佳答案

尝试这个

      Rect bounds = VisualTreeHelper.GetDescendantBounds(FrontCanvas);
      double dpiX =e.Graphics.DpiX  , dpiY=e.Graphics.DpiY ;
      RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX  / 96.0),
                                                      (int)(bounds.Height * dpiY   / 96.0),
                                                      dpiX,
                                                      dpiY,
                                                      PixelFormats.Pbgra32);

      DrawingVisual dv = new DrawingVisual();
      using (DrawingContext ctx = dv.RenderOpen())
      {
          VisualBrush vb = new VisualBrush(FrontCanvas);
          ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
      }

      rtb.Render(dv);

      //System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(rtb);
      //e.Graphics.DrawImage(rtb, 0, 0);

      using (MemoryStream outStream = new MemoryStream())
      {
          // Use png encoder for  data
          BitmapEncoder encoder = new PngBitmapEncoder();

          // push the rendered bitmap to it
          encoder.Frames.Add(BitmapFrame.Create(rtb));
          encoder.Save(outStream);
          System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
          e.Graphics.DrawImage(bitmap, 0, 0);

      }

07-28 03:00
查看更多