首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >使用c#将txt打印到默认打印机

有没有办法使用c#向打印机发送.txt?

就像这样

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
string doc = "c:\temp.txt";
sendToPrinter(doc);
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-09-24 06:45:24

Stack Overflow用户

发布于 2017-06-28 15:10:03

评论一个旧的帖子,但由于这是弹出在谷歌搜索的前几个项目的"c#发送文本字符串到打印机“,我想我应该添加我发现的结果...省下别人几个小时的挖掘时间。

有时,我们需要将文本直接发送到打印机-- POS收据打印机、Zebra标签打印机、老式点阵打印机,向HP打印机发送PCL命令或其他转义序列,或者发送原始Postscript文件。正常的PrintDocument方法是不合适的。

微软有一篇知识库文章(322091)提供了一种这样做的方法,how-to-send-raw-data-to-a-printer-by-using-visual-c-.net

该方法涉及到以DLLimports的形式调用WinAPI的某些部分。

为了防止原始文件移动或消失,我在这里复制了该方法的核心,

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;     



private void button1_Click(object sender, System.EventArgs e)
        {
            // Allow the user to select a file.
            OpenFileDialog ofd = new OpenFileDialog();
            if( DialogResult.OK == ofd.ShowDialog(this) )
            {
                // Allow the user to select a printer.
                PrintDialog pd  = new PrintDialog();
                pd.PrinterSettings = new PrinterSettings();
                if( DialogResult.OK == pd.ShowDialog(this) )
                {
                    // Print the file to the printer.
                    RawPrinterHelper.SendFileToPrinter(pd.PrinterSettings.PrinterName, ofd.FileName);
                }
            }

    }

private void button2_Click(object sender, System.EventArgs e)
{
    string s = "Hello"; // device-dependent string, need a FormFeed?

    // Allow the user to select a printer.
    PrintDialog pd  = new PrintDialog();
    pd.PrinterSettings = new PrinterSettings();
    if( DialogResult.OK == pd.ShowDialog(this) )
    {
        // Send a printer-specific to the printer.
        RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s);
    }
}

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;
}

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;
}
public static bool SendStringToPrinter( 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.
    pBytes = Marshal.StringToCoTaskMemAnsi(szString);
    // Send the converted ANSI string to the printer.
    SendBytesToPrinter(szPrinterName, pBytes, dwCount);
    Marshal.FreeCoTaskMem(pBytes);
    return true;
}

}

票数 8
EN

Stack Overflow用户

发布于 2009-09-24 06:59:36

微软为.NET on How to: Print a Multi-Page Text File in Windows Forms提供了适用于.NET 2.03.03.54.0的更新文档。

在luvieere的回答中,它本质上是一个更新的、更完整的文档版本,它是为.NET 1.1编写的

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1472153

复制
相关文章
ubuntu gcc编译时对’xxxx’未定义的引用问题
http://www.cnblogs.com/oloroso/p/4688426.html
bear_fish
2018/09/19
8.2K0
curl和https,及openssl
如果使用curl访问https(注意不是http),则会牵涉到OpenSSL,就需要注意多线程安全问题。 一是OpenSSL需要编译成多线程安全版本,二是需要为OpenSSL注册两个回调函数。如果不这样多线程环境应用时,会遇到coredump问题。
一见
2018/08/10
1.6K0
加密通讯协议SSL编程周立发
编译程序用下列命令: gcc -Wall ssl-client.c -o client gcc -Wall ssl-server.c -o server 运行程序用如下命令: ./server 7838 1 127.0.0.1 cacert.pem privkey.pem ./client 127.0.0.1 7838 用下面这两个命令产生上述cacert.pem和privkey.pem文件: openssl genrsa -out privkey.pem 2048 openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095 具体请参考 “OpenSSL体系下使用密钥数字证书等” 如果想对SSL有更深入的了解,请学习计算机安全相关的内容,尤其是非对称加密技术。 如果想对SSL库的源代码有深入学习,请去 www.openssl.org 下载源码来阅读。
一见
2018/08/07
1.4K0
软引用和弱引用的区别_强引用软引用弱引用虚引用的区别
第一次GC的时候,软引用没有被回收,是因为这时候内存资源充足。第二次由于分配了较大的内存,导致GC,这时候由于内存资源紧张,软引用被回收了,也就是虽然User对象有一个软引用在引用着它,但User对象在此条件下也会被GC回收。所以软引用的对象在一定条件下可被回收,故软引用对象不会导致内存溢出。
全栈程序员站长
2022/10/04
1.2K0
C 和 C++ 中的未定义行为
theme: channing-cyan highlight: a11y-dark
鲸落c
2022/11/14
4.4K0
openjpeg:解决静态链接时未定义引用错误:undefined reference to `__imp_opj_xxxxxxx'
版权声明:本文为博主原创文章,转载请注明源地址。 https://blog.csdn.net/10km/article/details/50598753
10km
2019/05/25
4.6K0
openjpeg:解决静态链接时未定义引用错误:undefined reference to `__imp_opj_xxxxxxx'
nodejs的引用和导出
正如我们想的那样,nodejs每次只能运行一个js脚本,所以如果想运行多个js脚本可以采用引用(require)的方式
是小张啊喂
2021/08/10
7320
nim的引用和指针
nim语言的引用和其他语言的指针有点相似 可以提供一种“多对一”的关系 这就意味着不同的引用可以指向同一个内存位置 nim区分可被追踪的引用和不可被追踪的引用 不可被追踪的引用又称为指针 可被追踪的引用可以被垃圾回收器回收 不可被追踪的引用指向手动分配的对象,或其他地方创建出来的一块内存区域 这也就是说,不可被追踪的引用是不安全的 对于某些底层操作,不可被追踪的引用有其存在的必要 可被追踪的引用使用ref关键字定义, 不可被追踪的引用使用ptr关键字定义 空下标的方括号[]可以用来解引用 addr方法可以返
liulun
2018/01/12
9400
Python的赋值和引用
以某
2023/03/07
2K0
Python的赋值和引用
指针和引用的区别
先看代码输出是什么? 最后输出是: 1234567890 hello 指针和引用主要区别 1 在C++中,指针和引用经常用于函数的参数传递, 然而,指传递参数和引用传递参
程序员小王
2018/04/13
7340
指针和引用的区别
nodejs的引用和导出
正如我们想的那样,nodejs每次只能运行一个js脚本,所以如果想运行多个js脚本可以采用引用(require)的方式
是小张啊喂
2021/06/24
6290
【说站】java弱引用和软引用的对比
2、在垃圾回收器线程扫描管辖的存储区域的过程中,如果发现只有弱引用的对象,无论现在的存储空间是否充分,都会回收存储。但是,垃圾回收器是优先级低的线程,不一定很快就会发现只有弱引用的对象。
很酷的站长
2022/11/23
3040
【说站】java弱引用和软引用的对比
fastjson 重复引用和循环引用问题
数据传输使用json格式再方便不过了。 fastjson 由阿里巴巴那伙人使用Java语言编写,号称最快的JSON库 前两天遇到一个问题 后台的数据转化为json字符串后发送到前台出现了$ref字样的东西,后来明白了这是引用,在传输的数据中出现相同的对象时,fastjson默认开启引用检测将相同的对象写成引用的形式. 说到引用分为两种,重复引用和循环引用
Mshu
2018/10/31
2.6K0
[PHP] 对象和引用
在 PHP 5,一个对象变量已经不再保存整个对象的值。只是保存一个标识符来访问真正的对象内容。
唯一Chat
2021/06/10
5870
go的值传递和引用传递以及引用类型的问题
package main import( "fmt" ) // int string 参数传递是值传递 非引用类型 // map 参数传递是值传递 引用类型 var a int = 9 var b string = "aa" var c map[int]int func modify1(a int) { fmt.Println("值:",a) fmt.Println("地址:",&a) a = 10 fmt.Println("值:", a) fmt.Println("地址:", &a) } func modify2(a string) { fmt.Println("值:",a) fmt.Println("地址:",&a) a = "cccc" fmt.Println("值:", a) fmt.Println("地址:", &a) } func modify3(a map[int]int) { fmt.Println("值:",a) fmt.Printf("地址:%p\n",&a) a[4] = 10 fmt.Println("值:", a) fmt.Printf("地址:%p\n",&a) } func main(){ fmt.Println("值:", a) fmt.Println("地址:", &a) modify1(a) fmt.Println("值:", a) fmt.Println("地址:", &a) fmt.Println("值:", b) fmt.Println("地址:", &b) modify2(b) fmt.Println("值:", b) fmt.Println("地址:", &b) c = make(map[int]int) c[4] = 9 fmt.Println("值:", c) fmt.Printf("地址:%p\n", &c) modify3(c) fmt.Println("值:", c) fmt.Printf("地址:%p\n", &c) } //Go语言中所有的传参都是值传递(传值),都是一个副本,一个拷贝。因为拷贝的内容有时候是非引用类型(int、string、struct等这些),这样就在函数中就无法修改原内容数据;有的是引用类型(指针、map、slice、chan等这些),这样就可以修改原内容数据。是否可以修改原内容数据,和传值、传引用没有必然的关系。在C++中,传引用肯定是可以修改原内容数据的,在Go语言里,虽然只有传值,但是我们也可以修改原内容数据,因为参数是引用类型。这里也要记住,引用类型和传引用是两个概念。再记住,Go里只有传值(值传递)。
公众号-利志分享
2022/04/25
7680
强引用/软引用/弱引用/虚引用解析和应用场景分析
我们平常普通写的 Object a=new object(); 创建对象就是一种强引用 当内存不足,JVM开始垃圾回收,对于强引用的对象,就算是出现了OOM也不会对该对象进行回收
名字是乱打的
2022/05/13
6730
强引用/软引用/弱引用/虚引用解析和应用场景分析
C/C++未定义行为
下面是一段代码,这段代码中有标准未定义的行为。代码如下: #include<iostream> using namespace std; int main() { int j = 0;
zy010101
2020/04/16
3.7K0
为何 WPF 对 vcruntime140 有引用
通过阅读 WPF 官方开源仓库的代码和文档,可以了解到在进行独立发布的时候会在仓库里面带上 vcruntime140 的原因
林德熙
2020/05/09
4790
令人疑惑的引用和指针
在C++ 11中,新增了一种引用(本文都指左值引用)。从作用上来讲,它和指针类似,都可以用来间接引用对象,他们之间到底有什么异同呢?
编程珠玑
2019/09/03
6120
点击加载更多

相似问题

为C++ API编译期间,对`SSL_library_init错误的引用未定义

1316

未定义对“cudaGetDeviceCount”的引用未定义对“cudaGetDeviceProperties”的引用

10

对“加密”的未定义引用&对“解密”的未定义引用

34

对mmap和munmap的未定义引用

10

对GLShaderManager和GLBatch的引用未定义

10
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文