Pregunta

I have a postscript file. How can I send it to a printer using Visual C++? This seems like it should be simple.

¿Fue útil?

Solución

If the printer supports PostScript directly you can spool a raw print jobs like this:

HANDLE ph;

OpenPrinter(&ph, "Printer Name", NULL);

di1.pDatatype = IsV4Driver("Printer Name") ? "XPS_PASS" : "RAW"; 
di1.pDocName = "Raw print document";
di1.pOutputFile = NULL;

StartDocPrinter(ph, 1, (LPBYTE)&di1);

StartPagePrinter(ph);

WritePrinter(ph, buffer, dwRead, &dwWritten);

EndPagePrinter(ph);

EndDocPrinter(ph)

Repeat the WritePrinter until you have spooled the whole file.

IsV4Driver() Checks for version 4 drivers, this is necessary in Windows 8 and Server 2012:

bool IsV4Driver(wchar_t* printerName)
{
    HANDLE handle;
    PRINTER_DEFAULTS defaults;

    defaults.DesiredAccess = PRINTER_ACCESS_USE;
    defaults.pDatatype = L"RAW";
    defaults.pDevMode = NULL;

    if (::OpenPrinter(printerName, &handle, &defaults) == 0)
    {
        return false;
    }

    DWORD version = GetVersion(handle);

    ClosePrinter(handle);

    return version == 4;
}

DWORD GetVersion(HANDLE handle)
{
    DWORD needed;

    GetPrinterDriver(handle, NULL, 2, NULL, 0, &needed);

    std::vector<char> buffer(needed);

    return ((DRIVER_INFO_2*) &buffer[0])->cVersion;
}

Otros consejos

It's more complicated than you suspect. If it's a postscript printer, connected over a serial or usb port, you can just open the device and write the file. Similarly, if it's a postscript printer connected to an Ethernet network, you can connect to port 9100 (telnet my.network.printer 9100 < pic.ps) (I may not be recalling the port number correctly, may need to sniff or do some research) and write the file.

But if it's just any old printer, then you need to interpret the postscript code and send rasterized pages to the printer.

If it's a combined PCL/PS printer, you may need to add a PCL header to enter PS mode depending on the printer settings (if it's all set to "auto-detect", don't worry about this part). You'll know to do this if you get bits of postscript code printed-out, possibly with other gobbeldegook, instead of the desired output.

I'm embarrassed to say I don't actually know how to open a usb device in windows c++, but if it helps, the DOS way was to use lpt1: as the filename (as in copy pic.ps lpt1:) which would use the device.

If it's a shared printer, you really should go through the network print queue, instead of directly to the printer.

It's not that hard. You can use LPD (Line Printer Daemon) protocol to talk to server. The protocol is simple, you can read the specification and write one by your self.

Another way is invoke the lpr command directly. However this command is disabled in windows 7 by default. Search "lpr command windows 7" will tell you how to enable it.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top