2

Is it possible to print a PDF file from using windows Spooler API. I tried with below code and it is not working...

int print_handle = 0;   
OpenPrinter(pPrinterName, &print_handle, NULL);
if (print_handle == 0)
{
    return 0;
}
docinfo1.pDocName = (LPTSTR)("My PDF");
docinfo1.pOutputFile = NULL;
docinfo1.pDatatype = (LPTSTR)("RAW");
temp = StartDocPrinter(print_handle, 1, &docinfo1);
temp = StartPagePrinter(print_handle);
temp = WritePrinter(print_handle, (LPBYTE)filebuff, filelen, &bytes_written);
EndPagePrinter(print_handle);
EndDocPrinter(print_handle);

WritePrinter function return SUCCESS and nothing got printed. Printing TXT and PRN file using this API is working.

DAC84
  • 421
  • 1
  • 8
  • 20

1 Answers1

5

Windows has no built-in ability to print PDF files.

You'll have to use an external application or library, e.g. Ghostscript.

I should note that because your code uses the "RAW" datatype (like the official sample) it is sending the written job data directly to the printer. ASCII data works because practically all printers can receive and print ASCII. If the printer understood PDF as a PDL (Page Description Language - other examples are PCL or PostScript), it would print your PDF. But for all other printers the PDF needs to be converted into a PDL the printer understands.

Nick Westgate
  • 3,088
  • 2
  • 34
  • 41
  • 1
    Defining PDL on first use would improve your answer. – Carey Gregory Jan 28 '18 at 05:33
  • At least can i print a DOC file or a IMG file using this API? Or for this also i need to convert it using some external library... – DAC84 Jan 29 '18 at 05:49
  • 1
    The Windows print APIs you're using are very low-level and know nothing about application-level files like PDF and DOC. Please read this [overview of Windows printing](https://learn.microsoft.com/en-us/windows-hardware/drivers/print/introduction-to-printing). Only MS Word (and a few other applications and libraries) know how to print DOC files. Images can be printed, but need higher level APIs. Even then you'll probably need a library for anything other than BMP. Google for "windows print image C++" or use .NET if you can, because that will be easier. – Nick Westgate Jan 29 '18 at 08:18
  • 1
    You can use Ghostscript to convert PDF to images. Then you can print those images – anuradha Jan 30 '21 at 11:44