duandie5707
duandie5707
2015-04-07 12:04
浏览 105
已采纳

如何打印到实际打印机?

I have a messaging server written in Go. Now I have a requirement that some messages need to be printed out on paper by the server.

How can I implement this in Go? I'm having a real hard time finding anything on the subject.

The app will be running on Windows machines and needs to be able to print UTF8 encoded text in a fixed width font. So no fancy formatting (bold text, color etc) is needed.

I'm rather completely in the dark on how to go about this... Can someone shed some light on this for me and point me in the right direction?

图片转代码服务由CSDN问答提供 功能建议

我有一个用Go语言编写的消息传递服务器。 现在,我要求服务器将某些消息打印在纸上。

如何在Go中实现此功能? 我很难找到关于该主题的任何内容。

该应用程序将在Windows计算机上运行,​​并且需要能够以固定宽度的字体打印UTF8编码的文本。 因此,不需要花哨的格式设置(粗体文本,颜色等)。

我完全不知道该如何处理...有人可以对此进行一些说明吗? 我并指出正确的方向?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duancanjiu3754
    duancanjiu3754 2015-04-08 10:52
    已采纳

    Using the answers from @abalos and @alex I was able to get this to work the way I need it to. Answering this to supply a sample of how to use it - it's pretty straightforward using alex's library:

    import prt "github.com/alexbrainman/printer"
    
    ...
    
    name, err := prt.Default() // returns name of Default Printer as string
    if err != nil {
        log.fatal(err)
    }
    p, err := prt.Open(name) // Opens the named printer and returns a *Printer
    if err != nil {
        log.fatal(err)
    }
    err = p.StartDocument("test", "text") // test: doc name, text: doc type
    if err != nil {
        log.fatal(err)
    }
    err = p.StartPage() // begin a new page
    if err != nil {
        log.fatal(err)
    }
    n, err := p.Write([]byte("Hello, Printer!")) // Send some text to the printer
    if err != nil {
        log.fatal(err)
    }
    fmt.Println("Num of bytes written to printer:", n)
    err = p.PageEnd() // end of page
    if err != nil {
        log.fatal(err)
    }
    err = p.DocumentEnd() // end of document
    if err != nil {
        log.fatal(err)
    }
    err = p.Close() // close the resource
    if err != nil {
        log.fatal(err)
    }
    

    More details on the Windows API can be found here

    点赞 评论
  • doujiao1981
    doujiao1981 2015-04-07 12:28

    It's possible to use Go to call the correct command line arguments to print whatever files are needed. You'd just need to print this information to a file first.

    Please see the information on Microsoft TechNet for this method.

    Another method I am less familiar with is to use the DLL's present in Windows through Go to invoke printing. I wasn't able to find as much information on this, but this Go documentation has some pretty good examples.

    There are a couple directions you can look in! :)

    点赞 评论

相关推荐