using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Printing;
using System.Runtime.InteropServices;

namespace BarCodePrintApi
{
public class RawPrinterHelper
{
// Structure and API declarions:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)]
public string pDocName;
[MarshalAs(UnmanagedType.LPStr)]
public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)]
public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.

di.pDocName = "My C#.NET RAW Document";
di.pDataType = "RAW";

// Open the printer.
if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
{
// Start a document.
if (StartDocPrinter(hPrinter, 1, di))
{
// Start a page.
if (StartPagePrinter(hPrinter))
{
// Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if (bSuccess == false)
{
dwError = Marshal.GetLastWin32Error();
}
return bSuccess;
}

/// <summary>
/// 发送文件到打印机
/// </summary>
/// <param name="szPrinterName">打印机名称</param>
/// <param name="szFileName">文件</param>
/// <returns></returns>
public static bool SendFileToPrinter(string szPrinterName, string szFileName)
{
// Open the file.
FileStream fs = new FileStream(szFileName, FileMode.Open);
// Create a BinaryReader on the file.
BinaryReader br = new BinaryReader(fs);
// Dim an array of bytes big enough to hold the file's contents.
Byte[] bytes = new Byte[fs.Length];
bool bSuccess = false;
// Your unmanaged pointer.
IntPtr pUnmanagedBytes = new IntPtr(0);
int nLength;

nLength = Convert.ToInt32(fs.Length);
// Read the contents of the file into the array.
bytes = br.ReadBytes(nLength);
// Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
// Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);
return bSuccess;
}

/// <summary>
/// 发送字符串到打印机
/// </summary>
/// <param name="szPrinterName">打印机名称</param>
/// <param name="szString">指令</param>
/// <returns></returns>
public static bool SendStringToPrinter1(string szPrinterName, string szString)
{
IntPtr pBytes;
Int32 dwCount;
// How many characters are in the string?
dwCount = szString.Length;
// Assume that the printer is expecting ANSI text, and then convert
// the string to ANSI text.
//Encoding.GetEncoding("GB2312").GetBytes(szString);
pBytes = Marshal.StringToCoTaskMemAnsi(szString);

// Send the converted ANSI string to the printer.
SendBytesToPrinter(szPrinterName, pBytes, dwCount);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
/// <summary>
/// 打印标签带有中文字符的ZPL指令
/// </summary>
/// <param name="printerName">打印机名称</param>
/// <param name="szString">指令</param>
/// <returns></returns>
public static string SendStringToPrinter(string printerName, string szString)
{
byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(szString); //转换格式
IntPtr ptr = Marshal.AllocHGlobal(bytes.Length + 2);
try
{
Marshal.Copy(bytes, 0, ptr, bytes.Length);
SendBytesToPrinter(printerName, ptr, bytes.Length);
return "success";
}
catch(Exception ex)
{
return ex.Message;
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}

/// <summary>
/// 网络打印
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <param name="szString"></param>
/// <returns></returns>
public static string SendStringToNetPrinter(string ip, int port, string szString)
{
try
{
//打开连接
System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
client.Connect(ip, port);

//写入zpl命令
System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
writer.Write(szString);
writer.Flush();

//关闭连接
writer.Close();
client.Close();

return "success";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}

ZPL打印机公用代码的更多相关文章

  1. SVN 外部引用(svn:externals)处理相似系统的公用代码

    一.创建外部引用 我们常常遇到这样一个场景,我们有两个系统,两个系统用的是同一套框架.如果我们用两套程序 去做,当我们修改这个公共的框架的时候,另外一个还是旧版本的,很容易造成混乱. SVN的外部用就 ...

  2. 静态页面如何实现 include 引入公用代码

    一直以来,我司的前端都是用 php 的 include 函数来实现引入 header .footer 这些公用代码的,就像下面这样: <!-- index.php --> <!DOC ...

  3. webpack4 自学笔记三(提取公用代码)

    全部的代码及笔记都可以在我的github上查看, 欢迎star:https://github.com/Jasonwang911/webpackStudyInit/tree/master/commonT ...

  4. Smtp邮件发送系统公用代码整理—总结

    1.前言 a.在软件开发中,我们经常能够遇到给用户或者客户推送邮件,推送邮件也分为很多方式,比如:推送一句话,推送一个网页等等.那么在系统开发中我们一般在什么情况下会使用邮件发送呢?下面我简单总结了一 ...

  5. Asp.net MVC 视图之公用代码

    一.公共模板 转自:http://www.cnblogs.com/kissdodog/archive/2013/01/07/2848881.html 1.@RenderBody() 在网站公用部分通过 ...

  6. 基于 Koa平台Node.js开发的KoaHub.js连接打印机的代码

    最近好多小伙伴都在做微信商城的项目,那就给大家分享一个基于 Koa.js 平台的 Node.js web 开发的框架连接微信易联云打印机接口的代码,供大家学习.koahub-yilianyun 微信易 ...

  7. MVC 5 视图之公用代码

    一.公共模板 1.@RenderBody() 在网站公用部分通过一个占位符@RenderBody()来为网站独立部分预留一个位置.然后私有页面顶部通过@{Layout="公用模板路径&quo ...

  8. 20190626_二次开发BarTender打印机_C#代码_一边读取TID_一边打印_打印机POSTEK

    demo代码如下: private void btnPrint_Click(object sender, EventArgs e) { if (this.btnPrint.Text == " ...

  9. mybatis公用代码抽取到单独的mapper.xml文件

    同任何的代码库一样,在mapper中,通常也会有一些公共的sql代码段会被很多业务mapper.xml引用到,比如最常用的可能是分页和数据权限过滤了,尤其是在oracle中的分页语法.为了减少骨架性代 ...

随机推荐

  1. requestLayout, invalidate和postInvalidate的异同

    requestLayout 当一个VIEW的布局属性发生了变化的时候,可以调用该方法,让父VIEW调用onmeasure 和onlayout重新定位该view的位置,需要在UI线程调用 invalid ...

  2. css自动换行 word-break:break-all和word-wrap:break-word(转)

    css自动换行 word-break:break-all和word-wrap:break-word 2012-12-31 17:30 by greenal, 159 阅读, 0 评论, 收藏, 编辑 ...

  3. Python 使用其他邮件服务商的 SMTP 访问(QQ、网易、163、Google等)发送邮件

    163邮箱SMTP授权 使用Python SMTP发送邮件 # -*- coding:utf-8 -*- from __future__ import print_function __author_ ...

  4. JDK并发包2-线程池

  5. p3172 选数

    传送门 分析 对这个$f(k)$整除分块,用杜教筛搞出$\mu$的部分然后另一部分快速幂即可 代码 #include<iostream> #include<cstdio> #i ...

  6. 《Head First Servlets & JSP》-13-过滤器和包装器

    过滤器是什么 与servlet非常类似,过滤器就是java组件,请求发送到servlet之前,可以用过滤器截获和处理清求,另外 servlet结束工作之后,在响应发回给客户之前,可以用过滤器处理响应. ...

  7. Visual Studio 代码格式化插件(等号自动对齐、注释自动对齐等)

    1.下载地址 插件:Code alignment  下载地址 2.介绍 Based on principles borrowed from mathematics and other discipli ...

  8. c# get set 理解

  9. DjVu转PDG的方法与步骤

    作者:马健邮箱:stronghorse_mj@hotmail.com发布:2008.08.03更新:2008.08.24 补充说明:此文成文较早,当时PDG浏览器只支持纯正PDG,不支持名为PDG,实 ...

  10. selenium自动化测试、Python单元测试unittest框架以及测试报告和日志输出

    部分内容来自:https://www.cnblogs.com/klb561/p/8858122.html 一.基础介绍 核心概念:test case, testsuite, TestLoder,Tex ...