代码之家  ›  专栏  ›  技术社区  ›  Batajus

在Windows上打印不起作用

  •  1
  • Batajus  · 技术社区  · 7 年前

    目前我正在使用以下代码 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 回复  |  直到 7 年前
        1
  •  0
  •   schlebe    7 年前

    2004,我从C++程序中遇到了一系列问题。我试过使用windowsmfcapi,但效果不好。因此,我找到了另一个在2018年继续使用Visual Studio 2017的解决方案!

     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(德国的Siemens操作系统=Betrieb系统)上工作。

    此代码只有在每个PC上定义一个共享打印名为“Debug打印机”的地方才能工作,其中C++必须运行。

    std::string sDevice = "\\\\localhost\\DefaultPrinter";
    
    system(string("net use LPT1: ") + sDevice);
    system(string("print /D:LPT1 ") + sFileToPrint;
    system("net use LPT1: /delete");