扯淡
打印功能其实也不简单,开始使用的是Winform打印,主要是打印公司的订单,但是有个问题用户在备注的时候会加入emoji表情,比如 😔😪🤤😴 等等,因为套打需要定位每一个内容的位置,Winform使用的是Graphics对象的DrawString方法,但是遇到emoji表情确不支持,没办法困扰了很长时间,后来测试wpf的打印功能支持emoji表情,我对wpf不熟悉,只是简单的实现打印,对分页,位置控制等等完全搞不定,找了好长时间的资料都没有搞定,最后终于解决了,到最后发现真的太简单了,根本都不需要有多么高深的技术,只要方向对了,小白都能搞定专业的事情。请继续往下看。
我以为打印预览什么的正常了就可以了,实际上打印机测试 才发现,效果都不忍直视,不过好在花了几天时间,最终完美解决。
思路
创建Wpf项目 -> 编写打印代码 -> 生成 Dll文件 -> 提供给第三方语言调用(我最终是提供给JS调用打印的,项目是基于WEB端)
项目
1.创建一个WPF的项目
2.创建PrintTools.cs
其实可以使用 xaml 作为打印模板,但是我对xaml布局不太熟悉,用xaml还要设计到数据绑定,调用等等感觉非常麻烦也很难,所以就直接使用代码生成了。
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace WpfPrint
{
/// <summary>
/// 打印工具类(注意要用public修饰)
/// </summary>
public class PrintTools
{
/// <summary>
/// 对外暴露的方法
/// </summary>
/// <param name="preview">true:打印预览 false:直接打印</param>
public static void Print(bool preview = false)
{
if (preview)
{
var viewer = new DocumentViewer
{
Document = CreateDocument()
};
Window wnd = new Window
{
Content = viewer,
Title = "打印预览"
};
wnd.ShowDialog();
}
else
{
PrintDialog printDialog = new PrintDialog();
printDialog.PrintDocument(((IDocumentPaginatorSource)CreateDocument()).DocumentPaginator, "Wpf打印");
}
}
private static SolidColorBrush brush = new SolidColorBrush
{
Color = Color.FromArgb(126, 56, 86, 0)
};
/// <summary>
/// 创建文档
/// </summary>
/// <returns></returns>
private static FixedDocument CreateDocument()
{
FixedDocument fd = new FixedDocument();
FixedPage fp = new FixedPage();
PageContent pc = new PageContent();
fp.Width = 200;
fp.Height = 100;
TextBlock tb = new TextBlock();
//add some text to a TextBox object
tb.Text = "This is some test text🤤😴";
//add the text box to the FixedPage
fp.Children.Add(tb);
//add the FixedPage to the PageContent
pc.Child = fp;
//add the PageContent to the FixedDocument
fd.Pages.Add(pc);
FixedPage fp2