在Windows上无法打印

时间:2018-06-26 06:24:37

标签: c++ windows winapi printing

我正在研究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());

我的问题是打印作业在我的打印机的打印队列中显示了几毫秒(刚好足以看到),但是他什么也不打印。

有人知道我在做什么错吗?

1 个答案:

答案 0 :(得分: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");