c# - 用于打印的真实尺寸 WPF 控件

标签 c# wpf printing dpi zpl

我目前正在开发一个应用程序,用户可以在其中动态创建/移动 Canvas 上的 TextBlock。一旦他们将文本 block 放置在他们想要的位置,他们就可以按下打印按钮,这将导致 ZPL 打印机打印当前显示在屏幕上的内容。

ZPL 命令是通过从每个 TextBlock 中获取以下值来构建的:

  • XPosition = Canvas.Left
  • YPosition = Canvas.Right
  • 文本 = 文本

但是我找不到一种方法使打印输出类似于屏幕显示。我猜这是因为 Canvas.Left 和 Canvas.Right 的值与打印机 DPI 不匹配。

这是我当前正在使用的转换(因为我认为 Canvas.Left = 1 表示 1/96 英寸)( Canvas 的左上角是 0,0)

public double GetZplXPosition(UIElement uiElement)
{
    int dpiOfPrinter = 300;
    double zplXPosition = (Canvas.GetLeft(uiElement) / 96.0) * dpiOfPrinter;
    return zplXPosition;
}

我可以以“实际大小”显示控件吗?使用的纸张始终为 A5(8.3 英寸 x 5.8 英寸)。

我考虑过在 Canvas 周围使用 View 框,其宽度和高度设置为 830 x 580(A5 的正确比例),但这没有帮助。

有什么建议吗?

谢谢

最佳答案

不要做你正在做的事情,而是拍摄整个 Canvas 的“屏幕截图”并将其打印出来。

using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace ImageProcessing
{
    public class ImageProc
    {
        public RenderTargetBitmap GetImage(UIElement source)
        {
            double actualHeight = source.RenderSize.Height;
            double actualWidth = source.RenderSize.Width;

            if (actualHeight > 0 && actualWidth > 0)
            {
                RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)actualWidth, (int)actualHeight, 96, 96, PixelFormats.Pbgra32);
                VisualBrush sourceBrush = new VisualBrush(source);

                DrawingVisual drawingVisual = new DrawingVisual();
                DrawingContext drawingContext = drawingVisual.RenderOpen();
                drawingContext.DrawRectangle(sourceBrush, null, new Rect(0, 0, actualWidth, actualHeight));
                drawingContext.Close();

                renderTarget.Render(drawingVisual);
                return renderTarget;
            }
            else
                return null;
        }
    }
}

关于c# - 用于打印的真实尺寸 WPF 控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18218061/

相关文章:

C# 将外部程序集中的属性标记为已过时?

c# - 将 async/await 与托管插件框架结合使用

c# - 使用 ASP.NET MVC Web API 时如何注册已知类型以进行序列化

c# - 更改 .NET 4.5 WPF 功能区的主题

c# - WPF DataGrid 在编辑时预填充单元格默认值

javascript - 有没有办法跟踪用户是否打印网页?

html - 在 Firefox(最新版本)中打印预览或打印分页后元素不 float

c# - 以编程方式选择 ListBox 中的多个项目?

c# - WPF VS Collection编辑器教程?

java - 从 Android 设备通过 Wifi 访问打印机