在Windows上打印不起作用

问题描述 投票:1回答:1

我正在编写一个C ++脚本,可以直接在Windows上打印。

目前我正在使用here的以下代码:

BOOL RawDataToPrinter(LPTSTR szPrinterName, LPBYTE lpData, DWORD dwCount)
{
    BOOL     bStatus = FALSE;
    HANDLE     hPrinter = NULL;
    DOC_INFO_1 DocInfo;
    DWORD      dwJob = 0L;
    DWORD      dwBytesWritten = 0L;

    bStatus = OpenPrinter(szPrinterName, &hPrinter, NULL);

    if (bStatus) {
        // Fill in the structure with info about this "document." 
        DocInfo.pDocName = (LPTSTR)_T("My Document");
        DocInfo.pOutputFile = NULL;
        DocInfo.pDatatype = (LPTSTR)_T("RAW");

        // Inform the spooler the document is beginning. 
        dwJob = StartDocPrinter(hPrinter, 1, (LPBYTE)&DocInfo);
        if (dwJob > 0) {
            // Start a page. 
            bStatus = StartPagePrinter(hPrinter);

            if (bStatus) {
                // Send the data to the printer. 
                bStatus = WritePrinter(hPrinter, lpData, dwCount, &dwBytesWritten);
                EndPagePrinter(hPrinter);
            }
            // Inform the spooler that the document is ending. 
            EndDocPrinter(hPrinter);
        }
        // Close the printer handle. 
        ClosePrinter(hPrinter);

        std::cout << GetLastError() << std::endl;
    }
    // Check to see if correct number of bytes were written. 
    if (!bStatus || (dwBytesWritten != dwCount)) {
        bStatus = FALSE;
    }
    else {
        bStatus = TRUE;
    }
    return bStatus;
}

而我正在调用方法:

std::string str = "Hello World";
BOOL blubb = RawDataToPrinter((LPTSTR)_T("PRINTER_NAME"), (LPBYTE) str.c_str(), str.size());

我遇到的问题是打印作业在我的打印机的打印队列中显示几毫秒(只是足够长),但他没有打印任何东西。

有谁知道我做错了什么?

c++ windows winapi printing
1个回答
0
投票

2004年,我遇到了从C ++程序打印文档的问题。我曾尝试使用Windows MFC API,但这不能很好地工作。所以我找到了另一个使用Visual Studio 2017继续在2018年工作的解决方案!

 XString sCmd;
 XString sDevice = "\\\\localhost\\DefaultPrinter";

 sCmd.Clear() << "net use LPT1: " << sDevice;
 iRetCode = system(sCmd);

 sCmd.Clear() << "print /D:LPT1 " << sFile;
 iRetCode = system(sCmd);

 sCmd = "net use LPT1: /delete";
 iRetCode = system(sCmd);

类XString是MFC CString增强的克隆,因此代码可以在Windows和BS2000上运行(西门子操作系统=德国的Betrieb系统)。

只有在必须运行C ++ EXE的每台PC上定义共享打印名为“DefaultPrinter”时,此代码才有效。

不使用XString,并简化一些行,代码可以是:

std::string sDevice = "\\\\localhost\\DefaultPrinter";

system(string("net use LPT1: ") + sDevice);
system(string("print /D:LPT1 ") + sFileToPrint;
system("net use LPT1: /delete");
© www.soinside.com 2019 - 2024. All rights reserved.